diff --git a/examples/go/custody_transfer.go b/examples/go/custody_transfer.go new file mode 100644 index 000000000..a31a6d5f6 --- /dev/null +++ b/examples/go/custody_transfer.go @@ -0,0 +1,93 @@ +package main + +import ( + "context" + "fmt" + "log" + + "github.com/coinbase/cdp-sdk/go/openapi" +) + +func CustodyTransferExample() { + ctx := context.Background() + + client, err := createCDPClient() + if err != nil { + log.Fatalf("Failed to create CDP client: %v", err) + } + + // 1. List accounts + accountsResp, err := client.ListFoundationAccountsWithResponse(ctx, &openapi.ListFoundationAccountsParams{}) + if err != nil { + log.Fatalf("Failed to list accounts: %v", err) + } + if accountsResp.JSON200 == nil { + log.Fatalf("Failed to list accounts: %s", string(accountsResp.Body)) + } + accounts := accountsResp.JSON200.Accounts + fmt.Printf("Found %d accounts:\n", len(accounts)) + for _, account := range accounts { + fmt.Printf(" %s (%s) - type: %s\n", account.AccountId, account.Name, account.Type) + } + + if len(accounts) == 0 { + fmt.Println("No accounts found. Create one in the CDP dashboard first.") + return + } + + // 2. Get balances for the first account + account := accounts[0] + balancesResp, err := client.ListBalancesWithResponse(ctx, account.AccountId, &openapi.ListBalancesParams{}) + if err != nil { + log.Fatalf("Failed to list balances: %v", err) + } + fmt.Printf("\nBalances for %s:\n", account.Name) + for _, balance := range balancesResp.JSON200.Balances { + fmt.Printf(" %s: %s\n", balance.Asset, balance.Amount) + } + + // 3. Create a quoted transfer (execute=false — no funds move) + var source openapi.CreateTransferSource + if err := source.FromTransfersAccount(openapi.TransfersAccount{ + AccountId: account.AccountId, + Asset: "usd", + }); err != nil { + log.Fatalf("Failed to build transfer source: %v", err) + } + + var target openapi.TransferTarget + if err := target.FromOnchainAddress(openapi.OnchainAddress{ + Address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + Network: "base", + Asset: "usdc", + }); err != nil { + log.Fatalf("Failed to build transfer target: %v", err) + } + + transferResp, err := client.CreateTransferWithResponse(ctx, &openapi.CreateTransferParams{}, + openapi.CreateTransferJSONRequestBody{ + Source: source, + Target: target, + Amount: "10.00", + Asset: "usd", + Execute: false, + }, + ) + if err != nil { + log.Fatalf("Failed to create transfer: %v", err) + } + transfer := transferResp.JSON200 + fmt.Printf("\nCreated transfer %s:\n", transfer.TransferId) + fmt.Printf(" Status: %s\n", transfer.Status) + fmt.Printf(" Source: %s %s\n", transfer.SourceAmount, transfer.SourceAsset) + fmt.Printf(" Target: %s %s\n", transfer.TargetAmount, transfer.TargetAsset) + fmt.Printf(" Expires: %s\n", transfer.ExpiresAt) + + // 4. List recent transfers + status := openapi.TransferStatus("quoted") + transfersResp, err := client.ListTransfersWithResponse(ctx, &openapi.ListTransfersParams{Status: &status}) + if err != nil { + log.Fatalf("Failed to list transfers: %v", err) + } + fmt.Printf("\n%d quoted transfers found.\n", len(transfersResp.JSON200.Transfers)) +} diff --git a/examples/go/go.mod b/examples/go/go.mod index 53fe6190e..bc35effce 100644 --- a/examples/go/go.mod +++ b/examples/go/go.mod @@ -1,6 +1,6 @@ module example.com/m/v2 -go 1.24.0 +go 1.24.3 require ( github.com/coinbase/cdp-sdk/go v0.0.0-20251024190004-8f3878c202dc @@ -27,7 +27,7 @@ require ( github.com/google/uuid v1.6.0 // indirect github.com/gorilla/websocket v1.4.2 // indirect github.com/holiman/uint256 v1.3.2 // indirect - github.com/oapi-codegen/runtime v1.1.1 // indirect + github.com/oapi-codegen/runtime v1.4.1 // indirect github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible // indirect github.com/supranational/blst v0.3.16 // indirect github.com/tklauser/go-sysconf v0.3.12 // indirect @@ -40,3 +40,5 @@ require ( golang.org/x/sync v0.18.0 // indirect golang.org/x/sys v0.41.0 // indirect ) + +replace github.com/coinbase/cdp-sdk/go => ../../go diff --git a/examples/go/go.sum b/examples/go/go.sum index d0b90e681..09630ba53 100644 --- a/examples/go/go.sum +++ b/examples/go/go.sum @@ -30,8 +30,6 @@ github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwP github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 h1:zuQyyAKVxetITBuuhv3BI9cMrmStnpT18zmgmTxunpo= github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06/go.mod h1:7nc4anLGjupUW/PeY5qiNYsdNXj7zopG+eqsS7To5IQ= -github.com/coinbase/cdp-sdk/go v0.0.0-20251024190004-8f3878c202dc h1:nkYJEEEHRIHYqkdXD74cK0RhlKRDlQ3gIlw6OG5+dOU= -github.com/coinbase/cdp-sdk/go v0.0.0-20251024190004-8f3878c202dc/go.mod h1:7SCUyseVQvmT158f23xvVghYF7dYxypj0sw+558F+7g= github.com/consensys/gnark-crypto v0.19.2 h1:qrEAIXq3T4egxqiliFFoNrepkIWVEeIYwt3UL0fvS80= github.com/consensys/gnark-crypto v0.19.2/go.mod h1:rT23F0XSZqE0mUA0+pRtnL56IbPxs6gp4CeRsBk4XS0= github.com/cpuguy83/go-md2man/v2 v2.0.5 h1:ZtcqGrnekaHpVLArFSe4HK5DoKx1T0rq2DwVB0alcyc= @@ -39,8 +37,8 @@ github.com/cpuguy83/go-md2man/v2 v2.0.5/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46t github.com/crate-crypto/go-eth-kzg v1.4.0 h1:WzDGjHk4gFg6YzV0rJOAsTK4z3Qkz5jd4RE3DAvPFkg= github.com/crate-crypto/go-eth-kzg v1.4.0/go.mod h1:J9/u5sWfznSObptgfa92Jq8rTswn6ahQWEuiLHOjCUI= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dchest/siphash v1.2.3 h1:QXwFc8cFOR2dSa/gE6o/HokBMWtLUaNDVd+22aKHeEA= github.com/dchest/siphash v1.2.3/go.mod h1:0NvQU092bT0ipiFN++/rXm69QG9tVxLAlQHIXMPAkHc= github.com/deckarep/golang-set/v2 v2.6.0 h1:XfcQbWM1LlMB8BsJ8N9vW5ehnnPVIw0je80NsVHagjM= @@ -108,8 +106,8 @@ github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwA github.com/juju/gnuflag v0.0.0-20171113085948-2ce1bb71843d/go.mod h1:2PavIy+JPciBPrBUjwbNvtwB6RQlve+hkpll6QSNmOE= github.com/klauspost/compress v1.17.8 h1:YcnTYrq7MikUT7k0Yb5eceMmALQPYBW/Xltxn0NAMnU= github.com/klauspost/compress v1.17.8/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= -github.com/klauspost/cpuid/v2 v2.2.5 h1:0E5MSMDEoAulmXNFquVs//DdoomxaoTY1kUhbc/qbZg= -github.com/klauspost/cpuid/v2 v2.2.5/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM= +github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -118,8 +116,8 @@ github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0 github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/leanovate/gopter v0.2.11 h1:vRjThO1EKPb/1NsDXuDrzldR28RLkBflWYcU9CvzWu4= github.com/leanovate/gopter v0.2.11/go.mod h1:aK3tzZP/C+p1m3SPRE4SYZFGP7jjkuSI4f7Xvpt0S9c= -github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= -github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= +github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo= @@ -130,8 +128,10 @@ github.com/mitchellh/mapstructure v1.4.1 h1:CpVNEelQCZBooIPDn+AR3NpivK/TIKU8bDxd github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/pointerstructure v1.2.0 h1:O+i9nHnXS3l/9Wu7r4NrEdwA2VFTicjUEN1uBnDo34A= github.com/mitchellh/pointerstructure v1.2.0/go.mod h1:BRAsLI5zgXmw97Lf6s25bs8ohIXc3tViBH44KcwB2g4= -github.com/oapi-codegen/runtime v1.1.1 h1:EXLHh0DXIJnWhdRPN2w4MXAzFyE4CskzhNLUmtpMYro= -github.com/oapi-codegen/runtime v1.1.1/go.mod h1:SK9X900oXmPWilYR5/WKPzt3Kqxn/uS/+lbpREv+eCg= +github.com/oapi-codegen/nullable v1.1.0 h1:eAh8JVc5430VtYVnq00Hrbpag9PFRGWLjxR1/3KntMs= +github.com/oapi-codegen/nullable v1.1.0/go.mod h1:KUZ3vUzkmEKY90ksAmit2+5juDIhIZhfDl+0PwOQlFY= +github.com/oapi-codegen/runtime v1.4.1 h1:9nwLoI+KrWxzbBcp0jO/R8uXqbik/HUyCvPeU68Y/qo= +github.com/oapi-codegen/runtime v1.4.1/go.mod h1:GwV7hC2hviaMzj+ITfHVRESK5J2W/GefVwIND/bMGvU= github.com/pion/dtls/v2 v2.2.7 h1:cSUBsETxepsCSFSxC3mc/aDo14qQLMSL+O6IjG28yV8= github.com/pion/dtls/v2 v2.2.7/go.mod h1:8WiMkebSHFD0T+dIU+UeBaoV7kDhOW5oDCzZ7WZ/F9s= github.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY= @@ -144,8 +144,9 @@ github.com/pion/transport/v3 v3.0.1 h1:gDTlPJwROfSfz6QfSi0ZmeCSkFcnWWiiR9ES0ouAN github.com/pion/transport/v3 v3.0.1/go.mod h1:UY7kiITrlMv7/IKgd5eTUcaahZx5oUN3l9SzK5f5xE0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_golang v1.15.0 h1:5fCgGYogn0hFdhyhLbw7hEsWxufKtY9klyvdNfFlFhM= github.com/prometheus/client_golang v1.15.0/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= github.com/prometheus/client_model v0.3.0 h1:UBgGFHqYdG/TPFD1B1ogZywDqEkwp3fBMvqdiQ7Xew4= @@ -191,8 +192,8 @@ go.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6 go.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA= golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts= golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos= -golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df h1:UA2aFVmmsIlefxMk29Dp2juaUSth8Pyn3Tq5Y5mJGME= -golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= +golang.org/x/exp v0.0.0-20240404231335-c0f41cb1a7a0 h1:985EYyeCOxTpcgOTJpflJUwOeEz0CQOdPt73OzpE9F8= +golang.org/x/exp v0.0.0-20240404231335-c0f41cb1a7a0/go.mod h1:/lliqkxwWAhPjf5oSOIJup2XcqJaw8RGS6k3TGEc7GI= golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I= golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -203,8 +204,8 @@ golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= -golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY= -golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= +golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= diff --git a/examples/go/main.go b/examples/go/main.go index c5f961b96..2ef75f860 100644 --- a/examples/go/main.go +++ b/examples/go/main.go @@ -18,6 +18,8 @@ func main() { SendTransactionExample() case "send_user_operation": SendUserOperationExample() + case "custody_transfer": + CustodyTransferExample() default: fmt.Printf("Unknown example: %s\n", exampleName) printUsage() @@ -30,4 +32,5 @@ func printUsage() { fmt.Println("Available examples:") fmt.Println(" send_transaction - Create an EVM account and send a transaction") fmt.Println(" send_user_operation - Create a smart account and send a user operation") -} \ No newline at end of file + fmt.Println(" custody_transfer - List custody accounts and create a quoted transfer") +} diff --git a/examples/java/build.gradle.kts b/examples/java/build.gradle.kts index 484df517e..d97331bc2 100644 --- a/examples/java/build.gradle.kts +++ b/examples/java/build.gradle.kts @@ -129,6 +129,13 @@ tasks.register("runRetryConfiguration") { classpath = sourceSets["main"].runtimeClasspath } +tasks.register("runCustodyTransfer") { + group = "examples" + description = "List custody accounts and create a quoted transfer" + mainClass.set("com.coinbase.cdp.examples.custody.ListAccountsAndTransfer") + classpath = sourceSets["main"].runtimeClasspath +} + // Task to list all available example tasks tasks.register("listExamples") { group = "examples" @@ -148,6 +155,7 @@ tasks.register("listExamples") { println(" ./gradlew runListSolanaAccounts - List Solana accounts") println(" ./gradlew runSolanaTransfer - Transfer SOL between accounts") println(" ./gradlew runRetryConfiguration - Configure HTTP retry behavior") + println(" ./gradlew runCustodyTransfer - List custody accounts and create a quoted transfer") println("\nOr run any example directly:") println(" ./gradlew run -PmainClass=com.coinbase.cdp.examples.evm.CreateAccount") } diff --git a/examples/java/src/main/java/com/coinbase/cdp/examples/custody/ListAccountsAndTransfer.java b/examples/java/src/main/java/com/coinbase/cdp/examples/custody/ListAccountsAndTransfer.java new file mode 100644 index 000000000..6d0060155 --- /dev/null +++ b/examples/java/src/main/java/com/coinbase/cdp/examples/custody/ListAccountsAndTransfer.java @@ -0,0 +1,86 @@ +package com.coinbase.cdp.examples.custody; + +import com.coinbase.cdp.CdpClient; +import com.coinbase.cdp.examples.utils.EnvLoader; +import com.coinbase.cdp.openapi.api.AccountsApi; +import com.coinbase.cdp.openapi.api.TransfersApi; +import com.coinbase.cdp.openapi.model.CreateTransferSource; +import com.coinbase.cdp.openapi.model.Network; +import com.coinbase.cdp.openapi.model.OnchainAddress; +import com.coinbase.cdp.openapi.model.TransferRequest; +import com.coinbase.cdp.openapi.model.TransferStatus; +import com.coinbase.cdp.openapi.model.TransferTarget; +import com.coinbase.cdp.openapi.model.TransfersAccount; + +/** + * Example: Flexible Custody API flow. + * + *

Demonstrates listing accounts, checking balances, creating a quoted transfer, + * and listing recent transfers using the auto-generated OpenAPI client. + * + *

Usage: ./gradlew runCustodyTransfer + */ +public class ListAccountsAndTransfer { + + public static void main(String[] args) throws Exception { + EnvLoader.load(); + + try (CdpClient cdp = CdpClient.create()) { + var apiClient = cdp.getApiClient(); + AccountsApi accountsApi = new AccountsApi(apiClient); + TransfersApi transfersApi = new TransfersApi(apiClient); + + // 1. List accounts + var accountsResponse = accountsApi.listFoundationAccounts(null, null, null); + var accounts = accountsResponse.getAccounts(); + System.out.printf("Found %d accounts:%n", accounts.size()); + for (var account : accounts) { + System.out.printf(" %s (%s) - type: %s%n", + account.getAccountId(), account.getName(), account.getType()); + } + + if (accounts.isEmpty()) { + System.out.println("No accounts found. Create one in the CDP dashboard first."); + return; + } + + // 2. Get balances for the first account + var account = accounts.get(0); + var balancesResponse = accountsApi.listBalances(account.getAccountId(), null, null); + System.out.printf("%nBalances for %s:%n", account.getName()); + for (var balance : balancesResponse.getBalances()) { + System.out.printf(" %s: %s%n", balance.getAsset(), balance.getAmount()); + } + + // 3. Create a quoted transfer (execute=false — no funds move) + var source = new CreateTransferSource(); + source.setActualInstance(new TransfersAccount().accountId(account.getAccountId()).asset("usd")); + + var target = new TransferTarget(); + target.setActualInstance(new OnchainAddress() + .address("0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913") + .network(Network.BASE) + .asset("usdc")); + + var transferRequest = new TransferRequest() + .source(source) + .target(target) + .amount("10.00") + .asset("usd") + .execute(false); + + var transfer = transfersApi.createTransfer(null, transferRequest); + System.out.printf("%nCreated transfer %s:%n", transfer.getTransferId()); + System.out.printf(" Status: %s%n", transfer.getStatus()); + System.out.printf(" Source: %s %s%n", transfer.getSourceAmount(), transfer.getSourceAsset()); + System.out.printf(" Target: %s %s%n", transfer.getTargetAmount(), transfer.getTargetAsset()); + System.out.printf(" Expires: %s%n", transfer.getExpiresAt()); + + // 4. List recent transfers + var transfersResponse = transfersApi.listTransfers( + TransferStatus.QUOTED, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); + System.out.printf("%n%d quoted transfers found.%n", + transfersResponse.getTransfers().size()); + } + } +} diff --git a/examples/python/custody/list_accounts_and_transfer.py b/examples/python/custody/list_accounts_and_transfer.py new file mode 100644 index 000000000..709239aaf --- /dev/null +++ b/examples/python/custody/list_accounts_and_transfer.py @@ -0,0 +1,69 @@ +# Usage: uv run python custody/list_accounts_and_transfer.py +# +# Demonstrates the Flexible Custody API flow: +# 1. List accounts +# 2. Get balances for the first account +# 3. Create a quoted transfer (not executed) +# 4. List recent transfers + +import asyncio + +from cdp import CdpClient +from cdp.openapi_client.api.accounts_api import AccountsApi +from cdp.openapi_client.api.transfers_api import TransfersApi +from cdp.openapi_client.models import TransferRequest +from dotenv import load_dotenv + +load_dotenv() + + +async def main(): + async with CdpClient() as cdp: + api_client = cdp.cdp_api_client + accounts_api = AccountsApi(api_client) + transfers_api = TransfersApi(api_client) + + # 1. List accounts + response = await accounts_api.list_foundation_accounts() + accounts = response.accounts + print(f"Found {len(accounts)} accounts:") + for account in accounts: + print(f" {account.account_id} ({account.name}) - type: {account.type}") + + if not accounts: + print("No accounts found. Create one in the CDP dashboard first.") + return + + # 2. Get balances for the first account + account = accounts[0] + balances_response = await accounts_api.list_balances(account.account_id) + print(f"\nBalances for {account.name}:") + for balance in balances_response.balances: + print(f" {balance.asset}: {balance.amount}") + + # 3. Create a quoted transfer (execute=False — no funds move) + transfer = await transfers_api.create_transfer( + transfer_request=TransferRequest( + source={"accountId": account.account_id, "asset": "usd"}, + target={ + "address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + "network": "base", + "asset": "usdc", + }, + amount="10.00", + asset="usd", + execute=False, + ) + ) + print(f"\nCreated transfer {transfer.transfer_id}:") + print(f" Status: {transfer.status}") + print(f" Source: {transfer.source_amount} {transfer.source_asset}") + print(f" Target: {transfer.target_amount} {transfer.target_asset}") + print(f" Expires: {transfer.expires_at}") + + # 4. List recent transfers + transfers_response = await transfers_api.list_transfers(status="quoted") + print(f"\n{len(transfers_response.transfers)} quoted transfers found.") + + +asyncio.run(main()) diff --git a/examples/python/uv.lock b/examples/python/uv.lock index e392d146a..b2d7ec58e 100644 --- a/examples/python/uv.lock +++ b/examples/python/uv.lock @@ -286,7 +286,7 @@ wheels = [ [[package]] name = "cdp-sdk" -version = "1.41.0" +version = "1.45.1" source = { editable = "../../python" } dependencies = [ { name = "aiohttp" }, @@ -326,7 +326,7 @@ requires-dist = [ { name = "sphinxcontrib-napoleon", marker = "extra == 'dev'", specifier = ">=0.7" }, { name = "towncrier", marker = "extra == 'dev'", specifier = ">=24.8.0,<25" }, { name = "urllib3", specifier = ">=2.2.3" }, - { name = "web3", specifier = ">=7.6.0,<=7.10.0" }, + { name = "web3", specifier = ">=7.6.0" }, ] provides-extras = ["dev"] diff --git a/examples/rust/Cargo.toml b/examples/rust/Cargo.toml index 5f239439c..2924aa86a 100644 --- a/examples/rust/Cargo.toml +++ b/examples/rust/Cargo.toml @@ -47,3 +47,7 @@ path = "examples/solana_signing.rs" [[example]] name = "token_balances" path = "examples/token_balances.rs" + +[[example]] +name = "custody_transfer" +path = "examples/custody_transfer.rs" diff --git a/examples/rust/examples/custody_transfer.rs b/examples/rust/examples/custody_transfer.rs new file mode 100644 index 000000000..a883ab8a6 --- /dev/null +++ b/examples/rust/examples/custody_transfer.rs @@ -0,0 +1,110 @@ +use cdp_sdk::{auth::WalletAuth, types, Client, CDP_BASE_URL}; +use dotenv::dotenv; +use reqwest_middleware::ClientBuilder; + +#[tokio::main] +async fn main() -> Result<(), Box> { + dotenv().ok(); + + let wallet_auth = WalletAuth::builder().build()?; + let http_client = ClientBuilder::new(reqwest::Client::new()) + .with(wallet_auth) + .build(); + let client = Client::new_with_client(CDP_BASE_URL, http_client); + + // 1. List accounts + let accounts_response = client.list_foundation_accounts().send().await?; + let accounts = accounts_response.into_inner(); + println!("Found {} accounts:", accounts.accounts.len()); + for account in &accounts.accounts { + println!( + " {} ({}) - type: {:?}", + *account.account_id, + account.name.as_ref().map(|n| n.as_str()).unwrap_or(""), + account.type_ + ); + } + + if accounts.accounts.is_empty() { + println!("No accounts found. Create one in the CDP dashboard first."); + return Ok(()); + } + + // 2. Get balances for the first account + let account = &accounts.accounts[0]; + let balances_response = client + .list_balances() + .account_id(&account.account_id) + .send() + .await?; + let balances = balances_response.into_inner(); + println!("\nBalances for {}:", account.name.as_ref().map(|n| n.as_str()).unwrap_or("")); + for balance in &balances.balances { + let total = balance + .amount + .get(balance.asset.symbol.as_str()) + .map(|d| d.available.as_str()) + .unwrap_or("0"); + println!(" {}: {}", balance.asset.symbol.as_str(), total); + } + + // 3. Create a quoted transfer (execute: false — no funds move) + let source = types::CreateTransferSource::TransfersAccount(types::TransfersAccount { + account_id: account.account_id.to_string(), + asset: "usd".parse()?, + }); + + let target = types::TransferTarget::OnchainAddress(types::OnchainAddress { + address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913".parse()?, + network: "base".parse()?, + asset: "usdc".parse()?, + destination_tag: None, + }); + + let transfer_body = types::TransferRequest::builder() + .source(source) + .target(target) + .amount("10.00") + .asset("usd".parse::()?) + .execute(false); + + let transfer_response = client + .create_transfer() + .body(transfer_body) + .send() + .await?; + let transfer = transfer_response.into_inner(); + println!( + "\nCreated transfer {}:", + transfer.transfer_id.as_deref().unwrap_or("unknown") + ); + println!(" Status: {:?}", transfer.status); + println!( + " Source: {} {}", + transfer.source_amount.as_deref().unwrap_or(""), + transfer.source_asset.as_ref().map(|a| a.as_str()).unwrap_or("") + ); + println!( + " Target: {} {}", + transfer.target_amount.as_deref().unwrap_or(""), + transfer.target_asset.as_ref().map(|a| a.as_str()).unwrap_or("") + ); + println!( + " Expires: {}", + transfer + .expires_at + .map(|d| d.to_string()) + .unwrap_or_default() + ); + + // 4. List recent transfers + let transfers_response = client + .list_transfers() + .status("quoted".parse::()?) + .send() + .await?; + let transfers = transfers_response.into_inner(); + println!("\n{} quoted transfers found.", transfers.transfers.len()); + + Ok(()) +} diff --git a/examples/typescript/custody/listAccountsAndTransfer.ts b/examples/typescript/custody/listAccountsAndTransfer.ts new file mode 100644 index 000000000..d75f86f0e --- /dev/null +++ b/examples/typescript/custody/listAccountsAndTransfer.ts @@ -0,0 +1,71 @@ +// Usage: pnpm tsx custody/listAccountsAndTransfer.ts +// +// Demonstrates the Flexible Custody API flow: +// 1. List accounts +// 2. Get balances for the first account +// 3. Create a quoted transfer (not executed) +// 4. List recent transfers + +import { + configure, + listFoundationAccounts, + listBalances, + createTransfer, + listTransfers, + } from "@coinbase/cdp-sdk"; + import "dotenv/config"; + + configure({ + apiKeyId: process.env.CDP_API_KEY_ID ?? process.env.CDP_API_KEY_NAME ?? "", + apiKeySecret: process.env.CDP_API_KEY_SECRET ?? "", + walletSecret: process.env.CDP_WALLET_SECRET, + }); + + async function main() { + // 1. List accounts + const { accounts } = await listFoundationAccounts(); + console.log(`Found ${accounts.length} accounts:`); + for (const account of accounts) { + console.log(` ${account.accountId} (${account.name}) - type: ${account.type}`); + } + + if (accounts.length === 0) { + console.log("No accounts found. Create one in the CDP dashboard first."); + return; + } + + // 2. Get balances for the first account + const account = accounts[0]; + const { balances } = await listBalances(account.accountId); + console.log(`\nBalances for ${account.name}:`); + for (const balance of balances) { + console.log(` ${balance.asset}: ${balance.amount}`); + } + + // 3. Create a quoted transfer (execute: false — no funds move) + const transfer = await createTransfer({ + source: { + accountId: account.accountId, + asset: "usd", + }, + target: { + address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + network: "base", + asset: "usdc", + }, + amount: "10.00", + asset: "usd", + execute: false, + }); + console.log(`\nCreated transfer ${transfer.transferId}:`); + console.log(` Status: ${transfer.status}`); + console.log(` Source: ${transfer.sourceAmount} ${transfer.sourceAsset}`); + console.log(` Target: ${transfer.targetAmount} ${transfer.targetAsset}`); + console.log(` Expires: ${transfer.expiresAt}`); + + // 4. List recent transfers + const { transfers } = await listTransfers({ status: "quoted" }); + console.log(`\n${transfers.length} quoted transfers found.`); + } + + main().catch(console.error); diff --git a/go/go.mod b/go/go.mod index 86072bc63..62fe096fb 100644 --- a/go/go.mod +++ b/go/go.mod @@ -4,14 +4,14 @@ go 1.24.3 require ( github.com/golang-jwt/jwt/v5 v5.2.2 - github.com/oapi-codegen/runtime v1.1.1 + github.com/oapi-codegen/runtime v1.4.1 github.com/stretchr/testify v1.11.1 ) require ( github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect - github.com/google/uuid v1.5.0 // indirect + github.com/google/uuid v1.6.0 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/oapi-codegen/oapi-codegen/v2 v2.7.0 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect diff --git a/go/go.sum b/go/go.sum index f2cd551b3..7563c284b 100644 --- a/go/go.sum +++ b/go/go.sum @@ -12,6 +12,8 @@ github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeD github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU= github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/juju/gnuflag v0.0.0-20171113085948-2ce1bb71843d/go.mod h1:2PavIy+JPciBPrBUjwbNvtwB6RQlve+hkpll6QSNmOE= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= @@ -24,6 +26,8 @@ github.com/oapi-codegen/oapi-codegen/v2 v2.7.0 h1:/8daqIYZfwnsHEAZdHUu9m0D5LA+5D github.com/oapi-codegen/oapi-codegen/v2 v2.7.0/go.mod h1:qzFy6iuobJw/hD1aRILee4G87/ShmhR0xYCwcUtZMCw= github.com/oapi-codegen/runtime v1.1.1 h1:EXLHh0DXIJnWhdRPN2w4MXAzFyE4CskzhNLUmtpMYro= github.com/oapi-codegen/runtime v1.1.1/go.mod h1:SK9X900oXmPWilYR5/WKPzt3Kqxn/uS/+lbpREv+eCg= +github.com/oapi-codegen/runtime v1.4.1 h1:9nwLoI+KrWxzbBcp0jO/R8uXqbik/HUyCvPeU68Y/qo= +github.com/oapi-codegen/runtime v1.4.1/go.mod h1:GwV7hC2hviaMzj+ITfHVRESK5J2W/GefVwIND/bMGvU= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= diff --git a/go/openapi/client.gen.go b/go/openapi/client.gen.go index d47c2c3cb..56f86b1f2 100644 --- a/go/openapi/client.gen.go +++ b/go/openapi/client.gen.go @@ -1,12 +1,13 @@ // Package openapi provides primitives to interact with the openapi HTTP API. // -// Code generated by github.com/deepmap/oapi-codegen version v1.16.3 DO NOT EDIT. +// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.7.0 DO NOT EDIT. package openapi import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -19,9 +20,9 @@ import ( ) const ( - ApiKeyAuthScopes = "apiKeyAuth.Scopes" - EndUserAuthScopes = "endUserAuth.Scopes" - UnauthenticatedScopes = "unauthenticated.Scopes" + ApiKeyAuthScopes apiKeyAuthContextKey = "apiKeyAuth.Scopes" + EndUserAuthScopes endUserAuthContextKey = "endUserAuth.Scopes" + UnauthenticatedScopes unauthenticatedContextKey = "unauthenticated.Scopes" ) // Defines values for AbiFunctionType. @@ -29,6 +30,16 @@ const ( Function AbiFunctionType = "function" ) +// Valid indicates whether the value is a known member of the AbiFunctionType enum. +func (e AbiFunctionType) Valid() bool { + switch e { + case Function: + return true + default: + return false + } +} + // Defines values for AbiInputType. const ( AbiInputTypeConstructor AbiInputType = "constructor" @@ -38,6 +49,24 @@ const ( AbiInputTypeReceive AbiInputType = "receive" ) +// Valid indicates whether the value is a known member of the AbiInputType enum. +func (e AbiInputType) Valid() bool { + switch e { + case AbiInputTypeConstructor: + return true + case AbiInputTypeError: + return true + case AbiInputTypeEvent: + return true + case AbiInputTypeFallback: + return true + case AbiInputTypeReceive: + return true + default: + return false + } +} + // Defines values for AbiStateMutability. const ( Nonpayable AbiStateMutability = "nonpayable" @@ -46,37 +75,223 @@ const ( View AbiStateMutability = "view" ) +// Valid indicates whether the value is a known member of the AbiStateMutability enum. +func (e AbiStateMutability) Valid() bool { + switch e { + case Nonpayable: + return true + case Payable: + return true + case Pure: + return true + case View: + return true + default: + return false + } +} + +// Defines values for AccountType. +const ( + Business AccountType = "business" + Cdp AccountType = "cdp" + Prime AccountType = "prime" +) + +// Valid indicates whether the value is a known member of the AccountType enum. +func (e AccountType) Valid() bool { + switch e { + case Business: + return true + case Cdp: + return true + case Prime: + return true + default: + return false + } +} + +// Defines values for AssetType. +const ( + AssetTypeCrypto AssetType = "crypto" + AssetTypeFiat AssetType = "fiat" +) + +// Valid indicates whether the value is a known member of the AssetType enum. +func (e AssetType) Valid() bool { + switch e { + case AssetTypeCrypto: + return true + case AssetTypeFiat: + return true + default: + return false + } +} + // Defines values for CommonSwapResponseLiquidityAvailable. const ( CommonSwapResponseLiquidityAvailableTrue CommonSwapResponseLiquidityAvailable = true ) +// Valid indicates whether the value is a known member of the CommonSwapResponseLiquidityAvailable enum. +func (e CommonSwapResponseLiquidityAvailable) Valid() bool { + switch e { + case CommonSwapResponseLiquidityAvailableTrue: + return true + default: + return false + } +} + +// Defines values for CreateCryptoDepositDestinationRequestType. +const ( + CreateCryptoDepositDestinationRequestTypeCrypto CreateCryptoDepositDestinationRequestType = "crypto" +) + +// Valid indicates whether the value is a known member of the CreateCryptoDepositDestinationRequestType enum. +func (e CreateCryptoDepositDestinationRequestType) Valid() bool { + switch e { + case CreateCryptoDepositDestinationRequestTypeCrypto: + return true + default: + return false + } +} + // Defines values for CreateEndUserEvmSwapRuleAction. const ( CreateEndUserEvmSwapRuleActionAccept CreateEndUserEvmSwapRuleAction = "accept" CreateEndUserEvmSwapRuleActionReject CreateEndUserEvmSwapRuleAction = "reject" ) +// Valid indicates whether the value is a known member of the CreateEndUserEvmSwapRuleAction enum. +func (e CreateEndUserEvmSwapRuleAction) Valid() bool { + switch e { + case CreateEndUserEvmSwapRuleActionAccept: + return true + case CreateEndUserEvmSwapRuleActionReject: + return true + default: + return false + } +} + // Defines values for CreateEndUserEvmSwapRuleOperation. const ( CreateEndUserEvmSwap CreateEndUserEvmSwapRuleOperation = "createEndUserEvmSwap" ) +// Valid indicates whether the value is a known member of the CreateEndUserEvmSwapRuleOperation enum. +func (e CreateEndUserEvmSwapRuleOperation) Valid() bool { + switch e { + case CreateEndUserEvmSwap: + return true + default: + return false + } +} + // Defines values for CreateSwapQuoteResponseLiquidityAvailable. const ( CreateSwapQuoteResponseLiquidityAvailableTrue CreateSwapQuoteResponseLiquidityAvailable = true ) +// Valid indicates whether the value is a known member of the CreateSwapQuoteResponseLiquidityAvailable enum. +func (e CreateSwapQuoteResponseLiquidityAvailable) Valid() bool { + switch e { + case CreateSwapQuoteResponseLiquidityAvailableTrue: + return true + default: + return false + } +} + +// Defines values for CryptoDepositDestinationType. +const ( + Crypto CryptoDepositDestinationType = "crypto" +) + +// Valid indicates whether the value is a known member of the CryptoDepositDestinationType enum. +func (e CryptoDepositDestinationType) Valid() bool { + switch e { + case Crypto: + return true + default: + return false + } +} + +// Defines values for DepositDestinationStatus. +const ( + DepositDestinationStatusActive DepositDestinationStatus = "active" + DepositDestinationStatusInactive DepositDestinationStatus = "inactive" + DepositDestinationStatusPending DepositDestinationStatus = "pending" +) + +// Valid indicates whether the value is a known member of the DepositDestinationStatus enum. +func (e DepositDestinationStatus) Valid() bool { + switch e { + case DepositDestinationStatusActive: + return true + case DepositDestinationStatusInactive: + return true + case DepositDestinationStatusPending: + return true + default: + return false + } +} + +// Defines values for DepositTravelRuleOriginatorWalletType. +const ( + DepositTravelRuleOriginatorWalletTypeCustodial DepositTravelRuleOriginatorWalletType = "custodial" + DepositTravelRuleOriginatorWalletTypeSelfCustody DepositTravelRuleOriginatorWalletType = "self_custody" +) + +// Valid indicates whether the value is a known member of the DepositTravelRuleOriginatorWalletType enum. +func (e DepositTravelRuleOriginatorWalletType) Valid() bool { + switch e { + case DepositTravelRuleOriginatorWalletTypeCustodial: + return true + case DepositTravelRuleOriginatorWalletTypeSelfCustody: + return true + default: + return false + } +} + // Defines values for DeveloperJWTAuthenticationType. const ( Jwt DeveloperJWTAuthenticationType = "jwt" ) +// Valid indicates whether the value is a known member of the DeveloperJWTAuthenticationType enum. +func (e DeveloperJWTAuthenticationType) Valid() bool { + switch e { + case Jwt: + return true + default: + return false + } +} + // Defines values for EmailAuthenticationType. const ( Email EmailAuthenticationType = "email" ) +// Valid indicates whether the value is a known member of the EmailAuthenticationType enum. +func (e EmailAuthenticationType) Valid() bool { + switch e { + case Email: + return true + default: + return false + } +} + // Defines values for ErrorType. const ( ErrorTypeAccountLimitExceeded ErrorType = "account_limit_exceeded" @@ -87,7 +302,13 @@ const ( ErrorTypeBadGateway ErrorType = "bad_gateway" ErrorTypeCaptureExpired ErrorType = "capture_expired" ErrorTypeClientClosedRequest ErrorType = "client_closed_request" + ErrorTypeDelegationExpired ErrorType = "delegation_expired" + ErrorTypeDelegationNotAuthorized ErrorType = "delegation_not_authorized" + ErrorTypeDelegationNotEnabled ErrorType = "delegation_not_enabled" + ErrorTypeDelegationNotFound ErrorType = "delegation_not_found" + ErrorTypeDelegationRevoked ErrorType = "delegation_revoked" ErrorTypeDocumentVerificationFailed ErrorType = "document_verification_failed" + ErrorTypeEndpointUnavailable ErrorType = "endpoint_unavailable" ErrorTypeFaucetLimitExceeded ErrorType = "faucet_limit_exceeded" ErrorTypeForbidden ErrorType = "forbidden" ErrorTypeGuestPermissionDenied ErrorType = "guest_permission_denied" @@ -140,56 +361,300 @@ const ( ErrorTypeTransactionSimulationFailed ErrorType = "transaction_simulation_failed" ErrorTypeTransferAmountInvalid ErrorType = "transfer_amount_invalid" ErrorTypeTransferAssetNotSupported ErrorType = "transfer_asset_not_supported" + ErrorTypeTransferQuoteExpired ErrorType = "transfer_quote_expired" ErrorTypeTravelRulesFieldMissing ErrorType = "travel_rules_field_missing" ErrorTypeTravelRulesRecipientViolation ErrorType = "travel_rules_recipient_violation" ErrorTypeUnauthorized ErrorType = "unauthorized" + ErrorTypeUnsupportedTosLanguage ErrorType = "unsupported_tos_language" ) +// Valid indicates whether the value is a known member of the ErrorType enum. +func (e ErrorType) Valid() bool { + switch e { + case ErrorTypeAccountLimitExceeded: + return true + case ErrorTypeAccountNotReady: + return true + case ErrorTypeAlreadyExists: + return true + case ErrorTypeAssetMismatch: + return true + case ErrorTypeAuthorizationExpired: + return true + case ErrorTypeBadGateway: + return true + case ErrorTypeCaptureExpired: + return true + case ErrorTypeClientClosedRequest: + return true + case ErrorTypeDelegationExpired: + return true + case ErrorTypeDelegationNotAuthorized: + return true + case ErrorTypeDelegationNotEnabled: + return true + case ErrorTypeDelegationNotFound: + return true + case ErrorTypeDelegationRevoked: + return true + case ErrorTypeDocumentVerificationFailed: + return true + case ErrorTypeEndpointUnavailable: + return true + case ErrorTypeFaucetLimitExceeded: + return true + case ErrorTypeForbidden: + return true + case ErrorTypeGuestPermissionDenied: + return true + case ErrorTypeGuestRegionForbidden: + return true + case ErrorTypeGuestTransactionCount: + return true + case ErrorTypeGuestTransactionLimit: + return true + case ErrorTypeIdempotencyError: + return true + case ErrorTypeInsufficientAllowance: + return true + case ErrorTypeInsufficientBalance: + return true + case ErrorTypeInsufficientLiquidity: + return true + case ErrorTypeInternalServerError: + return true + case ErrorTypeInvalidRequest: + return true + case ErrorTypeInvalidSignature: + return true + case ErrorTypeInvalidSqlQuery: + return true + case ErrorTypeMalformedTransaction: + return true + case ErrorTypeMetadataKeyTooLong: + return true + case ErrorTypeMetadataTooManyEntries: + return true + case ErrorTypeMetadataValueTooLong: + return true + case ErrorTypeMfaAlreadyEnrolled: + return true + case ErrorTypeMfaFlowExpired: + return true + case ErrorTypeMfaInvalidCode: + return true + case ErrorTypeMfaNotEnrolled: + return true + case ErrorTypeMfaRequired: + return true + case ErrorTypeNetworkNotTradable: + return true + case ErrorTypeNotFound: + return true + case ErrorTypeOrderAlreadyCanceled: + return true + case ErrorTypeOrderAlreadyFilled: + return true + case ErrorTypeOrderQuoteExpired: + return true + case ErrorTypePaymentMethodRequired: + return true + case ErrorTypePaymentRequired: + return true + case ErrorTypePhoneNumberVerificationExpired: + return true + case ErrorTypePolicyInUse: + return true + case ErrorTypePolicyViolation: + return true + case ErrorTypeRateLimitExceeded: + return true + case ErrorTypeRecipientAllowlistPending: + return true + case ErrorTypeRecipientAllowlistViolation: + return true + case ErrorTypeRefundExpired: + return true + case ErrorTypeRequestCanceled: + return true + case ErrorTypeServiceUnavailable: + return true + case ErrorTypeSettlementFailed: + return true + case ErrorTypeSourceAccountInvalid: + return true + case ErrorTypeSourceAccountNotFound: + return true + case ErrorTypeSourceAssetNotSupported: + return true + case ErrorTypeTargetAccountInvalid: + return true + case ErrorTypeTargetAccountNotFound: + return true + case ErrorTypeTargetAssetNotSupported: + return true + case ErrorTypeTargetEmailInvalid: + return true + case ErrorTypeTargetOnchainAddressInvalid: + return true + case ErrorTypeTimedOut: + return true + case ErrorTypeTransactionSimulationFailed: + return true + case ErrorTypeTransferAmountInvalid: + return true + case ErrorTypeTransferAssetNotSupported: + return true + case ErrorTypeTransferQuoteExpired: + return true + case ErrorTypeTravelRulesFieldMissing: + return true + case ErrorTypeTravelRulesRecipientViolation: + return true + case ErrorTypeUnauthorized: + return true + case ErrorTypeUnsupportedTosLanguage: + return true + default: + return false + } +} + // Defines values for EthValueCriterionOperator. const ( - EthValueCriterionOperatorEmpty EthValueCriterionOperator = ">" - EthValueCriterionOperatorEqualEqual EthValueCriterionOperator = "==" - EthValueCriterionOperatorN1 EthValueCriterionOperator = ">=" - EthValueCriterionOperatorN2 EthValueCriterionOperator = "<" - EthValueCriterionOperatorN3 EthValueCriterionOperator = "<=" + EthValueCriterionOperatorEqualEqual EthValueCriterionOperator = "==" + EthValueCriterionOperatorGreaterThan EthValueCriterionOperator = ">" + EthValueCriterionOperatorGreaterThanEqual EthValueCriterionOperator = ">=" + EthValueCriterionOperatorLessThan EthValueCriterionOperator = "<" + EthValueCriterionOperatorLessThanEqual EthValueCriterionOperator = "<=" ) +// Valid indicates whether the value is a known member of the EthValueCriterionOperator enum. +func (e EthValueCriterionOperator) Valid() bool { + switch e { + case EthValueCriterionOperatorEqualEqual: + return true + case EthValueCriterionOperatorGreaterThan: + return true + case EthValueCriterionOperatorGreaterThanEqual: + return true + case EthValueCriterionOperatorLessThan: + return true + case EthValueCriterionOperatorLessThanEqual: + return true + default: + return false + } +} + // Defines values for EthValueCriterionType. const ( EthValue EthValueCriterionType = "ethValue" ) +// Valid indicates whether the value is a known member of the EthValueCriterionType enum. +func (e EthValueCriterionType) Valid() bool { + switch e { + case EthValue: + return true + default: + return false + } +} + // Defines values for EvmAddressCriterionOperator. const ( EvmAddressCriterionOperatorIn EvmAddressCriterionOperator = "in" EvmAddressCriterionOperatorNotIn EvmAddressCriterionOperator = "not in" ) +// Valid indicates whether the value is a known member of the EvmAddressCriterionOperator enum. +func (e EvmAddressCriterionOperator) Valid() bool { + switch e { + case EvmAddressCriterionOperatorIn: + return true + case EvmAddressCriterionOperatorNotIn: + return true + default: + return false + } +} + // Defines values for EvmAddressCriterionType. const ( EvmAddress EvmAddressCriterionType = "evmAddress" ) +// Valid indicates whether the value is a known member of the EvmAddressCriterionType enum. +func (e EvmAddressCriterionType) Valid() bool { + switch e { + case EvmAddress: + return true + default: + return false + } +} + // Defines values for EvmDataCriterionType. const ( EvmData EvmDataCriterionType = "evmData" ) +// Valid indicates whether the value is a known member of the EvmDataCriterionType enum. +func (e EvmDataCriterionType) Valid() bool { + switch e { + case EvmData: + return true + default: + return false + } +} + // Defines values for EvmDataParameterConditionOperator. const ( - EvmDataParameterConditionOperatorEmpty EvmDataParameterConditionOperator = ">" - EvmDataParameterConditionOperatorEqualEqual EvmDataParameterConditionOperator = "==" - EvmDataParameterConditionOperatorN1 EvmDataParameterConditionOperator = ">=" - EvmDataParameterConditionOperatorN2 EvmDataParameterConditionOperator = "<" - EvmDataParameterConditionOperatorN3 EvmDataParameterConditionOperator = "<=" + EvmDataParameterConditionOperatorEqualEqual EvmDataParameterConditionOperator = "==" + EvmDataParameterConditionOperatorGreaterThan EvmDataParameterConditionOperator = ">" + EvmDataParameterConditionOperatorGreaterThanEqual EvmDataParameterConditionOperator = ">=" + EvmDataParameterConditionOperatorLessThan EvmDataParameterConditionOperator = "<" + EvmDataParameterConditionOperatorLessThanEqual EvmDataParameterConditionOperator = "<=" ) +// Valid indicates whether the value is a known member of the EvmDataParameterConditionOperator enum. +func (e EvmDataParameterConditionOperator) Valid() bool { + switch e { + case EvmDataParameterConditionOperatorEqualEqual: + return true + case EvmDataParameterConditionOperatorGreaterThan: + return true + case EvmDataParameterConditionOperatorGreaterThanEqual: + return true + case EvmDataParameterConditionOperatorLessThan: + return true + case EvmDataParameterConditionOperatorLessThanEqual: + return true + default: + return false + } +} + // Defines values for EvmDataParameterConditionListOperator. const ( EvmDataParameterConditionListOperatorIn EvmDataParameterConditionListOperator = "in" EvmDataParameterConditionListOperatorNotIn EvmDataParameterConditionListOperator = "not in" ) +// Valid indicates whether the value is a known member of the EvmDataParameterConditionListOperator enum. +func (e EvmDataParameterConditionListOperator) Valid() bool { + switch e { + case EvmDataParameterConditionListOperatorIn: + return true + case EvmDataParameterConditionListOperatorNotIn: + return true + default: + return false + } +} + // Defines values for EvmEip7702DelegationNetwork. const ( EvmEip7702DelegationNetworkArbitrum EvmEip7702DelegationNetwork = "arbitrum" @@ -201,6 +666,28 @@ const ( EvmEip7702DelegationNetworkPolygon EvmEip7702DelegationNetwork = "polygon" ) +// Valid indicates whether the value is a known member of the EvmEip7702DelegationNetwork enum. +func (e EvmEip7702DelegationNetwork) Valid() bool { + switch e { + case EvmEip7702DelegationNetworkArbitrum: + return true + case EvmEip7702DelegationNetworkBase: + return true + case EvmEip7702DelegationNetworkBaseSepolia: + return true + case EvmEip7702DelegationNetworkEthereum: + return true + case EvmEip7702DelegationNetworkEthereumSepolia: + return true + case EvmEip7702DelegationNetworkOptimism: + return true + case EvmEip7702DelegationNetworkPolygon: + return true + default: + return false + } +} + // Defines values for EvmEip7702DelegationOperationStatus. const ( COMPLETED EvmEip7702DelegationOperationStatus = "COMPLETED" @@ -210,11 +697,39 @@ const ( UNSPECIFIED EvmEip7702DelegationOperationStatus = "UNSPECIFIED" ) +// Valid indicates whether the value is a known member of the EvmEip7702DelegationOperationStatus enum. +func (e EvmEip7702DelegationOperationStatus) Valid() bool { + switch e { + case COMPLETED: + return true + case FAILED: + return true + case PENDING: + return true + case SUBMITTED: + return true + case UNSPECIFIED: + return true + default: + return false + } +} + // Defines values for EvmMessageCriterionType. const ( EvmMessage EvmMessageCriterionType = "evmMessage" ) +// Valid indicates whether the value is a known member of the EvmMessageCriterionType enum. +func (e EvmMessageCriterionType) Valid() bool { + switch e { + case EvmMessage: + return true + default: + return false + } +} + // Defines values for EvmNetworkCriterionNetworks. const ( EvmNetworkCriterionNetworksArbitrum EvmNetworkCriterionNetworks = "arbitrum" @@ -232,17 +747,73 @@ const ( EvmNetworkCriterionNetworksZora EvmNetworkCriterionNetworks = "zora" ) +// Valid indicates whether the value is a known member of the EvmNetworkCriterionNetworks enum. +func (e EvmNetworkCriterionNetworks) Valid() bool { + switch e { + case EvmNetworkCriterionNetworksArbitrum: + return true + case EvmNetworkCriterionNetworksArbitrumSepolia: + return true + case EvmNetworkCriterionNetworksAvalanche: + return true + case EvmNetworkCriterionNetworksBase: + return true + case EvmNetworkCriterionNetworksBaseSepolia: + return true + case EvmNetworkCriterionNetworksBnb: + return true + case EvmNetworkCriterionNetworksEthereum: + return true + case EvmNetworkCriterionNetworksEthereumSepolia: + return true + case EvmNetworkCriterionNetworksOptimism: + return true + case EvmNetworkCriterionNetworksPolygon: + return true + case EvmNetworkCriterionNetworksWorld: + return true + case EvmNetworkCriterionNetworksWorldSepolia: + return true + case EvmNetworkCriterionNetworksZora: + return true + default: + return false + } +} + // Defines values for EvmNetworkCriterionOperator. const ( EvmNetworkCriterionOperatorIn EvmNetworkCriterionOperator = "in" EvmNetworkCriterionOperatorNotIn EvmNetworkCriterionOperator = "not in" ) +// Valid indicates whether the value is a known member of the EvmNetworkCriterionOperator enum. +func (e EvmNetworkCriterionOperator) Valid() bool { + switch e { + case EvmNetworkCriterionOperatorIn: + return true + case EvmNetworkCriterionOperatorNotIn: + return true + default: + return false + } +} + // Defines values for EvmNetworkCriterionType. const ( EvmNetwork EvmNetworkCriterionType = "evmNetwork" ) +// Valid indicates whether the value is a known member of the EvmNetworkCriterionType enum. +func (e EvmNetworkCriterionType) Valid() bool { + switch e { + case EvmNetwork: + return true + default: + return false + } +} + // Defines values for EvmSwapsNetwork. const ( EvmSwapsNetworkArbitrum EvmSwapsNetwork = "arbitrum" @@ -252,21 +823,69 @@ const ( EvmSwapsNetworkPolygon EvmSwapsNetwork = "polygon" ) +// Valid indicates whether the value is a known member of the EvmSwapsNetwork enum. +func (e EvmSwapsNetwork) Valid() bool { + switch e { + case EvmSwapsNetworkArbitrum: + return true + case EvmSwapsNetworkBase: + return true + case EvmSwapsNetworkEthereum: + return true + case EvmSwapsNetworkOptimism: + return true + case EvmSwapsNetworkPolygon: + return true + default: + return false + } +} + // Defines values for EvmTypedAddressConditionOperator. const ( EvmTypedAddressConditionOperatorIn EvmTypedAddressConditionOperator = "in" EvmTypedAddressConditionOperatorNotIn EvmTypedAddressConditionOperator = "not in" ) +// Valid indicates whether the value is a known member of the EvmTypedAddressConditionOperator enum. +func (e EvmTypedAddressConditionOperator) Valid() bool { + switch e { + case EvmTypedAddressConditionOperatorIn: + return true + case EvmTypedAddressConditionOperatorNotIn: + return true + default: + return false + } +} + // Defines values for EvmTypedNumericalConditionOperator. const ( - EvmTypedNumericalConditionOperatorEmpty EvmTypedNumericalConditionOperator = ">" - EvmTypedNumericalConditionOperatorEqualEqual EvmTypedNumericalConditionOperator = "==" - EvmTypedNumericalConditionOperatorN1 EvmTypedNumericalConditionOperator = ">=" - EvmTypedNumericalConditionOperatorN2 EvmTypedNumericalConditionOperator = "<" - EvmTypedNumericalConditionOperatorN3 EvmTypedNumericalConditionOperator = "<=" + EvmTypedNumericalConditionOperatorEqualEqual EvmTypedNumericalConditionOperator = "==" + EvmTypedNumericalConditionOperatorGreaterThan EvmTypedNumericalConditionOperator = ">" + EvmTypedNumericalConditionOperatorGreaterThanEqual EvmTypedNumericalConditionOperator = ">=" + EvmTypedNumericalConditionOperatorLessThan EvmTypedNumericalConditionOperator = "<" + EvmTypedNumericalConditionOperatorLessThanEqual EvmTypedNumericalConditionOperator = "<=" ) +// Valid indicates whether the value is a known member of the EvmTypedNumericalConditionOperator enum. +func (e EvmTypedNumericalConditionOperator) Valid() bool { + switch e { + case EvmTypedNumericalConditionOperatorEqualEqual: + return true + case EvmTypedNumericalConditionOperatorGreaterThan: + return true + case EvmTypedNumericalConditionOperatorGreaterThanEqual: + return true + case EvmTypedNumericalConditionOperatorLessThan: + return true + case EvmTypedNumericalConditionOperatorLessThanEqual: + return true + default: + return false + } +} + // Defines values for EvmUserOperationStatus. const ( EvmUserOperationStatusBroadcast EvmUserOperationStatus = "broadcast" @@ -277,6 +896,26 @@ const ( EvmUserOperationStatusSigned EvmUserOperationStatus = "signed" ) +// Valid indicates whether the value is a known member of the EvmUserOperationStatus enum. +func (e EvmUserOperationStatus) Valid() bool { + switch e { + case EvmUserOperationStatusBroadcast: + return true + case EvmUserOperationStatusComplete: + return true + case EvmUserOperationStatusDropped: + return true + case EvmUserOperationStatusFailed: + return true + case EvmUserOperationStatusPending: + return true + case EvmUserOperationStatusSigned: + return true + default: + return false + } +} + // Defines values for EvmUserOperationNetwork. const ( EvmUserOperationNetworkArbitrum EvmUserOperationNetwork = "arbitrum" @@ -291,11 +930,64 @@ const ( EvmUserOperationNetworkZora EvmUserOperationNetwork = "zora" ) +// Valid indicates whether the value is a known member of the EvmUserOperationNetwork enum. +func (e EvmUserOperationNetwork) Valid() bool { + switch e { + case EvmUserOperationNetworkArbitrum: + return true + case EvmUserOperationNetworkAvalanche: + return true + case EvmUserOperationNetworkBase: + return true + case EvmUserOperationNetworkBaseSepolia: + return true + case EvmUserOperationNetworkBnb: + return true + case EvmUserOperationNetworkEthereum: + return true + case EvmUserOperationNetworkEthereumSepolia: + return true + case EvmUserOperationNetworkOptimism: + return true + case EvmUserOperationNetworkPolygon: + return true + case EvmUserOperationNetworkZora: + return true + default: + return false + } +} + +// Defines values for FedwirePaymentMethodPaymentRail. +const ( + Fedwire FedwirePaymentMethodPaymentRail = "fedwire" +) + +// Valid indicates whether the value is a known member of the FedwirePaymentMethodPaymentRail enum. +func (e FedwirePaymentMethodPaymentRail) Valid() bool { + switch e { + case Fedwire: + return true + default: + return false + } +} + // Defines values for GetSwapPriceResponseLiquidityAvailable. const ( True GetSwapPriceResponseLiquidityAvailable = true ) +// Valid indicates whether the value is a known member of the GetSwapPriceResponseLiquidityAvailable enum. +func (e GetSwapPriceResponseLiquidityAvailable) Valid() bool { + switch e { + case True: + return true + default: + return false + } +} + // Defines values for KnownAbiType. const ( Erc1155 KnownAbiType = "erc1155" @@ -303,6 +995,20 @@ const ( Erc721 KnownAbiType = "erc721" ) +// Valid indicates whether the value is a known member of the KnownAbiType enum. +func (e KnownAbiType) Valid() bool { + switch e { + case Erc1155: + return true + case Erc20: + return true + case Erc721: + return true + default: + return false + } +} + // Defines values for KnownIdlType. const ( AssociatedTokenProgram KnownIdlType = "AssociatedTokenProgram" @@ -310,6 +1016,20 @@ const ( TokenProgram KnownIdlType = "TokenProgram" ) +// Valid indicates whether the value is a known member of the KnownIdlType enum. +func (e KnownIdlType) Valid() bool { + switch e { + case AssociatedTokenProgram: + return true + case SystemProgram: + return true + case TokenProgram: + return true + default: + return false + } +} + // Defines values for ListEvmTokenBalancesNetwork. const ( ListEvmTokenBalancesNetworkBase ListEvmTokenBalancesNetwork = "base" @@ -317,37 +1037,155 @@ const ( ListEvmTokenBalancesNetworkEthereum ListEvmTokenBalancesNetwork = "ethereum" ) +// Valid indicates whether the value is a known member of the ListEvmTokenBalancesNetwork enum. +func (e ListEvmTokenBalancesNetwork) Valid() bool { + switch e { + case ListEvmTokenBalancesNetworkBase: + return true + case ListEvmTokenBalancesNetworkBaseSepolia: + return true + case ListEvmTokenBalancesNetworkEthereum: + return true + default: + return false + } +} + // Defines values for ListSolanaTokenBalancesNetwork. const ( ListSolanaTokenBalancesNetworkSolana ListSolanaTokenBalancesNetwork = "solana" ListSolanaTokenBalancesNetworkSolanaDevnet ListSolanaTokenBalancesNetwork = "solana-devnet" ) +// Valid indicates whether the value is a known member of the ListSolanaTokenBalancesNetwork enum. +func (e ListSolanaTokenBalancesNetwork) Valid() bool { + switch e { + case ListSolanaTokenBalancesNetworkSolana: + return true + case ListSolanaTokenBalancesNetworkSolanaDevnet: + return true + default: + return false + } +} + // Defines values for MintAddressCriterionOperator. const ( MintAddressCriterionOperatorIn MintAddressCriterionOperator = "in" MintAddressCriterionOperatorNotIn MintAddressCriterionOperator = "not in" ) +// Valid indicates whether the value is a known member of the MintAddressCriterionOperator enum. +func (e MintAddressCriterionOperator) Valid() bool { + switch e { + case MintAddressCriterionOperatorIn: + return true + case MintAddressCriterionOperatorNotIn: + return true + default: + return false + } +} + // Defines values for MintAddressCriterionType. const ( MintAddress MintAddressCriterionType = "mintAddress" ) +// Valid indicates whether the value is a known member of the MintAddressCriterionType enum. +func (e MintAddressCriterionType) Valid() bool { + switch e { + case MintAddress: + return true + default: + return false + } +} + // Defines values for NetUSDChangeCriterionOperator. const ( - NetUSDChangeCriterionOperatorEmpty NetUSDChangeCriterionOperator = ">" - NetUSDChangeCriterionOperatorEqualEqual NetUSDChangeCriterionOperator = "==" - NetUSDChangeCriterionOperatorN1 NetUSDChangeCriterionOperator = ">=" - NetUSDChangeCriterionOperatorN2 NetUSDChangeCriterionOperator = "<" - NetUSDChangeCriterionOperatorN3 NetUSDChangeCriterionOperator = "<=" + NetUSDChangeCriterionOperatorEqualEqual NetUSDChangeCriterionOperator = "==" + NetUSDChangeCriterionOperatorGreaterThan NetUSDChangeCriterionOperator = ">" + NetUSDChangeCriterionOperatorGreaterThanEqual NetUSDChangeCriterionOperator = ">=" + NetUSDChangeCriterionOperatorLessThan NetUSDChangeCriterionOperator = "<" + NetUSDChangeCriterionOperatorLessThanEqual NetUSDChangeCriterionOperator = "<=" ) +// Valid indicates whether the value is a known member of the NetUSDChangeCriterionOperator enum. +func (e NetUSDChangeCriterionOperator) Valid() bool { + switch e { + case NetUSDChangeCriterionOperatorEqualEqual: + return true + case NetUSDChangeCriterionOperatorGreaterThan: + return true + case NetUSDChangeCriterionOperatorGreaterThanEqual: + return true + case NetUSDChangeCriterionOperatorLessThan: + return true + case NetUSDChangeCriterionOperatorLessThanEqual: + return true + default: + return false + } +} + // Defines values for NetUSDChangeCriterionType. const ( NetUSDChange NetUSDChangeCriterionType = "netUSDChange" ) +// Valid indicates whether the value is a known member of the NetUSDChangeCriterionType enum. +func (e NetUSDChangeCriterionType) Valid() bool { + switch e { + case NetUSDChange: + return true + default: + return false + } +} + +// Defines values for Network. +const ( + NetworkAptos Network = "aptos" + NetworkArbitrum Network = "arbitrum" + NetworkArbitrumSepolia Network = "arbitrum-sepolia" + NetworkBase Network = "base" + NetworkEthereum Network = "ethereum" + NetworkOptimism Network = "optimism" + NetworkPolygon Network = "polygon" + NetworkSolana Network = "solana" + NetworkWorld Network = "world" + NetworkWorldSepolia Network = "world-sepolia" +) + +// Valid indicates whether the value is a known member of the Network enum. +func (e Network) Valid() bool { + switch e { + case NetworkAptos: + return true + case NetworkArbitrum: + return true + case NetworkArbitrumSepolia: + return true + case NetworkBase: + return true + case NetworkEthereum: + return true + case NetworkOptimism: + return true + case NetworkPolygon: + return true + case NetworkSolana: + return true + case NetworkWorld: + return true + case NetworkWorldSepolia: + return true + default: + return false + } +} + // Defines values for OAuth2ProviderType. const ( Apple OAuth2ProviderType = "apple" @@ -357,6 +1195,24 @@ const ( X OAuth2ProviderType = "x" ) +// Valid indicates whether the value is a known member of the OAuth2ProviderType enum. +func (e OAuth2ProviderType) Valid() bool { + switch e { + case Apple: + return true + case Github: + return true + case Google: + return true + case Telegram: + return true + case X: + return true + default: + return false + } +} + // Defines values for OnchainDataResultSchemaColumnsType. const ( Bool OnchainDataResultSchemaColumnsType = "Bool" @@ -381,24 +1237,108 @@ const ( UUID OnchainDataResultSchemaColumnsType = "UUID" ) +// Valid indicates whether the value is a known member of the OnchainDataResultSchemaColumnsType enum. +func (e OnchainDataResultSchemaColumnsType) Valid() bool { + switch e { + case Bool: + return true + case Date: + return true + case DateTime: + return true + case DateTime64: + return true + case Float32: + return true + case Float64: + return true + case Int128: + return true + case Int16: + return true + case Int256: + return true + case Int32: + return true + case Int64: + return true + case Int8: + return true + case String: + return true + case UInt128: + return true + case UInt16: + return true + case UInt256: + return true + case UInt32: + return true + case UInt64: + return true + case UInt8: + return true + case UUID: + return true + default: + return false + } +} + // Defines values for OnrampLimitType. const ( LifetimeTransactions OnrampLimitType = "lifetime_transactions" WeeklySpending OnrampLimitType = "weekly_spending" ) +// Valid indicates whether the value is a known member of the OnrampLimitType enum. +func (e OnrampLimitType) Valid() bool { + switch e { + case LifetimeTransactions: + return true + case WeeklySpending: + return true + default: + return false + } +} + // Defines values for OnrampOrderFeeType. const ( FEETYPEEXCHANGE OnrampOrderFeeType = "FEE_TYPE_EXCHANGE" FEETYPENETWORK OnrampOrderFeeType = "FEE_TYPE_NETWORK" ) +// Valid indicates whether the value is a known member of the OnrampOrderFeeType enum. +func (e OnrampOrderFeeType) Valid() bool { + switch e { + case FEETYPEEXCHANGE: + return true + case FEETYPENETWORK: + return true + default: + return false + } +} + // Defines values for OnrampOrderPaymentMethodTypeId. const ( GUESTCHECKOUTAPPLEPAY OnrampOrderPaymentMethodTypeId = "GUEST_CHECKOUT_APPLE_PAY" GUESTCHECKOUTGOOGLEPAY OnrampOrderPaymentMethodTypeId = "GUEST_CHECKOUT_GOOGLE_PAY" ) +// Valid indicates whether the value is a known member of the OnrampOrderPaymentMethodTypeId enum. +func (e OnrampOrderPaymentMethodTypeId) Valid() bool { + switch e { + case GUESTCHECKOUTAPPLEPAY: + return true + case GUESTCHECKOUTGOOGLEPAY: + return true + default: + return false + } +} + // Defines values for OnrampOrderStatus. const ( ONRAMPORDERSTATUSCOMPLETED OnrampOrderStatus = "ONRAMP_ORDER_STATUS_COMPLETED" @@ -408,11 +1348,39 @@ const ( ONRAMPORDERSTATUSPROCESSING OnrampOrderStatus = "ONRAMP_ORDER_STATUS_PROCESSING" ) +// Valid indicates whether the value is a known member of the OnrampOrderStatus enum. +func (e OnrampOrderStatus) Valid() bool { + switch e { + case ONRAMPORDERSTATUSCOMPLETED: + return true + case ONRAMPORDERSTATUSFAILED: + return true + case ONRAMPORDERSTATUSPENDINGAUTH: + return true + case ONRAMPORDERSTATUSPENDINGPAYMENT: + return true + case ONRAMPORDERSTATUSPROCESSING: + return true + default: + return false + } +} + // Defines values for OnrampPaymentLinkType. const ( PAYMENTLINKTYPEAPPLEPAYBUTTON OnrampPaymentLinkType = "PAYMENT_LINK_TYPE_APPLE_PAY_BUTTON" ) +// Valid indicates whether the value is a known member of the OnrampPaymentLinkType enum. +func (e OnrampPaymentLinkType) Valid() bool { + switch e { + case PAYMENTLINKTYPEAPPLEPAYBUTTON: + return true + default: + return false + } +} + // Defines values for OnrampQuotePaymentMethodTypeId. const ( ACH OnrampQuotePaymentMethodTypeId = "ACH" @@ -423,341 +1391,1046 @@ const ( PAYPAL OnrampQuotePaymentMethodTypeId = "PAYPAL" ) +// Valid indicates whether the value is a known member of the OnrampQuotePaymentMethodTypeId enum. +func (e OnrampQuotePaymentMethodTypeId) Valid() bool { + switch e { + case ACH: + return true + case APPLEPAY: + return true + case CARD: + return true + case CRYPTOWALLET: + return true + case FIATWALLET: + return true + case PAYPAL: + return true + default: + return false + } +} + // Defines values for OnrampUserIdType. const ( PhoneNumber OnrampUserIdType = "phone_number" ) +// Valid indicates whether the value is a known member of the OnrampUserIdType enum. +func (e OnrampUserIdType) Valid() bool { + switch e { + case PhoneNumber: + return true + default: + return false + } +} + // Defines values for PolicyScope. const ( PolicyScopeAccount PolicyScope = "account" PolicyScopeProject PolicyScope = "project" ) +// Valid indicates whether the value is a known member of the PolicyScope enum. +func (e PolicyScope) Valid() bool { + switch e { + case PolicyScopeAccount: + return true + case PolicyScopeProject: + return true + default: + return false + } +} + // Defines values for PrepareUserOperationRuleAction. const ( PrepareUserOperationRuleActionAccept PrepareUserOperationRuleAction = "accept" PrepareUserOperationRuleActionReject PrepareUserOperationRuleAction = "reject" ) +// Valid indicates whether the value is a known member of the PrepareUserOperationRuleAction enum. +func (e PrepareUserOperationRuleAction) Valid() bool { + switch e { + case PrepareUserOperationRuleActionAccept: + return true + case PrepareUserOperationRuleActionReject: + return true + default: + return false + } +} + // Defines values for PrepareUserOperationRuleOperation. const ( PrepareUserOperation PrepareUserOperationRuleOperation = "prepareUserOperation" ) +// Valid indicates whether the value is a known member of the PrepareUserOperationRuleOperation enum. +func (e PrepareUserOperationRuleOperation) Valid() bool { + switch e { + case PrepareUserOperation: + return true + default: + return false + } +} + // Defines values for ProgramIdCriterionOperator. const ( ProgramIdCriterionOperatorIn ProgramIdCriterionOperator = "in" ProgramIdCriterionOperatorNotIn ProgramIdCriterionOperator = "not in" ) +// Valid indicates whether the value is a known member of the ProgramIdCriterionOperator enum. +func (e ProgramIdCriterionOperator) Valid() bool { + switch e { + case ProgramIdCriterionOperatorIn: + return true + case ProgramIdCriterionOperatorNotIn: + return true + default: + return false + } +} + // Defines values for ProgramIdCriterionType. const ( ProgramId ProgramIdCriterionType = "programId" ) +// Valid indicates whether the value is a known member of the ProgramIdCriterionType enum. +func (e ProgramIdCriterionType) Valid() bool { + switch e { + case ProgramId: + return true + default: + return false + } +} + // Defines values for SendEndUserEvmAssetRuleAction. const ( SendEndUserEvmAssetRuleActionAccept SendEndUserEvmAssetRuleAction = "accept" SendEndUserEvmAssetRuleActionReject SendEndUserEvmAssetRuleAction = "reject" ) +// Valid indicates whether the value is a known member of the SendEndUserEvmAssetRuleAction enum. +func (e SendEndUserEvmAssetRuleAction) Valid() bool { + switch e { + case SendEndUserEvmAssetRuleActionAccept: + return true + case SendEndUserEvmAssetRuleActionReject: + return true + default: + return false + } +} + // Defines values for SendEndUserEvmAssetRuleOperation. const ( SendEndUserEvmAsset SendEndUserEvmAssetRuleOperation = "sendEndUserEvmAsset" ) +// Valid indicates whether the value is a known member of the SendEndUserEvmAssetRuleOperation enum. +func (e SendEndUserEvmAssetRuleOperation) Valid() bool { + switch e { + case SendEndUserEvmAsset: + return true + default: + return false + } +} + // Defines values for SendEndUserEvmTransactionRuleAction. const ( SendEndUserEvmTransactionRuleActionAccept SendEndUserEvmTransactionRuleAction = "accept" SendEndUserEvmTransactionRuleActionReject SendEndUserEvmTransactionRuleAction = "reject" ) +// Valid indicates whether the value is a known member of the SendEndUserEvmTransactionRuleAction enum. +func (e SendEndUserEvmTransactionRuleAction) Valid() bool { + switch e { + case SendEndUserEvmTransactionRuleActionAccept: + return true + case SendEndUserEvmTransactionRuleActionReject: + return true + default: + return false + } +} + // Defines values for SendEndUserEvmTransactionRuleOperation. const ( SendEndUserEvmTransaction SendEndUserEvmTransactionRuleOperation = "sendEndUserEvmTransaction" ) +// Valid indicates whether the value is a known member of the SendEndUserEvmTransactionRuleOperation enum. +func (e SendEndUserEvmTransactionRuleOperation) Valid() bool { + switch e { + case SendEndUserEvmTransaction: + return true + default: + return false + } +} + // Defines values for SendEndUserSolAssetRuleAction. const ( SendEndUserSolAssetRuleActionAccept SendEndUserSolAssetRuleAction = "accept" SendEndUserSolAssetRuleActionReject SendEndUserSolAssetRuleAction = "reject" ) +// Valid indicates whether the value is a known member of the SendEndUserSolAssetRuleAction enum. +func (e SendEndUserSolAssetRuleAction) Valid() bool { + switch e { + case SendEndUserSolAssetRuleActionAccept: + return true + case SendEndUserSolAssetRuleActionReject: + return true + default: + return false + } +} + // Defines values for SendEndUserSolAssetRuleOperation. const ( SendEndUserSolAsset SendEndUserSolAssetRuleOperation = "sendEndUserSolAsset" ) +// Valid indicates whether the value is a known member of the SendEndUserSolAssetRuleOperation enum. +func (e SendEndUserSolAssetRuleOperation) Valid() bool { + switch e { + case SendEndUserSolAsset: + return true + default: + return false + } +} + // Defines values for SendEndUserSolTransactionRuleAction. const ( SendEndUserSolTransactionRuleActionAccept SendEndUserSolTransactionRuleAction = "accept" SendEndUserSolTransactionRuleActionReject SendEndUserSolTransactionRuleAction = "reject" ) +// Valid indicates whether the value is a known member of the SendEndUserSolTransactionRuleAction enum. +func (e SendEndUserSolTransactionRuleAction) Valid() bool { + switch e { + case SendEndUserSolTransactionRuleActionAccept: + return true + case SendEndUserSolTransactionRuleActionReject: + return true + default: + return false + } +} + // Defines values for SendEndUserSolTransactionRuleOperation. const ( SendEndUserSolTransaction SendEndUserSolTransactionRuleOperation = "sendEndUserSolTransaction" ) +// Valid indicates whether the value is a known member of the SendEndUserSolTransactionRuleOperation enum. +func (e SendEndUserSolTransactionRuleOperation) Valid() bool { + switch e { + case SendEndUserSolTransaction: + return true + default: + return false + } +} + // Defines values for SendEvmTransactionRuleAction. const ( SendEvmTransactionRuleActionAccept SendEvmTransactionRuleAction = "accept" SendEvmTransactionRuleActionReject SendEvmTransactionRuleAction = "reject" ) +// Valid indicates whether the value is a known member of the SendEvmTransactionRuleAction enum. +func (e SendEvmTransactionRuleAction) Valid() bool { + switch e { + case SendEvmTransactionRuleActionAccept: + return true + case SendEvmTransactionRuleActionReject: + return true + default: + return false + } +} + // Defines values for SendEvmTransactionRuleOperation. const ( SendEvmTransaction SendEvmTransactionRuleOperation = "sendEvmTransaction" ) +// Valid indicates whether the value is a known member of the SendEvmTransactionRuleOperation enum. +func (e SendEvmTransactionRuleOperation) Valid() bool { + switch e { + case SendEvmTransaction: + return true + default: + return false + } +} + // Defines values for SendSolTransactionRuleAction. const ( SendSolTransactionRuleActionAccept SendSolTransactionRuleAction = "accept" SendSolTransactionRuleActionReject SendSolTransactionRuleAction = "reject" ) +// Valid indicates whether the value is a known member of the SendSolTransactionRuleAction enum. +func (e SendSolTransactionRuleAction) Valid() bool { + switch e { + case SendSolTransactionRuleActionAccept: + return true + case SendSolTransactionRuleActionReject: + return true + default: + return false + } +} + // Defines values for SendSolTransactionRuleOperation. const ( SendSolTransaction SendSolTransactionRuleOperation = "sendSolTransaction" ) +// Valid indicates whether the value is a known member of the SendSolTransactionRuleOperation enum. +func (e SendSolTransactionRuleOperation) Valid() bool { + switch e { + case SendSolTransaction: + return true + default: + return false + } +} + // Defines values for SendUserOperationRuleAction. const ( SendUserOperationRuleActionAccept SendUserOperationRuleAction = "accept" SendUserOperationRuleActionReject SendUserOperationRuleAction = "reject" ) +// Valid indicates whether the value is a known member of the SendUserOperationRuleAction enum. +func (e SendUserOperationRuleAction) Valid() bool { + switch e { + case SendUserOperationRuleActionAccept: + return true + case SendUserOperationRuleActionReject: + return true + default: + return false + } +} + // Defines values for SendUserOperationRuleOperation. const ( SendUserOperation SendUserOperationRuleOperation = "sendUserOperation" ) +// Valid indicates whether the value is a known member of the SendUserOperationRuleOperation enum. +func (e SendUserOperationRuleOperation) Valid() bool { + switch e { + case SendUserOperation: + return true + default: + return false + } +} + +// Defines values for SepaPaymentMethodPaymentRail. +const ( + Sepa SepaPaymentMethodPaymentRail = "sepa" +) + +// Valid indicates whether the value is a known member of the SepaPaymentMethodPaymentRail enum. +func (e SepaPaymentMethodPaymentRail) Valid() bool { + switch e { + case Sepa: + return true + default: + return false + } +} + // Defines values for SignEndUserEvmHashRuleAction. const ( SignEndUserEvmHashRuleActionAccept SignEndUserEvmHashRuleAction = "accept" SignEndUserEvmHashRuleActionReject SignEndUserEvmHashRuleAction = "reject" ) +// Valid indicates whether the value is a known member of the SignEndUserEvmHashRuleAction enum. +func (e SignEndUserEvmHashRuleAction) Valid() bool { + switch e { + case SignEndUserEvmHashRuleActionAccept: + return true + case SignEndUserEvmHashRuleActionReject: + return true + default: + return false + } +} + // Defines values for SignEndUserEvmHashRuleOperation. const ( SignEndUserEvmHash SignEndUserEvmHashRuleOperation = "signEndUserEvmHash" ) +// Valid indicates whether the value is a known member of the SignEndUserEvmHashRuleOperation enum. +func (e SignEndUserEvmHashRuleOperation) Valid() bool { + switch e { + case SignEndUserEvmHash: + return true + default: + return false + } +} + // Defines values for SignEndUserEvmMessageRuleAction. const ( SignEndUserEvmMessageRuleActionAccept SignEndUserEvmMessageRuleAction = "accept" SignEndUserEvmMessageRuleActionReject SignEndUserEvmMessageRuleAction = "reject" ) +// Valid indicates whether the value is a known member of the SignEndUserEvmMessageRuleAction enum. +func (e SignEndUserEvmMessageRuleAction) Valid() bool { + switch e { + case SignEndUserEvmMessageRuleActionAccept: + return true + case SignEndUserEvmMessageRuleActionReject: + return true + default: + return false + } +} + // Defines values for SignEndUserEvmMessageRuleOperation. const ( SignEndUserEvmMessage SignEndUserEvmMessageRuleOperation = "signEndUserEvmMessage" ) -// Defines values for SignEndUserEvmTransactionRuleAction. +// Valid indicates whether the value is a known member of the SignEndUserEvmMessageRuleOperation enum. +func (e SignEndUserEvmMessageRuleOperation) Valid() bool { + switch e { + case SignEndUserEvmMessage: + return true + default: + return false + } +} + +// Defines values for SignEndUserEvmTransactionRuleAction. const ( SignEndUserEvmTransactionRuleActionAccept SignEndUserEvmTransactionRuleAction = "accept" SignEndUserEvmTransactionRuleActionReject SignEndUserEvmTransactionRuleAction = "reject" ) +// Valid indicates whether the value is a known member of the SignEndUserEvmTransactionRuleAction enum. +func (e SignEndUserEvmTransactionRuleAction) Valid() bool { + switch e { + case SignEndUserEvmTransactionRuleActionAccept: + return true + case SignEndUserEvmTransactionRuleActionReject: + return true + default: + return false + } +} + // Defines values for SignEndUserEvmTransactionRuleOperation. const ( SignEndUserEvmTransaction SignEndUserEvmTransactionRuleOperation = "signEndUserEvmTransaction" ) +// Valid indicates whether the value is a known member of the SignEndUserEvmTransactionRuleOperation enum. +func (e SignEndUserEvmTransactionRuleOperation) Valid() bool { + switch e { + case SignEndUserEvmTransaction: + return true + default: + return false + } +} + // Defines values for SignEndUserEvmTypedDataRuleAction. const ( SignEndUserEvmTypedDataRuleActionAccept SignEndUserEvmTypedDataRuleAction = "accept" SignEndUserEvmTypedDataRuleActionReject SignEndUserEvmTypedDataRuleAction = "reject" ) +// Valid indicates whether the value is a known member of the SignEndUserEvmTypedDataRuleAction enum. +func (e SignEndUserEvmTypedDataRuleAction) Valid() bool { + switch e { + case SignEndUserEvmTypedDataRuleActionAccept: + return true + case SignEndUserEvmTypedDataRuleActionReject: + return true + default: + return false + } +} + // Defines values for SignEndUserEvmTypedDataRuleOperation. const ( SignEndUserEvmTypedData SignEndUserEvmTypedDataRuleOperation = "signEndUserEvmTypedData" ) +// Valid indicates whether the value is a known member of the SignEndUserEvmTypedDataRuleOperation enum. +func (e SignEndUserEvmTypedDataRuleOperation) Valid() bool { + switch e { + case SignEndUserEvmTypedData: + return true + default: + return false + } +} + // Defines values for SignEndUserSolMessageRuleAction. const ( SignEndUserSolMessageRuleActionAccept SignEndUserSolMessageRuleAction = "accept" SignEndUserSolMessageRuleActionReject SignEndUserSolMessageRuleAction = "reject" ) +// Valid indicates whether the value is a known member of the SignEndUserSolMessageRuleAction enum. +func (e SignEndUserSolMessageRuleAction) Valid() bool { + switch e { + case SignEndUserSolMessageRuleActionAccept: + return true + case SignEndUserSolMessageRuleActionReject: + return true + default: + return false + } +} + // Defines values for SignEndUserSolMessageRuleOperation. const ( SignEndUserSolMessage SignEndUserSolMessageRuleOperation = "signEndUserSolMessage" ) +// Valid indicates whether the value is a known member of the SignEndUserSolMessageRuleOperation enum. +func (e SignEndUserSolMessageRuleOperation) Valid() bool { + switch e { + case SignEndUserSolMessage: + return true + default: + return false + } +} + // Defines values for SignEndUserSolTransactionRuleAction. const ( SignEndUserSolTransactionRuleActionAccept SignEndUserSolTransactionRuleAction = "accept" SignEndUserSolTransactionRuleActionReject SignEndUserSolTransactionRuleAction = "reject" ) +// Valid indicates whether the value is a known member of the SignEndUserSolTransactionRuleAction enum. +func (e SignEndUserSolTransactionRuleAction) Valid() bool { + switch e { + case SignEndUserSolTransactionRuleActionAccept: + return true + case SignEndUserSolTransactionRuleActionReject: + return true + default: + return false + } +} + // Defines values for SignEndUserSolTransactionRuleOperation. const ( SignEndUserSolTransaction SignEndUserSolTransactionRuleOperation = "signEndUserSolTransaction" ) +// Valid indicates whether the value is a known member of the SignEndUserSolTransactionRuleOperation enum. +func (e SignEndUserSolTransactionRuleOperation) Valid() bool { + switch e { + case SignEndUserSolTransaction: + return true + default: + return false + } +} + // Defines values for SignEvmHashRuleAction. const ( SignEvmHashRuleActionAccept SignEvmHashRuleAction = "accept" SignEvmHashRuleActionReject SignEvmHashRuleAction = "reject" ) +// Valid indicates whether the value is a known member of the SignEvmHashRuleAction enum. +func (e SignEvmHashRuleAction) Valid() bool { + switch e { + case SignEvmHashRuleActionAccept: + return true + case SignEvmHashRuleActionReject: + return true + default: + return false + } +} + // Defines values for SignEvmHashRuleOperation. const ( SignEvmHash SignEvmHashRuleOperation = "signEvmHash" ) +// Valid indicates whether the value is a known member of the SignEvmHashRuleOperation enum. +func (e SignEvmHashRuleOperation) Valid() bool { + switch e { + case SignEvmHash: + return true + default: + return false + } +} + // Defines values for SignEvmMessageRuleAction. const ( SignEvmMessageRuleActionAccept SignEvmMessageRuleAction = "accept" SignEvmMessageRuleActionReject SignEvmMessageRuleAction = "reject" ) +// Valid indicates whether the value is a known member of the SignEvmMessageRuleAction enum. +func (e SignEvmMessageRuleAction) Valid() bool { + switch e { + case SignEvmMessageRuleActionAccept: + return true + case SignEvmMessageRuleActionReject: + return true + default: + return false + } +} + // Defines values for SignEvmMessageRuleOperation. const ( SignEvmMessage SignEvmMessageRuleOperation = "signEvmMessage" ) +// Valid indicates whether the value is a known member of the SignEvmMessageRuleOperation enum. +func (e SignEvmMessageRuleOperation) Valid() bool { + switch e { + case SignEvmMessage: + return true + default: + return false + } +} + // Defines values for SignEvmTransactionRuleAction. const ( SignEvmTransactionRuleActionAccept SignEvmTransactionRuleAction = "accept" SignEvmTransactionRuleActionReject SignEvmTransactionRuleAction = "reject" ) +// Valid indicates whether the value is a known member of the SignEvmTransactionRuleAction enum. +func (e SignEvmTransactionRuleAction) Valid() bool { + switch e { + case SignEvmTransactionRuleActionAccept: + return true + case SignEvmTransactionRuleActionReject: + return true + default: + return false + } +} + // Defines values for SignEvmTransactionRuleOperation. const ( SignEvmTransaction SignEvmTransactionRuleOperation = "signEvmTransaction" ) +// Valid indicates whether the value is a known member of the SignEvmTransactionRuleOperation enum. +func (e SignEvmTransactionRuleOperation) Valid() bool { + switch e { + case SignEvmTransaction: + return true + default: + return false + } +} + // Defines values for SignEvmTypedDataFieldCriterionType. const ( EvmTypedDataField SignEvmTypedDataFieldCriterionType = "evmTypedDataField" ) +// Valid indicates whether the value is a known member of the SignEvmTypedDataFieldCriterionType enum. +func (e SignEvmTypedDataFieldCriterionType) Valid() bool { + switch e { + case EvmTypedDataField: + return true + default: + return false + } +} + // Defines values for SignEvmTypedDataRuleAction. const ( SignEvmTypedDataRuleActionAccept SignEvmTypedDataRuleAction = "accept" SignEvmTypedDataRuleActionReject SignEvmTypedDataRuleAction = "reject" ) +// Valid indicates whether the value is a known member of the SignEvmTypedDataRuleAction enum. +func (e SignEvmTypedDataRuleAction) Valid() bool { + switch e { + case SignEvmTypedDataRuleActionAccept: + return true + case SignEvmTypedDataRuleActionReject: + return true + default: + return false + } +} + // Defines values for SignEvmTypedDataRuleOperation. const ( SignEvmTypedData SignEvmTypedDataRuleOperation = "signEvmTypedData" ) +// Valid indicates whether the value is a known member of the SignEvmTypedDataRuleOperation enum. +func (e SignEvmTypedDataRuleOperation) Valid() bool { + switch e { + case SignEvmTypedData: + return true + default: + return false + } +} + // Defines values for SignEvmTypedDataVerifyingContractCriterionOperator. const ( SignEvmTypedDataVerifyingContractCriterionOperatorIn SignEvmTypedDataVerifyingContractCriterionOperator = "in" SignEvmTypedDataVerifyingContractCriterionOperatorNotIn SignEvmTypedDataVerifyingContractCriterionOperator = "not in" ) +// Valid indicates whether the value is a known member of the SignEvmTypedDataVerifyingContractCriterionOperator enum. +func (e SignEvmTypedDataVerifyingContractCriterionOperator) Valid() bool { + switch e { + case SignEvmTypedDataVerifyingContractCriterionOperatorIn: + return true + case SignEvmTypedDataVerifyingContractCriterionOperatorNotIn: + return true + default: + return false + } +} + // Defines values for SignEvmTypedDataVerifyingContractCriterionType. const ( EvmTypedDataVerifyingContract SignEvmTypedDataVerifyingContractCriterionType = "evmTypedDataVerifyingContract" ) +// Valid indicates whether the value is a known member of the SignEvmTypedDataVerifyingContractCriterionType enum. +func (e SignEvmTypedDataVerifyingContractCriterionType) Valid() bool { + switch e { + case EvmTypedDataVerifyingContract: + return true + default: + return false + } +} + // Defines values for SignSolMessageRuleAction. const ( SignSolMessageRuleActionAccept SignSolMessageRuleAction = "accept" SignSolMessageRuleActionReject SignSolMessageRuleAction = "reject" ) +// Valid indicates whether the value is a known member of the SignSolMessageRuleAction enum. +func (e SignSolMessageRuleAction) Valid() bool { + switch e { + case SignSolMessageRuleActionAccept: + return true + case SignSolMessageRuleActionReject: + return true + default: + return false + } +} + // Defines values for SignSolMessageRuleOperation. const ( SignSolMessage SignSolMessageRuleOperation = "signSolMessage" ) +// Valid indicates whether the value is a known member of the SignSolMessageRuleOperation enum. +func (e SignSolMessageRuleOperation) Valid() bool { + switch e { + case SignSolMessage: + return true + default: + return false + } +} + // Defines values for SignSolTransactionRuleAction. const ( Accept SignSolTransactionRuleAction = "accept" Reject SignSolTransactionRuleAction = "reject" ) +// Valid indicates whether the value is a known member of the SignSolTransactionRuleAction enum. +func (e SignSolTransactionRuleAction) Valid() bool { + switch e { + case Accept: + return true + case Reject: + return true + default: + return false + } +} + // Defines values for SignSolTransactionRuleOperation. const ( SignSolTransaction SignSolTransactionRuleOperation = "signSolTransaction" ) +// Valid indicates whether the value is a known member of the SignSolTransactionRuleOperation enum. +func (e SignSolTransactionRuleOperation) Valid() bool { + switch e { + case SignSolTransaction: + return true + default: + return false + } +} + // Defines values for SiweAuthenticationType. const ( Siwe SiweAuthenticationType = "siwe" ) +// Valid indicates whether the value is a known member of the SiweAuthenticationType enum. +func (e SiweAuthenticationType) Valid() bool { + switch e { + case Siwe: + return true + default: + return false + } +} + // Defines values for SmsAuthenticationType. const ( Sms SmsAuthenticationType = "sms" ) +// Valid indicates whether the value is a known member of the SmsAuthenticationType enum. +func (e SmsAuthenticationType) Valid() bool { + switch e { + case Sms: + return true + default: + return false + } +} + // Defines values for SolAddressCriterionOperator. const ( SolAddressCriterionOperatorIn SolAddressCriterionOperator = "in" SolAddressCriterionOperatorNotIn SolAddressCriterionOperator = "not in" ) +// Valid indicates whether the value is a known member of the SolAddressCriterionOperator enum. +func (e SolAddressCriterionOperator) Valid() bool { + switch e { + case SolAddressCriterionOperatorIn: + return true + case SolAddressCriterionOperatorNotIn: + return true + default: + return false + } +} + // Defines values for SolAddressCriterionType. const ( SolAddress SolAddressCriterionType = "solAddress" ) +// Valid indicates whether the value is a known member of the SolAddressCriterionType enum. +func (e SolAddressCriterionType) Valid() bool { + switch e { + case SolAddress: + return true + default: + return false + } +} + // Defines values for SolDataCriterionType. const ( SolData SolDataCriterionType = "solData" ) +// Valid indicates whether the value is a known member of the SolDataCriterionType enum. +func (e SolDataCriterionType) Valid() bool { + switch e { + case SolData: + return true + default: + return false + } +} + // Defines values for SolDataParameterConditionOperator. const ( - SolDataParameterConditionOperatorEmpty SolDataParameterConditionOperator = ">" - SolDataParameterConditionOperatorEqualEqual SolDataParameterConditionOperator = "==" - SolDataParameterConditionOperatorN1 SolDataParameterConditionOperator = ">=" - SolDataParameterConditionOperatorN2 SolDataParameterConditionOperator = "<" - SolDataParameterConditionOperatorN3 SolDataParameterConditionOperator = "<=" + SolDataParameterConditionOperatorEqualEqual SolDataParameterConditionOperator = "==" + SolDataParameterConditionOperatorGreaterThan SolDataParameterConditionOperator = ">" + SolDataParameterConditionOperatorGreaterThanEqual SolDataParameterConditionOperator = ">=" + SolDataParameterConditionOperatorLessThan SolDataParameterConditionOperator = "<" + SolDataParameterConditionOperatorLessThanEqual SolDataParameterConditionOperator = "<=" ) +// Valid indicates whether the value is a known member of the SolDataParameterConditionOperator enum. +func (e SolDataParameterConditionOperator) Valid() bool { + switch e { + case SolDataParameterConditionOperatorEqualEqual: + return true + case SolDataParameterConditionOperatorGreaterThan: + return true + case SolDataParameterConditionOperatorGreaterThanEqual: + return true + case SolDataParameterConditionOperatorLessThan: + return true + case SolDataParameterConditionOperatorLessThanEqual: + return true + default: + return false + } +} + // Defines values for SolDataParameterConditionListOperator. const ( SolDataParameterConditionListOperatorIn SolDataParameterConditionListOperator = "in" SolDataParameterConditionListOperatorNotIn SolDataParameterConditionListOperator = "not in" ) +// Valid indicates whether the value is a known member of the SolDataParameterConditionListOperator enum. +func (e SolDataParameterConditionListOperator) Valid() bool { + switch e { + case SolDataParameterConditionListOperatorIn: + return true + case SolDataParameterConditionListOperatorNotIn: + return true + default: + return false + } +} + // Defines values for SolMessageCriterionType. const ( SolMessage SolMessageCriterionType = "solMessage" ) +// Valid indicates whether the value is a known member of the SolMessageCriterionType enum. +func (e SolMessageCriterionType) Valid() bool { + switch e { + case SolMessage: + return true + default: + return false + } +} + // Defines values for SolNetworkCriterionNetworks. const ( SolNetworkCriterionNetworksSolana SolNetworkCriterionNetworks = "solana" SolNetworkCriterionNetworksSolanaDevnet SolNetworkCriterionNetworks = "solana-devnet" ) +// Valid indicates whether the value is a known member of the SolNetworkCriterionNetworks enum. +func (e SolNetworkCriterionNetworks) Valid() bool { + switch e { + case SolNetworkCriterionNetworksSolana: + return true + case SolNetworkCriterionNetworksSolanaDevnet: + return true + default: + return false + } +} + // Defines values for SolNetworkCriterionOperator. const ( SolNetworkCriterionOperatorIn SolNetworkCriterionOperator = "in" SolNetworkCriterionOperatorNotIn SolNetworkCriterionOperator = "not in" ) +// Valid indicates whether the value is a known member of the SolNetworkCriterionOperator enum. +func (e SolNetworkCriterionOperator) Valid() bool { + switch e { + case SolNetworkCriterionOperatorIn: + return true + case SolNetworkCriterionOperatorNotIn: + return true + default: + return false + } +} + // Defines values for SolNetworkCriterionType. const ( SolNetwork SolNetworkCriterionType = "solNetwork" ) +// Valid indicates whether the value is a known member of the SolNetworkCriterionType enum. +func (e SolNetworkCriterionType) Valid() bool { + switch e { + case SolNetwork: + return true + default: + return false + } +} + // Defines values for SolValueCriterionOperator. const ( - SolValueCriterionOperatorEmpty SolValueCriterionOperator = ">" - SolValueCriterionOperatorEqualEqual SolValueCriterionOperator = "==" - SolValueCriterionOperatorN1 SolValueCriterionOperator = ">=" - SolValueCriterionOperatorN2 SolValueCriterionOperator = "<" - SolValueCriterionOperatorN3 SolValueCriterionOperator = "<=" + SolValueCriterionOperatorEqualEqual SolValueCriterionOperator = "==" + SolValueCriterionOperatorGreaterThan SolValueCriterionOperator = ">" + SolValueCriterionOperatorGreaterThanEqual SolValueCriterionOperator = ">=" + SolValueCriterionOperatorLessThan SolValueCriterionOperator = "<" + SolValueCriterionOperatorLessThanEqual SolValueCriterionOperator = "<=" ) +// Valid indicates whether the value is a known member of the SolValueCriterionOperator enum. +func (e SolValueCriterionOperator) Valid() bool { + switch e { + case SolValueCriterionOperatorEqualEqual: + return true + case SolValueCriterionOperatorGreaterThan: + return true + case SolValueCriterionOperatorGreaterThanEqual: + return true + case SolValueCriterionOperatorLessThan: + return true + case SolValueCriterionOperatorLessThanEqual: + return true + default: + return false + } +} + // Defines values for SolValueCriterionType. const ( SolValue SolValueCriterionType = "solValue" ) +// Valid indicates whether the value is a known member of the SolValueCriterionType enum. +func (e SolValueCriterionType) Valid() bool { + switch e { + case SolValue: + return true + default: + return false + } +} + // Defines values for SpendPermissionNetwork. const ( SpendPermissionNetworkArbitrum SpendPermissionNetwork = "arbitrum" @@ -770,36 +2443,237 @@ const ( SpendPermissionNetworkPolygon SpendPermissionNetwork = "polygon" ) +// Valid indicates whether the value is a known member of the SpendPermissionNetwork enum. +func (e SpendPermissionNetwork) Valid() bool { + switch e { + case SpendPermissionNetworkArbitrum: + return true + case SpendPermissionNetworkAvalanche: + return true + case SpendPermissionNetworkBase: + return true + case SpendPermissionNetworkBaseSepolia: + return true + case SpendPermissionNetworkEthereum: + return true + case SpendPermissionNetworkEthereumSepolia: + return true + case SpendPermissionNetworkOptimism: + return true + case SpendPermissionNetworkPolygon: + return true + default: + return false + } +} + // Defines values for SplAddressCriterionOperator. const ( In SplAddressCriterionOperator = "in" NotIn SplAddressCriterionOperator = "not in" ) +// Valid indicates whether the value is a known member of the SplAddressCriterionOperator enum. +func (e SplAddressCriterionOperator) Valid() bool { + switch e { + case In: + return true + case NotIn: + return true + default: + return false + } +} + // Defines values for SplAddressCriterionType. const ( SplAddress SplAddressCriterionType = "splAddress" ) +// Valid indicates whether the value is a known member of the SplAddressCriterionType enum. +func (e SplAddressCriterionType) Valid() bool { + switch e { + case SplAddress: + return true + default: + return false + } +} + // Defines values for SplValueCriterionOperator. const ( - SplValueCriterionOperatorEmpty SplValueCriterionOperator = ">" - SplValueCriterionOperatorEqualEqual SplValueCriterionOperator = "==" - SplValueCriterionOperatorN1 SplValueCriterionOperator = ">=" - SplValueCriterionOperatorN2 SplValueCriterionOperator = "<" - SplValueCriterionOperatorN3 SplValueCriterionOperator = "<=" + EqualEqual SplValueCriterionOperator = "==" + GreaterThan SplValueCriterionOperator = ">" + GreaterThanEqual SplValueCriterionOperator = ">=" + LessThan SplValueCriterionOperator = "<" + LessThanEqual SplValueCriterionOperator = "<=" ) +// Valid indicates whether the value is a known member of the SplValueCriterionOperator enum. +func (e SplValueCriterionOperator) Valid() bool { + switch e { + case EqualEqual: + return true + case GreaterThan: + return true + case GreaterThanEqual: + return true + case LessThan: + return true + case LessThanEqual: + return true + default: + return false + } +} + // Defines values for SplValueCriterionType. const ( SplValue SplValueCriterionType = "splValue" ) +// Valid indicates whether the value is a known member of the SplValueCriterionType enum. +func (e SplValueCriterionType) Valid() bool { + switch e { + case SplValue: + return true + default: + return false + } +} + // Defines values for SwapUnavailableResponseLiquidityAvailable. const ( False SwapUnavailableResponseLiquidityAvailable = false ) +// Valid indicates whether the value is a known member of the SwapUnavailableResponseLiquidityAvailable enum. +func (e SwapUnavailableResponseLiquidityAvailable) Valid() bool { + switch e { + case False: + return true + default: + return false + } +} + +// Defines values for SwiftPaymentMethodPaymentRail. +const ( + Swift SwiftPaymentMethodPaymentRail = "swift" +) + +// Valid indicates whether the value is a known member of the SwiftPaymentMethodPaymentRail enum. +func (e SwiftPaymentMethodPaymentRail) Valid() bool { + switch e { + case Swift: + return true + default: + return false + } +} + +// Defines values for TransferFeeType. +const ( + BankFee TransferFeeType = "bank" + ConversionFee TransferFeeType = "conversion" + NetworkFee TransferFeeType = "network" + OtherFee TransferFeeType = "other" +) + +// Valid indicates whether the value is a known member of the TransferFeeType enum. +func (e TransferFeeType) Valid() bool { + switch e { + case BankFee: + return true + case ConversionFee: + return true + case NetworkFee: + return true + case OtherFee: + return true + default: + return false + } +} + +// Defines values for TransferRequestAmountType. +const ( + Source TransferRequestAmountType = "source" + Target TransferRequestAmountType = "target" +) + +// Valid indicates whether the value is a known member of the TransferRequestAmountType enum. +func (e TransferRequestAmountType) Valid() bool { + switch e { + case Source: + return true + case Target: + return true + default: + return false + } +} + +// Defines values for TransferStatus. +const ( + TransferStatusCompleted TransferStatus = "completed" + TransferStatusFailed TransferStatus = "failed" + TransferStatusProcessing TransferStatus = "processing" + TransferStatusQuoted TransferStatus = "quoted" +) + +// Valid indicates whether the value is a known member of the TransferStatus enum. +func (e TransferStatus) Valid() bool { + switch e { + case TransferStatusCompleted: + return true + case TransferStatusFailed: + return true + case TransferStatusProcessing: + return true + case TransferStatusQuoted: + return true + default: + return false + } +} + +// Defines values for TravelRuleBeneficiaryWalletType. +const ( + TravelRuleBeneficiaryWalletTypeCustodial TravelRuleBeneficiaryWalletType = "custodial" + TravelRuleBeneficiaryWalletTypeSelfCustody TravelRuleBeneficiaryWalletType = "self_custody" +) + +// Valid indicates whether the value is a known member of the TravelRuleBeneficiaryWalletType enum. +func (e TravelRuleBeneficiaryWalletType) Valid() bool { + switch e { + case TravelRuleBeneficiaryWalletTypeCustodial: + return true + case TravelRuleBeneficiaryWalletTypeSelfCustody: + return true + default: + return false + } +} + +// Defines values for TravelRuleStatus. +const ( + TravelRuleStatusCompleted TravelRuleStatus = "completed" + TravelRuleStatusIncomplete TravelRuleStatus = "incomplete" +) + +// Valid indicates whether the value is a known member of the TravelRuleStatus enum. +func (e TravelRuleStatus) Valid() bool { + switch e { + case TravelRuleStatusCompleted: + return true + case TravelRuleStatusIncomplete: + return true + default: + return false + } +} + // Defines values for WebhookEventResponseStatus. const ( WebhookEventResponseStatusFailed WebhookEventResponseStatus = "failed" @@ -809,34 +2683,108 @@ const ( WebhookEventResponseStatusSucceeded WebhookEventResponseStatus = "succeeded" ) +// Valid indicates whether the value is a known member of the WebhookEventResponseStatus enum. +func (e WebhookEventResponseStatus) Valid() bool { + switch e { + case WebhookEventResponseStatusFailed: + return true + case WebhookEventResponseStatusPending: + return true + case WebhookEventResponseStatusProcessing: + return true + case WebhookEventResponseStatusRetrying: + return true + case WebhookEventResponseStatusSucceeded: + return true + default: + return false + } +} + // Defines values for X402Version. const ( - X402VersionN1 X402Version = 1 - X402VersionN2 X402Version = 2 + N1 X402Version = 1 + N2 X402Version = 2 ) +// Valid indicates whether the value is a known member of the X402Version enum. +func (e X402Version) Valid() bool { + switch e { + case N1: + return true + case N2: + return true + default: + return false + } +} + // Defines values for X402DiscoveryResourceType. const ( Http X402DiscoveryResourceType = "http" Mcp X402DiscoveryResourceType = "mcp" ) +// Valid indicates whether the value is a known member of the X402DiscoveryResourceType enum. +func (e X402DiscoveryResourceType) Valid() bool { + switch e { + case Http: + return true + case Mcp: + return true + default: + return false + } +} + // Defines values for X402McpRequestJsonrpc. const ( X402McpRequestJsonrpcN20 X402McpRequestJsonrpc = "2.0" ) +// Valid indicates whether the value is a known member of the X402McpRequestJsonrpc enum. +func (e X402McpRequestJsonrpc) Valid() bool { + switch e { + case X402McpRequestJsonrpcN20: + return true + default: + return false + } +} + // Defines values for X402McpResponseJsonrpc. const ( X402McpResponseJsonrpcN20 X402McpResponseJsonrpc = "2.0" ) +// Valid indicates whether the value is a known member of the X402McpResponseJsonrpc enum. +func (e X402McpResponseJsonrpc) Valid() bool { + switch e { + case X402McpResponseJsonrpcN20: + return true + default: + return false + } +} + // Defines values for X402SearchResourcesResponseSearchMethod. const ( Text X402SearchResourcesResponseSearchMethod = "text" Vector X402SearchResourcesResponseSearchMethod = "vector" ) +// Valid indicates whether the value is a known member of the X402SearchResourcesResponseSearchMethod enum. +func (e X402SearchResourcesResponseSearchMethod) Valid() bool { + switch e { + case Text: + return true + case Vector: + return true + default: + return false + } +} + // Defines values for X402SettleErrorReason. const ( X402SettleErrorReasonInsufficientFunds X402SettleErrorReason = "insufficient_funds" @@ -889,6 +2837,110 @@ const ( X402SettleErrorReasonUnknownError X402SettleErrorReason = "unknown_error" ) +// Valid indicates whether the value is a known member of the X402SettleErrorReason enum. +func (e X402SettleErrorReason) Valid() bool { + switch e { + case X402SettleErrorReasonInsufficientFunds: + return true + case X402SettleErrorReasonInvalidExactEvmPayloadAuthorizationFromAddressKyt: + return true + case X402SettleErrorReasonInvalidExactEvmPayloadAuthorizationToAddressKyt: + return true + case X402SettleErrorReasonInvalidExactEvmPayloadAuthorizationTypedDataMessage: + return true + case X402SettleErrorReasonInvalidExactEvmPayloadAuthorizationValidAfter: + return true + case X402SettleErrorReasonInvalidExactEvmPayloadAuthorizationValidBefore: + return true + case X402SettleErrorReasonInvalidExactEvmPayloadAuthorizationValue: + return true + case X402SettleErrorReasonInvalidExactEvmPayloadAuthorizationValueTooLow: + return true + case X402SettleErrorReasonInvalidExactEvmPayloadSignature: + return true + case X402SettleErrorReasonInvalidExactEvmPayloadSignatureAddress: + return true + case X402SettleErrorReasonInvalidExactEvmPermit2PayloadAllowanceRequired: + return true + case X402SettleErrorReasonInvalidExactEvmPermit2PayloadAmount: + return true + case X402SettleErrorReasonInvalidExactEvmPermit2PayloadDeadline: + return true + case X402SettleErrorReasonInvalidExactEvmPermit2PayloadRecipient: + return true + case X402SettleErrorReasonInvalidExactEvmPermit2PayloadSignature: + return true + case X402SettleErrorReasonInvalidExactEvmPermit2PayloadSpender: + return true + case X402SettleErrorReasonInvalidExactEvmPermit2PayloadValidAfter: + return true + case X402SettleErrorReasonInvalidExactSvmPayloadTransaction: + return true + case X402SettleErrorReasonInvalidExactSvmPayloadTransactionAmountMismatch: + return true + case X402SettleErrorReasonInvalidExactSvmPayloadTransactionCannotDeriveReceiverAta: + return true + case X402SettleErrorReasonInvalidExactSvmPayloadTransactionCreateAtaInstruction: + return true + case X402SettleErrorReasonInvalidExactSvmPayloadTransactionCreateAtaInstructionIncorrectAsset: + return true + case X402SettleErrorReasonInvalidExactSvmPayloadTransactionCreateAtaInstructionIncorrectPayee: + return true + case X402SettleErrorReasonInvalidExactSvmPayloadTransactionFeePayerIncludedInInstructionAccounts: + return true + case X402SettleErrorReasonInvalidExactSvmPayloadTransactionFeePayerTransferringFunds: + return true + case X402SettleErrorReasonInvalidExactSvmPayloadTransactionInstructionNotSplTokenTransferChecked: + return true + case X402SettleErrorReasonInvalidExactSvmPayloadTransactionInstructionNotToken2022TransferChecked: + return true + case X402SettleErrorReasonInvalidExactSvmPayloadTransactionInstructions: + return true + case X402SettleErrorReasonInvalidExactSvmPayloadTransactionInstructionsComputeLimitInstruction: + return true + case X402SettleErrorReasonInvalidExactSvmPayloadTransactionInstructionsComputePriceInstruction: + return true + case X402SettleErrorReasonInvalidExactSvmPayloadTransactionInstructionsComputePriceInstructionTooHigh: + return true + case X402SettleErrorReasonInvalidExactSvmPayloadTransactionInstructionsLength: + return true + case X402SettleErrorReasonInvalidExactSvmPayloadTransactionNotATransferInstruction: + return true + case X402SettleErrorReasonInvalidExactSvmPayloadTransactionReceiverAtaNotFound: + return true + case X402SettleErrorReasonInvalidExactSvmPayloadTransactionSenderAtaNotFound: + return true + case X402SettleErrorReasonInvalidExactSvmPayloadTransactionSimulationFailed: + return true + case X402SettleErrorReasonInvalidExactSvmPayloadTransactionTransferToIncorrectAta: + return true + case X402SettleErrorReasonInvalidNetwork: + return true + case X402SettleErrorReasonInvalidPayload: + return true + case X402SettleErrorReasonInvalidPaymentRequirements: + return true + case X402SettleErrorReasonInvalidScheme: + return true + case X402SettleErrorReasonInvalidX402Version: + return true + case X402SettleErrorReasonSettleExactEvmTransactionConfirmationTimedOut: + return true + case X402SettleErrorReasonSettleExactFailedOnchain: + return true + case X402SettleErrorReasonSettleExactNodeFailure: + return true + case X402SettleErrorReasonSettleExactSvmBlockHeightExceeded: + return true + case X402SettleErrorReasonSettleExactSvmTransactionConfirmationTimedOut: + return true + case X402SettleErrorReasonUnknownError: + return true + default: + return false + } +} + // Defines values for X402SupportedPaymentKindNetwork. const ( X402SupportedPaymentKindNetworkArbitrum X402SupportedPaymentKindNetwork = "arbitrum" @@ -908,12 +2960,62 @@ const ( X402SupportedPaymentKindNetworkWorldSepolia X402SupportedPaymentKindNetwork = "world-sepolia" ) +// Valid indicates whether the value is a known member of the X402SupportedPaymentKindNetwork enum. +func (e X402SupportedPaymentKindNetwork) Valid() bool { + switch e { + case X402SupportedPaymentKindNetworkArbitrum: + return true + case X402SupportedPaymentKindNetworkArbitrumSepolia: + return true + case X402SupportedPaymentKindNetworkAvalanche: + return true + case X402SupportedPaymentKindNetworkBase: + return true + case X402SupportedPaymentKindNetworkBaseSepolia: + return true + case X402SupportedPaymentKindNetworkEip155137: + return true + case X402SupportedPaymentKindNetworkEip1558453: + return true + case X402SupportedPaymentKindNetworkEip15584532: + return true + case X402SupportedPaymentKindNetworkPolygon: + return true + case X402SupportedPaymentKindNetworkSolana: + return true + case X402SupportedPaymentKindNetworkSolana5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp: + return true + case X402SupportedPaymentKindNetworkSolanaDevnet: + return true + case X402SupportedPaymentKindNetworkSolanaEtWTRABZaYq6iMfeYKouRu166VU2xqa1: + return true + case X402SupportedPaymentKindNetworkWorld: + return true + case X402SupportedPaymentKindNetworkWorldSepolia: + return true + default: + return false + } +} + // Defines values for X402SupportedPaymentKindScheme. const ( X402SupportedPaymentKindSchemeExact X402SupportedPaymentKindScheme = "exact" X402SupportedPaymentKindSchemeUpto X402SupportedPaymentKindScheme = "upto" ) +// Valid indicates whether the value is a known member of the X402SupportedPaymentKindScheme enum. +func (e X402SupportedPaymentKindScheme) Valid() bool { + switch e { + case X402SupportedPaymentKindSchemeExact: + return true + case X402SupportedPaymentKindSchemeUpto: + return true + default: + return false + } +} + // Defines values for X402V1PaymentPayloadNetwork. const ( X402V1PaymentPayloadNetworkBase X402V1PaymentPayloadNetwork = "base" @@ -923,11 +3025,39 @@ const ( X402V1PaymentPayloadNetworkSolanaDevnet X402V1PaymentPayloadNetwork = "solana-devnet" ) +// Valid indicates whether the value is a known member of the X402V1PaymentPayloadNetwork enum. +func (e X402V1PaymentPayloadNetwork) Valid() bool { + switch e { + case X402V1PaymentPayloadNetworkBase: + return true + case X402V1PaymentPayloadNetworkBaseSepolia: + return true + case X402V1PaymentPayloadNetworkPolygon: + return true + case X402V1PaymentPayloadNetworkSolana: + return true + case X402V1PaymentPayloadNetworkSolanaDevnet: + return true + default: + return false + } +} + // Defines values for X402V1PaymentPayloadScheme. const ( X402V1PaymentPayloadSchemeExact X402V1PaymentPayloadScheme = "exact" ) +// Valid indicates whether the value is a known member of the X402V1PaymentPayloadScheme enum. +func (e X402V1PaymentPayloadScheme) Valid() bool { + switch e { + case X402V1PaymentPayloadSchemeExact: + return true + default: + return false + } +} + // Defines values for X402V1PaymentRequirementsNetwork. const ( X402V1PaymentRequirementsNetworkBase X402V1PaymentRequirementsNetwork = "base" @@ -937,17 +3067,57 @@ const ( X402V1PaymentRequirementsNetworkSolanaDevnet X402V1PaymentRequirementsNetwork = "solana-devnet" ) +// Valid indicates whether the value is a known member of the X402V1PaymentRequirementsNetwork enum. +func (e X402V1PaymentRequirementsNetwork) Valid() bool { + switch e { + case X402V1PaymentRequirementsNetworkBase: + return true + case X402V1PaymentRequirementsNetworkBaseSepolia: + return true + case X402V1PaymentRequirementsNetworkPolygon: + return true + case X402V1PaymentRequirementsNetworkSolana: + return true + case X402V1PaymentRequirementsNetworkSolanaDevnet: + return true + default: + return false + } +} + // Defines values for X402V1PaymentRequirementsScheme. const ( X402V1PaymentRequirementsSchemeExact X402V1PaymentRequirementsScheme = "exact" ) +// Valid indicates whether the value is a known member of the X402V1PaymentRequirementsScheme enum. +func (e X402V1PaymentRequirementsScheme) Valid() bool { + switch e { + case X402V1PaymentRequirementsSchemeExact: + return true + default: + return false + } +} + // Defines values for X402V2PaymentRequirementsScheme. const ( X402V2PaymentRequirementsSchemeExact X402V2PaymentRequirementsScheme = "exact" X402V2PaymentRequirementsSchemeUpto X402V2PaymentRequirementsScheme = "upto" ) +// Valid indicates whether the value is a known member of the X402V2PaymentRequirementsScheme enum. +func (e X402V2PaymentRequirementsScheme) Valid() bool { + switch e { + case X402V2PaymentRequirementsSchemeExact: + return true + case X402V2PaymentRequirementsSchemeUpto: + return true + default: + return false + } +} + // Defines values for X402VerifyInvalidReason. const ( X402VerifyInvalidReasonInsufficientFunds X402VerifyInvalidReason = "insufficient_funds" @@ -995,18 +3165,136 @@ const ( X402VerifyInvalidReasonUnknownError X402VerifyInvalidReason = "unknown_error" ) +// Valid indicates whether the value is a known member of the X402VerifyInvalidReason enum. +func (e X402VerifyInvalidReason) Valid() bool { + switch e { + case X402VerifyInvalidReasonInsufficientFunds: + return true + case X402VerifyInvalidReasonInvalidExactEvmPayloadAuthorizationFromAddressKyt: + return true + case X402VerifyInvalidReasonInvalidExactEvmPayloadAuthorizationToAddressKyt: + return true + case X402VerifyInvalidReasonInvalidExactEvmPayloadAuthorizationTypedDataMessage: + return true + case X402VerifyInvalidReasonInvalidExactEvmPayloadAuthorizationValidAfter: + return true + case X402VerifyInvalidReasonInvalidExactEvmPayloadAuthorizationValidBefore: + return true + case X402VerifyInvalidReasonInvalidExactEvmPayloadAuthorizationValue: + return true + case X402VerifyInvalidReasonInvalidExactEvmPayloadAuthorizationValueTooLow: + return true + case X402VerifyInvalidReasonInvalidExactEvmPayloadSignature: + return true + case X402VerifyInvalidReasonInvalidExactEvmPayloadSignatureAddress: + return true + case X402VerifyInvalidReasonInvalidExactEvmPermit2PayloadAllowanceRequired: + return true + case X402VerifyInvalidReasonInvalidExactEvmPermit2PayloadAmount: + return true + case X402VerifyInvalidReasonInvalidExactEvmPermit2PayloadDeadline: + return true + case X402VerifyInvalidReasonInvalidExactEvmPermit2PayloadRecipient: + return true + case X402VerifyInvalidReasonInvalidExactEvmPermit2PayloadSignature: + return true + case X402VerifyInvalidReasonInvalidExactEvmPermit2PayloadSpender: + return true + case X402VerifyInvalidReasonInvalidExactEvmPermit2PayloadValidAfter: + return true + case X402VerifyInvalidReasonInvalidExactSvmPayloadTransaction: + return true + case X402VerifyInvalidReasonInvalidExactSvmPayloadTransactionAmountMismatch: + return true + case X402VerifyInvalidReasonInvalidExactSvmPayloadTransactionCannotDeriveReceiverAta: + return true + case X402VerifyInvalidReasonInvalidExactSvmPayloadTransactionCreateAtaInstruction: + return true + case X402VerifyInvalidReasonInvalidExactSvmPayloadTransactionCreateAtaInstructionIncorrectAsset: + return true + case X402VerifyInvalidReasonInvalidExactSvmPayloadTransactionCreateAtaInstructionIncorrectPayee: + return true + case X402VerifyInvalidReasonInvalidExactSvmPayloadTransactionFeePayerIncludedInInstructionAccounts: + return true + case X402VerifyInvalidReasonInvalidExactSvmPayloadTransactionFeePayerTransferringFunds: + return true + case X402VerifyInvalidReasonInvalidExactSvmPayloadTransactionInstructionNotSplTokenTransferChecked: + return true + case X402VerifyInvalidReasonInvalidExactSvmPayloadTransactionInstructionNotToken2022TransferChecked: + return true + case X402VerifyInvalidReasonInvalidExactSvmPayloadTransactionInstructions: + return true + case X402VerifyInvalidReasonInvalidExactSvmPayloadTransactionInstructionsComputeLimitInstruction: + return true + case X402VerifyInvalidReasonInvalidExactSvmPayloadTransactionInstructionsComputePriceInstruction: + return true + case X402VerifyInvalidReasonInvalidExactSvmPayloadTransactionInstructionsComputePriceInstructionTooHigh: + return true + case X402VerifyInvalidReasonInvalidExactSvmPayloadTransactionInstructionsLength: + return true + case X402VerifyInvalidReasonInvalidExactSvmPayloadTransactionNotATransferInstruction: + return true + case X402VerifyInvalidReasonInvalidExactSvmPayloadTransactionReceiverAtaNotFound: + return true + case X402VerifyInvalidReasonInvalidExactSvmPayloadTransactionSenderAtaNotFound: + return true + case X402VerifyInvalidReasonInvalidExactSvmPayloadTransactionSimulationFailed: + return true + case X402VerifyInvalidReasonInvalidExactSvmPayloadTransactionTransferToIncorrectAta: + return true + case X402VerifyInvalidReasonInvalidNetwork: + return true + case X402VerifyInvalidReasonInvalidPayload: + return true + case X402VerifyInvalidReasonInvalidPaymentRequirements: + return true + case X402VerifyInvalidReasonInvalidScheme: + return true + case X402VerifyInvalidReasonInvalidX402Version: + return true + case X402VerifyInvalidReasonUnknownError: + return true + default: + return false + } +} + // Defines values for ListTokensForAccountParamsNetwork. const ( ListTokensForAccountParamsNetworkBase ListTokensForAccountParamsNetwork = "base" ListTokensForAccountParamsNetworkBaseSepolia ListTokensForAccountParamsNetwork = "base-sepolia" ) +// Valid indicates whether the value is a known member of the ListTokensForAccountParamsNetwork enum. +func (e ListTokensForAccountParamsNetwork) Valid() bool { + switch e { + case ListTokensForAccountParamsNetworkBase: + return true + case ListTokensForAccountParamsNetworkBaseSepolia: + return true + default: + return false + } +} + // Defines values for GetSQLSchemaParamsDatabase. const ( GetSQLSchemaParamsDatabaseBase GetSQLSchemaParamsDatabase = "base" GetSQLSchemaParamsDatabaseBaseSepolia GetSQLSchemaParamsDatabase = "base_sepolia" ) +// Valid indicates whether the value is a known member of the GetSQLSchemaParamsDatabase enum. +func (e GetSQLSchemaParamsDatabase) Valid() bool { + switch e { + case GetSQLSchemaParamsDatabaseBase: + return true + case GetSQLSchemaParamsDatabaseBaseSepolia: + return true + default: + return false + } +} + // Defines values for SendEvmTransactionWithEndUserAccountJSONBodyNetwork. const ( SendEvmTransactionWithEndUserAccountJSONBodyNetworkArbitrum SendEvmTransactionWithEndUserAccountJSONBodyNetwork = "arbitrum" @@ -1022,6 +3310,36 @@ const ( SendEvmTransactionWithEndUserAccountJSONBodyNetworkWorldSepolia SendEvmTransactionWithEndUserAccountJSONBodyNetwork = "world-sepolia" ) +// Valid indicates whether the value is a known member of the SendEvmTransactionWithEndUserAccountJSONBodyNetwork enum. +func (e SendEvmTransactionWithEndUserAccountJSONBodyNetwork) Valid() bool { + switch e { + case SendEvmTransactionWithEndUserAccountJSONBodyNetworkArbitrum: + return true + case SendEvmTransactionWithEndUserAccountJSONBodyNetworkArbitrumSepolia: + return true + case SendEvmTransactionWithEndUserAccountJSONBodyNetworkAvalanche: + return true + case SendEvmTransactionWithEndUserAccountJSONBodyNetworkBase: + return true + case SendEvmTransactionWithEndUserAccountJSONBodyNetworkBaseSepolia: + return true + case SendEvmTransactionWithEndUserAccountJSONBodyNetworkEthereum: + return true + case SendEvmTransactionWithEndUserAccountJSONBodyNetworkEthereumSepolia: + return true + case SendEvmTransactionWithEndUserAccountJSONBodyNetworkOptimism: + return true + case SendEvmTransactionWithEndUserAccountJSONBodyNetworkPolygon: + return true + case SendEvmTransactionWithEndUserAccountJSONBodyNetworkWorld: + return true + case SendEvmTransactionWithEndUserAccountJSONBodyNetworkWorldSepolia: + return true + default: + return false + } +} + // Defines values for SendEvmAssetWithEndUserAccountJSONBodyNetwork. const ( SendEvmAssetWithEndUserAccountJSONBodyNetworkArbitrum SendEvmAssetWithEndUserAccountJSONBodyNetwork = "arbitrum" @@ -1037,30 +3355,108 @@ const ( SendEvmAssetWithEndUserAccountJSONBodyNetworkWorldSepolia SendEvmAssetWithEndUserAccountJSONBodyNetwork = "world-sepolia" ) +// Valid indicates whether the value is a known member of the SendEvmAssetWithEndUserAccountJSONBodyNetwork enum. +func (e SendEvmAssetWithEndUserAccountJSONBodyNetwork) Valid() bool { + switch e { + case SendEvmAssetWithEndUserAccountJSONBodyNetworkArbitrum: + return true + case SendEvmAssetWithEndUserAccountJSONBodyNetworkArbitrumSepolia: + return true + case SendEvmAssetWithEndUserAccountJSONBodyNetworkAvalanche: + return true + case SendEvmAssetWithEndUserAccountJSONBodyNetworkBase: + return true + case SendEvmAssetWithEndUserAccountJSONBodyNetworkBaseSepolia: + return true + case SendEvmAssetWithEndUserAccountJSONBodyNetworkEthereum: + return true + case SendEvmAssetWithEndUserAccountJSONBodyNetworkEthereumSepolia: + return true + case SendEvmAssetWithEndUserAccountJSONBodyNetworkOptimism: + return true + case SendEvmAssetWithEndUserAccountJSONBodyNetworkPolygon: + return true + case SendEvmAssetWithEndUserAccountJSONBodyNetworkWorld: + return true + case SendEvmAssetWithEndUserAccountJSONBodyNetworkWorldSepolia: + return true + default: + return false + } +} + // Defines values for SendSolanaTransactionWithEndUserAccountJSONBodyNetwork. const ( SendSolanaTransactionWithEndUserAccountJSONBodyNetworkSolana SendSolanaTransactionWithEndUserAccountJSONBodyNetwork = "solana" SendSolanaTransactionWithEndUserAccountJSONBodyNetworkSolanaDevnet SendSolanaTransactionWithEndUserAccountJSONBodyNetwork = "solana-devnet" ) +// Valid indicates whether the value is a known member of the SendSolanaTransactionWithEndUserAccountJSONBodyNetwork enum. +func (e SendSolanaTransactionWithEndUserAccountJSONBodyNetwork) Valid() bool { + switch e { + case SendSolanaTransactionWithEndUserAccountJSONBodyNetworkSolana: + return true + case SendSolanaTransactionWithEndUserAccountJSONBodyNetworkSolanaDevnet: + return true + default: + return false + } +} + // Defines values for SendSolanaAssetWithEndUserAccountJSONBodyNetwork. const ( SendSolanaAssetWithEndUserAccountJSONBodyNetworkSolana SendSolanaAssetWithEndUserAccountJSONBodyNetwork = "solana" SendSolanaAssetWithEndUserAccountJSONBodyNetworkSolanaDevnet SendSolanaAssetWithEndUserAccountJSONBodyNetwork = "solana-devnet" ) +// Valid indicates whether the value is a known member of the SendSolanaAssetWithEndUserAccountJSONBodyNetwork enum. +func (e SendSolanaAssetWithEndUserAccountJSONBodyNetwork) Valid() bool { + switch e { + case SendSolanaAssetWithEndUserAccountJSONBodyNetworkSolana: + return true + case SendSolanaAssetWithEndUserAccountJSONBodyNetworkSolanaDevnet: + return true + default: + return false + } +} + // Defines values for ListEndUsersParamsSort. const ( CreatedAtAsc ListEndUsersParamsSort = "createdAt=asc" CreatedAtDesc ListEndUsersParamsSort = "createdAt=desc" ) +// Valid indicates whether the value is a known member of the ListEndUsersParamsSort enum. +func (e ListEndUsersParamsSort) Valid() bool { + switch e { + case CreatedAtAsc: + return true + case CreatedAtDesc: + return true + default: + return false + } +} + // Defines values for ImportEndUserJSONBodyKeyType. const ( ImportEndUserJSONBodyKeyTypeEvm ImportEndUserJSONBodyKeyType = "evm" ImportEndUserJSONBodyKeyTypeSolana ImportEndUserJSONBodyKeyType = "solana" ) +// Valid indicates whether the value is a known member of the ImportEndUserJSONBodyKeyType enum. +func (e ImportEndUserJSONBodyKeyType) Valid() bool { + switch e { + case ImportEndUserJSONBodyKeyTypeEvm: + return true + case ImportEndUserJSONBodyKeyTypeSolana: + return true + default: + return false + } +} + // Defines values for SendEvmTransactionJSONBodyNetwork. const ( SendEvmTransactionJSONBodyNetworkArbitrum SendEvmTransactionJSONBodyNetwork = "arbitrum" @@ -1076,13 +3472,57 @@ const ( SendEvmTransactionJSONBodyNetworkWorldSepolia SendEvmTransactionJSONBodyNetwork = "world-sepolia" ) +// Valid indicates whether the value is a known member of the SendEvmTransactionJSONBodyNetwork enum. +func (e SendEvmTransactionJSONBodyNetwork) Valid() bool { + switch e { + case SendEvmTransactionJSONBodyNetworkArbitrum: + return true + case SendEvmTransactionJSONBodyNetworkArbitrumSepolia: + return true + case SendEvmTransactionJSONBodyNetworkAvalanche: + return true + case SendEvmTransactionJSONBodyNetworkBase: + return true + case SendEvmTransactionJSONBodyNetworkBaseSepolia: + return true + case SendEvmTransactionJSONBodyNetworkEthereum: + return true + case SendEvmTransactionJSONBodyNetworkEthereumSepolia: + return true + case SendEvmTransactionJSONBodyNetworkOptimism: + return true + case SendEvmTransactionJSONBodyNetworkPolygon: + return true + case SendEvmTransactionJSONBodyNetworkWorld: + return true + case SendEvmTransactionJSONBodyNetworkWorldSepolia: + return true + default: + return false + } +} + // Defines values for RequestEvmFaucetJSONBodyNetwork. const ( - BaseSepolia RequestEvmFaucetJSONBodyNetwork = "base-sepolia" - EthereumHoodi RequestEvmFaucetJSONBodyNetwork = "ethereum-hoodi" - EthereumSepolia RequestEvmFaucetJSONBodyNetwork = "ethereum-sepolia" + RequestEvmFaucetJSONBodyNetworkBaseSepolia RequestEvmFaucetJSONBodyNetwork = "base-sepolia" + RequestEvmFaucetJSONBodyNetworkEthereumHoodi RequestEvmFaucetJSONBodyNetwork = "ethereum-hoodi" + RequestEvmFaucetJSONBodyNetworkEthereumSepolia RequestEvmFaucetJSONBodyNetwork = "ethereum-sepolia" ) +// Valid indicates whether the value is a known member of the RequestEvmFaucetJSONBodyNetwork enum. +func (e RequestEvmFaucetJSONBodyNetwork) Valid() bool { + switch e { + case RequestEvmFaucetJSONBodyNetworkBaseSepolia: + return true + case RequestEvmFaucetJSONBodyNetworkEthereumHoodi: + return true + case RequestEvmFaucetJSONBodyNetworkEthereumSepolia: + return true + default: + return false + } +} + // Defines values for RequestEvmFaucetJSONBodyToken. const ( RequestEvmFaucetJSONBodyTokenCbbtc RequestEvmFaucetJSONBodyToken = "cbbtc" @@ -1091,24 +3531,76 @@ const ( RequestEvmFaucetJSONBodyTokenUsdc RequestEvmFaucetJSONBodyToken = "usdc" ) +// Valid indicates whether the value is a known member of the RequestEvmFaucetJSONBodyToken enum. +func (e RequestEvmFaucetJSONBodyToken) Valid() bool { + switch e { + case RequestEvmFaucetJSONBodyTokenCbbtc: + return true + case RequestEvmFaucetJSONBodyTokenEth: + return true + case RequestEvmFaucetJSONBodyTokenEurc: + return true + case RequestEvmFaucetJSONBodyTokenUsdc: + return true + default: + return false + } +} + // Defines values for ListPoliciesParamsScope. const ( ListPoliciesParamsScopeAccount ListPoliciesParamsScope = "account" ListPoliciesParamsScopeProject ListPoliciesParamsScope = "project" ) +// Valid indicates whether the value is a known member of the ListPoliciesParamsScope enum. +func (e ListPoliciesParamsScope) Valid() bool { + switch e { + case ListPoliciesParamsScopeAccount: + return true + case ListPoliciesParamsScopeProject: + return true + default: + return false + } +} + // Defines values for CreatePolicyJSONBodyScope. const ( - Account CreatePolicyJSONBodyScope = "account" - Project CreatePolicyJSONBodyScope = "project" + CreatePolicyJSONBodyScopeAccount CreatePolicyJSONBodyScope = "account" + CreatePolicyJSONBodyScopeProject CreatePolicyJSONBodyScope = "project" ) +// Valid indicates whether the value is a known member of the CreatePolicyJSONBodyScope enum. +func (e CreatePolicyJSONBodyScope) Valid() bool { + switch e { + case CreatePolicyJSONBodyScopeAccount: + return true + case CreatePolicyJSONBodyScopeProject: + return true + default: + return false + } +} + // Defines values for SendSolanaTransactionJSONBodyNetwork. const ( SendSolanaTransactionJSONBodyNetworkSolana SendSolanaTransactionJSONBodyNetwork = "solana" SendSolanaTransactionJSONBodyNetworkSolanaDevnet SendSolanaTransactionJSONBodyNetwork = "solana-devnet" ) +// Valid indicates whether the value is a known member of the SendSolanaTransactionJSONBodyNetwork enum. +func (e SendSolanaTransactionJSONBodyNetwork) Valid() bool { + switch e { + case SendSolanaTransactionJSONBodyNetworkSolana: + return true + case SendSolanaTransactionJSONBodyNetworkSolanaDevnet: + return true + default: + return false + } +} + // Defines values for RequestSolanaFaucetJSONBodyToken. const ( RequestSolanaFaucetJSONBodyTokenCbtusd RequestSolanaFaucetJSONBodyToken = "cbtusd" @@ -1116,6 +3608,20 @@ const ( RequestSolanaFaucetJSONBodyTokenUsdc RequestSolanaFaucetJSONBodyToken = "usdc" ) +// Valid indicates whether the value is a known member of the RequestSolanaFaucetJSONBodyToken enum. +func (e RequestSolanaFaucetJSONBodyToken) Valid() bool { + switch e { + case RequestSolanaFaucetJSONBodyTokenCbtusd: + return true + case RequestSolanaFaucetJSONBodyTokenSol: + return true + case RequestSolanaFaucetJSONBodyTokenUsdc: + return true + default: + return false + } +} + // Abi Contract ABI Specification following Solidity's external JSON interface format. type Abi = []Abi_Item @@ -1157,7 +3663,7 @@ type AbiFunctionType string // AbiInput Generic ABI item type encapsulating all other types besides `function`. type AbiInput struct { // AdditionalProperties For additional information on the ABI JSON specification, see [the Solidity documentation](https://docs.soliditylang.org/en/latest/abi-spec.html#json). - AdditionalProperties *interface{} `json:"additionalProperties,omitempty"` + AdditionalProperties interface{} `json:"additionalProperties,omitempty"` // Type The type of the ABI item. Type AbiInputType `json:"type"` @@ -1184,6 +3690,36 @@ type AbiParameter struct { // AbiStateMutability State mutability of a function in Solidity. type AbiStateMutability string +// Account defines model for Account. +type Account struct { + // AccountId The ID of the Account, which is a UUID prefixed by the string `account_`. + AccountId AccountId `json:"accountId"` + + // CreatedAt The timestamp when the account was created. + CreatedAt time.Time `json:"createdAt"` + + // Name An optional name for the account. Must be 1-64 characters and can only contain alphanumeric characters, hyphens, and spaces. + Name *AccountName `json:"name,omitempty"` + + // Owner The Owner ID of the Account. + // Owner IDs are UUIDs prefixed with the Owner Type as follows: + // * **Entity**: `entity_` - If the Owner is your Entity, e.g. `entity_af2937b0-9846-4fe7-bfe9-ccc22d935114`. + // Support for Customer-owned accounts (`customer_` prefix) is in development. + Owner Owner `json:"owner"` + + // Type The type of the Account. + Type AccountType `json:"type"` + + // UpdatedAt The timestamp when the account was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// AccountId The ID of the Account, which is a UUID prefixed by the string `account_`. +type AccountId = string + +// AccountName An optional name for the account. Must be 1-64 characters and can only contain alphanumeric characters, hyphens, and spaces. +type AccountName = string + // AccountTokenAddressesResponse Response containing token addresses that an account has received. type AccountTokenAddressesResponse struct { // AccountAddress The account address that was queried. @@ -1196,9 +3732,24 @@ type AccountTokenAddressesResponse struct { TotalCount *int `json:"totalCount,omitempty"` } +// AccountType The type of the Account. +type AccountType string + +// AmountDetail Available and total amounts for a specific currency. +type AmountDetail struct { + // Available The amount that is currently available to be used. + Available string `json:"available"` + + // Total The total amount, including the amount that is currently on hold. + Total string `json:"total"` +} + // Asset The symbol of the asset (e.g., eth, usd, usdc, usdt). type Asset = string +// AssetType The type of the asset. +type AssetType string + // AuthenticationMethod Information about how the end user is authenticated. type AuthenticationMethod struct { union json.RawMessage @@ -1207,6 +3758,22 @@ type AuthenticationMethod struct { // AuthenticationMethods The list of valid authentication methods linked to the end user. type AuthenticationMethods = []AuthenticationMethod +// Balance A balance of an asset. +type Balance struct { + // Amount Amount details denominated in different assets. + // - The keys represent the asset symbols (e.g., "btc", "usd"), - Each value contains available and total amounts. - There will always be an entry for the asset specified in the `asset` field. + Amount map[string]AmountDetail `json:"amount"` + + // Asset An asset, e.g. fiat or crypto. + Asset BalancesAsset `json:"asset"` +} + +// Balances A list of balances for an account. +type Balances struct { + // Balances The list of balances. + Balances []Balance `json:"balances"` +} + // BlockchainAddress A blockchain address. Format varies by network (e.g., 0x-prefixed for EVM, base58 for Solana). type BlockchainAddress = string @@ -1273,6 +3840,57 @@ type CommonSwapResponse struct { // CommonSwapResponseLiquidityAvailable Whether sufficient liquidity is available to settle the swap. All other fields in the response will be empty if this is false. type CommonSwapResponseLiquidityAvailable bool +// CreateAccountRequest defines model for CreateAccountRequest. +type CreateAccountRequest struct { + // Name An optional name for the account. Must be 1-64 characters and can only contain alphanumeric characters, hyphens, and spaces. + Name *AccountName `json:"name,omitempty"` +} + +// CreateCryptoDepositDestinationRequest defines model for CreateCryptoDepositDestinationRequest. +type CreateCryptoDepositDestinationRequest struct { + // AccountId The ID of the Account, which is a UUID prefixed by the string `account_`. + AccountId AccountId `json:"accountId"` + + // Crypto Crypto-specific details. Required when `type` is `crypto`. + Crypto CreateDepositDestinationCrypto `json:"crypto"` + + // Metadata Optional metadata as key-value pairs. Use this to store additional structured information on a resource, such as customer IDs, order references, or any application-specific data. Up to 10 key/value pairs may be provided. Keys and values are both strings. Keys must be ≤ 40 characters; values must be ≤ 500 characters. + Metadata *Metadata `json:"metadata,omitempty"` + + // Target The intended target for deposited funds. + Target *DepositDestinationTarget `json:"target,omitempty"` + Type CreateCryptoDepositDestinationRequestType `json:"type"` +} + +// CreateCryptoDepositDestinationRequestType defines model for CreateCryptoDepositDestinationRequest.Type. +type CreateCryptoDepositDestinationRequestType string + +// CreateDepositDestinationCrypto Crypto-specific details for creating a deposit destination. +type CreateDepositDestinationCrypto struct { + // Network The blockchain network for the payment. Supported networks depend on the account type. See [API and Network Support](https://docs.cdp.coinbase.com/api-reference/payment-apis/supported-networks-assets#by-asset-and-network) for more details. + Network Network `json:"network"` +} + +// CreateDepositDestinationRequest Request to create a new deposit destination. Provide the type-specific details matching the chosen `type`. +type CreateDepositDestinationRequest struct { + union json.RawMessage +} + +// CreateDepositDestinationRequestBase Common fields for creating a deposit destination. +type CreateDepositDestinationRequestBase struct { + // AccountId The ID of the Account, which is a UUID prefixed by the string `account_`. + AccountId AccountId `json:"accountId"` + + // Metadata Optional metadata as key-value pairs. Use this to store additional structured information on a resource, such as customer IDs, order references, or any application-specific data. Up to 10 key/value pairs may be provided. Keys and values are both strings. Keys must be ≤ 40 characters; values must be ≤ 500 characters. + Metadata *Metadata `json:"metadata,omitempty"` + + // Target The intended target for deposited funds. + Target *DepositDestinationTarget `json:"target,omitempty"` + + // Type The type of deposit destination. + Type DepositDestinationType `json:"type"` +} + // CreateEndUserEvmSwapCriteria A schema for specifying criteria for the createEndUserEvmSwap operation. type CreateEndUserEvmSwapCriteria = []CreateEndUserEvmSwapCriteria_Item @@ -1427,6 +4045,44 @@ type CreateSwapQuoteResponseWrapper struct { union json.RawMessage } +// CreateTransferSource The source of the transfer. +type CreateTransferSource struct { + union json.RawMessage +} + +// CryptoDepositDestination A cryptocurrency deposit destination. +type CryptoDepositDestination struct { + // AccountId The ID of the Account, which is a UUID prefixed by the string `account_`. + AccountId AccountId `json:"accountId"` + + // CreatedAt The timestamp when the deposit destination was created. + CreatedAt time.Time `json:"createdAt"` + + // Crypto Crypto-specific details for this deposit destination. Always populated in responses. Contains the network and address. + Crypto DepositDestinationCrypto `json:"crypto"` + + // DepositDestinationId The ID of the Deposit Destination, which is a UUID prefixed by the string `depositDestination_`. + DepositDestinationId DepositDestinationId `json:"depositDestinationId"` + + // Metadata Optional metadata as key-value pairs. Use this to store additional structured information on a resource, such as customer IDs, order references, or any application-specific data. Up to 10 key/value pairs may be provided. Keys and values are both strings. Keys must be ≤ 40 characters; values must be ≤ 500 characters. + Metadata *Metadata `json:"metadata,omitempty"` + + // Status The status of the deposit destination. + Status DepositDestinationStatus `json:"status"` + + // Target The intended target for deposited funds. + Target *DepositDestinationTarget `json:"target,omitempty"` + + // Type The type of deposit destination. + Type CryptoDepositDestinationType `json:"type"` + + // UpdatedAt The timestamp when the deposit destination was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// CryptoDepositDestinationType The type of deposit destination. +type CryptoDepositDestinationType string + // DateOfBirth Date of birth. type DateOfBirth struct { // Day Day of birth (01-31). @@ -1439,6 +4095,112 @@ type DateOfBirth struct { Year *string `json:"year,omitempty"` } +// DepositDestination A deposit destination for receiving funds to an account. +type DepositDestination struct { + union json.RawMessage +} + +// DepositDestinationCrypto Crypto-specific deposit destination details. In responses, this object is always present. Contains the network and address for the deposit destination. +type DepositDestinationCrypto struct { + // Address A blockchain address. Format varies by network (e.g., 0x-prefixed for EVM, base58 for Solana). + Address BlockchainAddress `json:"address"` + + // Network The blockchain network for the payment. Supported networks depend on the account type. See [API and Network Support](https://docs.cdp.coinbase.com/api-reference/payment-apis/supported-networks-assets#by-asset-and-network) for more details. + Network Network `json:"network"` +} + +// DepositDestinationId The ID of the Deposit Destination, which is a UUID prefixed by the string `depositDestination_`. +type DepositDestinationId = string + +// DepositDestinationReference A reference to the deposit destination associated with the transfer. +type DepositDestinationReference struct { + // Id The ID of the Deposit Destination, which is a UUID prefixed by the string `depositDestination_`. + Id DepositDestinationId `json:"id"` +} + +// DepositDestinationStatus The status of the deposit destination. +type DepositDestinationStatus string + +// DepositDestinationTarget The intended target for deposited funds. +type DepositDestinationTarget struct { + union json.RawMessage +} + +// DepositDestinationTargetAccount The account and asset where incoming deposits should be credited. +type DepositDestinationTargetAccount struct { + // AccountId The ID of the CDP Account to which deposited funds should be transferred. + AccountId *AccountId `json:"accountId,omitempty"` + + // Asset The symbol of the asset that should land in the target account. + Asset Asset `json:"asset"` +} + +// DepositDestinationType The type of deposit destination. +type DepositDestinationType = string + +// DepositTravelRuleBeneficiary Beneficiary information for a deposit travel rule submission. +type DepositTravelRuleBeneficiary struct { + // Name Full name of the beneficiary. + Name *string `json:"name,omitempty"` +} + +// DepositTravelRuleOriginator Originator information for a deposit travel rule submission. +type DepositTravelRuleOriginator struct { + // Address A physical address with standard address components including street, city, state/province, postal code, and country. + Address *PhysicalAddress `json:"address,omitempty"` + + // DateOfBirth Date of birth. + DateOfBirth *DateOfBirth `json:"dateOfBirth,omitempty"` + + // Name Full name of the originator. + Name *string `json:"name,omitempty"` + + // PersonalId Government-issued personal identification number for the originator. + PersonalId *string `json:"personalId,omitempty"` + + // VirtualAssetServiceProvider Information about the Virtual Asset Service Provider (VASP) for a deposit travel rule submission. + VirtualAssetServiceProvider *DepositTravelRuleVasp `json:"virtualAssetServiceProvider,omitempty"` + + // WalletType The type of the originator's wallet. + WalletType *DepositTravelRuleOriginatorWalletType `json:"walletType,omitempty"` +} + +// DepositTravelRuleOriginatorWalletType The type of the originator's wallet. +type DepositTravelRuleOriginatorWalletType string + +// DepositTravelRuleRequest Request body for submitting travel rule information for a deposit transfer. Required fields vary by jurisdiction. +type DepositTravelRuleRequest struct { + // Beneficiary Beneficiary information for a deposit travel rule submission. + Beneficiary *DepositTravelRuleBeneficiary `json:"beneficiary,omitempty"` + + // IsSelf Indicates whether the user attests that the originating wallet belongs to them. + IsSelf *bool `json:"isSelf,omitempty"` + + // Originator Originator information for a deposit travel rule submission. + Originator *DepositTravelRuleOriginator `json:"originator,omitempty"` +} + +// DepositTravelRuleResponse Response from submitting travel rule information for a deposit transfer. +type DepositTravelRuleResponse struct { + // MissingFields List of field paths that are still required to complete travel rule compliance. Each entry is a dot-separated path (e.g., "originator.name", "originator.address.countryCode"). Empty when status is "completed". + MissingFields *[]string `json:"missingFields,omitempty"` + + // Reason Additional context about the current status. Present when status is `incomplete` to explain what needs to be fixed before the transfer can proceed. + Reason *string `json:"reason,omitempty"` + + // Status The status of a travel rule submission. + Status TravelRuleStatus `json:"status"` +} + +// DepositTravelRuleVasp Information about the Virtual Asset Service Provider (VASP) for a deposit travel rule submission. +type DepositTravelRuleVasp struct { + // Identifier The Legal Entity Identifier (LEI) of the Virtual Asset Service Provider (VASP). + Identifier *string `json:"identifier,omitempty"` + + // Name The name of the Virtual Asset Service Provider (VASP). + Name *string `json:"name,omitempty"` +} + // Description A human-readable description. type Description = string @@ -1495,6 +4257,12 @@ type EIP712Message struct { // Each key corresponds to a type name (e.g., "`EIP712Domain`", "`PermitTransferFrom`"). type EIP712Types = map[string]interface{} +// EmailAddress The target of the payment is an email address. +type EmailAddress struct { + // Email The email address of the recipient. The recipient will need to have an account with Coinbase or onboard to Coinbase to receive the payment. + Email openapi_types.Email `json:"email"` +} + // EmailAuthentication Information about an end user who authenticates using a one-time password sent to their email address. type EmailAuthentication struct { // Email The email address of the end user. @@ -1507,6 +4275,15 @@ type EmailAuthentication struct { // EmailAuthenticationType The type of authentication information. type EmailAuthenticationType string +// EmailInstrument defines model for EmailInstrument. +type EmailInstrument struct { + // Asset Asset symbol of the payment received by the recipient. + Asset Asset `json:"asset"` + + // Email The email address of the recipient. The recipient will need to have an account with Coinbase or onboard to Coinbase to receive the payment. + Email openapi_types.Email `json:"email"` +} + // EndUser Information about the end user. type EndUser struct { // AuthenticationMethods The list of valid authentication methods linked to the end user. @@ -1519,14 +4296,14 @@ type EndUser struct { EvmAccountObjects []EndUserEvmAccount `json:"evmAccountObjects"` // EvmAccounts **DEPRECATED**: Use `evmAccountObjects` instead for richer account information. The list of EVM account addresses associated with the end user. End users can have up to 10 EVM accounts. - // Deprecated: + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set EvmAccounts []string `json:"evmAccounts"` // EvmSmartAccountObjects The list of EVM smart accounts associated with the end user. Each EVM EOA can own one smart account. EvmSmartAccountObjects []EndUserEvmSmartAccount `json:"evmSmartAccountObjects"` // EvmSmartAccounts **DEPRECATED**: Use `evmSmartAccountObjects` instead for richer account information including owner relationships. The list of EVM smart account addresses associated with the end user. Each EVM EOA can own one smart account. - // Deprecated: + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set EvmSmartAccounts []string `json:"evmSmartAccounts"` // MfaMethods Information about the end user's MFA enrollments. @@ -1536,7 +4313,7 @@ type EndUser struct { SolanaAccountObjects []EndUserSolanaAccount `json:"solanaAccountObjects"` // SolanaAccounts **DEPRECATED**: Use `solanaAccountObjects` instead for richer account information. The list of Solana account addresses associated with the end user. End users can have up to 10 Solana accounts. - // Deprecated: + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set SolanaAccounts []string `json:"solanaAccounts"` // UserId A stable, unique identifier for the end user. The `userId` must be unique across all end users in the developer's CDP Project. It must be between 1 and 100 characters long and can only contain alphanumeric characters and hyphens. @@ -1877,6 +4654,45 @@ type EvmUserOperationStatus string // EvmUserOperationNetwork The network the user operation is for. type EvmUserOperationNetwork string +// FedwireDetails Details specific to Fedwire (domestic USD wire) payment methods. +type FedwireDetails struct { + // AccountLast4 The last 4 digits of the bank account number. + AccountLast4 string `json:"accountLast4"` + + // Asset The asset for this payment method. Always `usd` for Fedwire. + Asset string `json:"asset"` + + // BankName The name of the bank. + BankName string `json:"bankName"` + + // RoutingNumber The ABA routing number of the bank. + RoutingNumber string `json:"routingNumber"` +} + +// FedwirePaymentMethod defines model for FedwirePaymentMethod. +type FedwirePaymentMethod struct { + // Active Whether the payment method is active and can be used in transfers. A payment method may be inactive due to verification requirements or entity-level restrictions. + Active bool `json:"active"` + + // CreatedAt The timestamp when the payment method was created. + CreatedAt time.Time `json:"createdAt"` + + // Fedwire Fedwire (domestic USD wire) details. + Fedwire FedwireDetails `json:"fedwire"` + + // PaymentMethodId The ID of the Payment Method, which is a UUID prefixed by the string `paymentMethod_`. + PaymentMethodId PaymentMethodId `json:"paymentMethodId"` + + // PaymentRail The payment rail for this payment method. + PaymentRail FedwirePaymentMethodPaymentRail `json:"paymentRail"` + + // UpdatedAt The timestamp when the payment method was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// FedwirePaymentMethodPaymentRail The payment rail for this payment method. +type FedwirePaymentMethodPaymentRail string + // GetSwapPriceResponse defines model for GetSwapPriceResponse. type GetSwapPriceResponse struct { // BlockNumber The block number at which the liquidity conditions were examined. @@ -2083,6 +4899,9 @@ type NetUSDChangeCriterionOperator string // NetUSDChangeCriterionType The type of criterion to use. This should be `netUSDChange`. type NetUSDChangeCriterionType string +// Network The blockchain network for the payment. Supported networks depend on the account type. See [API and Network Support](https://docs.cdp.coinbase.com/api-reference/payment-apis/supported-networks-assets#by-asset-and-network) for more details. +type Network string + // OAuth2Authentication Information about an end user who authenticates using a third-party provider. type OAuth2Authentication struct { // Email The email address of the end user contained within the user's ID token, if available from third-party OAuth2 provider's token exchange. @@ -2104,6 +4923,34 @@ type OAuth2Authentication struct { // OAuth2ProviderType The type of OAuth2 provider. type OAuth2ProviderType string +// OnchainAddress The target of the payment is an onchain address. +type OnchainAddress struct { + // Address The onchain crypto address of the recipient. + // + // Examples: + // - EVM address: 0xabc1234567890abcdef1234567890abcdef123456 + // - Solana address: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + // - XRP address: rhccc5p23aKiCGFcEqqnjEfLRZ6xEvfy3s + Address BlockchainAddress `json:"address"` + + // Asset Asset symbol of the payment received by the recipient. + Asset Asset `json:"asset"` + + // DestinationTag The destination tag of the onchain address. Destination tags are used by certain networks + // (primarily XRP/Ripple) to identify specific recipients when multiple users share a single address. + // The tag ensures funds are credited to the correct account within the shared address. + // + // Examples by network: + // - XRP/Ripple: Numeric values like "1234567890" or "123456" + // - Stellar (XLM): Memos which can be text, ID, or hash format + // + // Note: Most networks (Ethereum, Bitcoin, Solana) do not use destination tags. + DestinationTag *string `json:"destinationTag,omitempty"` + + // Network The blockchain network for the payment. Supported networks depend on the account type. See [API and Network Support](https://docs.cdp.coinbase.com/api-reference/payment-apis/supported-networks-assets#by-asset-and-network) for more details. + Network Network `json:"network"` +} + // OnchainDataColumnSchema Schema definition for a table column. type OnchainDataColumnSchema struct { // Description Human-readable description of the column. @@ -2368,6 +5215,72 @@ type OnrampUserLimit struct { Remaining string `json:"remaining"` } +// OriginatingBankAccountUS The originating US bank account details for the transfer source. Present when funds were deposited from an external bank account into a deposit destination. Only the last 4 digits of the account number are exposed. +type OriginatingBankAccountUS struct { + // AccountLast4 The last 4 digits of the originating bank account number. + AccountLast4 string `json:"accountLast4"` + + // BankName The name of the bank that originated the deposit. + BankName string `json:"bankName"` + + // Currency The fiat currency of the deposit (e.g., `usd`). + Currency string `json:"currency"` +} + +// Owner The Owner ID of the Account. +// Owner IDs are UUIDs prefixed with the Owner Type as follows: +// * **Entity**: `entity_` - If the Owner is your Entity, e.g. `entity_af2937b0-9846-4fe7-bfe9-ccc22d935114`. +// Support for Customer-owned accounts (`customer_` prefix) is in development. +type Owner = string + +// PaymentMethod The Payment Method specific details for the transfer. +type PaymentMethod struct { + // Asset The symbol of the asset (e.g., eth, usd, usdc, usdt). + Asset Asset `json:"asset"` + + // PaymentMethodId The ID of the Payment Method. + PaymentMethodId string `json:"paymentMethodId"` +} + +// PaymentMethodBase Common properties shared by all payment method types. +type PaymentMethodBase struct { + // Active Whether the payment method is active and can be used in transfers. A payment method may be inactive due to verification requirements or entity-level restrictions. + Active bool `json:"active"` + + // CreatedAt The timestamp when the payment method was created. + CreatedAt time.Time `json:"createdAt"` + + // PaymentMethodId The ID of the Payment Method, which is a UUID prefixed by the string `paymentMethod_`. + PaymentMethodId PaymentMethodId `json:"paymentMethodId"` + + // UpdatedAt The timestamp when the payment method was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// PaymentMethodId The ID of the Payment Method, which is a UUID prefixed by the string `paymentMethod_`. +type PaymentMethodId = string + +// PhysicalAddress A physical address with standard address components including street, city, state/province, postal code, and country. +type PhysicalAddress struct { + // City City or locality. + City *string `json:"city,omitempty"` + + // CountryCode ISO 3166-1 alpha-2 country code (2 characters). See https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes. + CountryCode *string `json:"countryCode,omitempty"` + + // Line1 Primary street address. + Line1 *string `json:"line1,omitempty"` + + // Line2 Secondary address information. + Line2 *string `json:"line2,omitempty"` + + // PostCode Postal or ZIP code. + PostCode *string `json:"postCode,omitempty"` + + // State State, province, or region. + State *string `json:"state,omitempty"` +} + // Policy defines model for Policy. type Policy struct { // CreatedAt The ISO 8601 timestamp at which the Policy was created. @@ -2636,6 +5549,45 @@ type SendUserOperationRuleAction string // SendUserOperationRuleOperation The operation to which the rule applies. Every element of the `criteria` array must match the specified operation. type SendUserOperationRuleOperation string +// SepaDetails Details specific to SEPA (Single Euro Payments Area) payment methods. +type SepaDetails struct { + // Asset The asset for this payment method. Always `eur` for SEPA. + Asset string `json:"asset"` + + // BankName The name of the bank. + BankName string `json:"bankName"` + + // Bic The Bank Identifier Code (BIC) / SWIFT code. + Bic string `json:"bic"` + + // IbanLast4 The last 4 characters of the IBAN. + IbanLast4 string `json:"ibanLast4"` +} + +// SepaPaymentMethod defines model for SepaPaymentMethod. +type SepaPaymentMethod struct { + // Active Whether the payment method is active and can be used in transfers. A payment method may be inactive due to verification requirements or entity-level restrictions. + Active bool `json:"active"` + + // CreatedAt The timestamp when the payment method was created. + CreatedAt time.Time `json:"createdAt"` + + // PaymentMethodId The ID of the Payment Method, which is a UUID prefixed by the string `paymentMethod_`. + PaymentMethodId PaymentMethodId `json:"paymentMethodId"` + + // PaymentRail The payment rail for this payment method. + PaymentRail SepaPaymentMethodPaymentRail `json:"paymentRail"` + + // Sepa SEPA (Single Euro Payments Area) details. + Sepa SepaDetails `json:"sepa"` + + // UpdatedAt The timestamp when the payment method was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// SepaPaymentMethodPaymentRail The payment rail for this payment method. +type SepaPaymentMethodPaymentRail string + // SignEndUserEvmHashRule defines model for SignEndUserEvmHashRule. type SignEndUserEvmHashRule struct { // Action Whether any attempts to sign a hash will be accepted or rejected. This rule does not accept any criteria. @@ -3290,6 +6242,49 @@ type SwapUnavailableResponse struct { // SwapUnavailableResponseLiquidityAvailable Whether sufficient liquidity is available to settle the swap. All other fields in the response will be empty if this is false. type SwapUnavailableResponseLiquidityAvailable bool +// SwiftDetails Details specific to SWIFT (international wire) payment methods. +type SwiftDetails struct { + // AccountLast4 The last 4 characters of the account identifier. For IBAN-based accounts (e.g., EU), this is the last 4 characters of the IBAN. For account number-based accounts (e.g., US), this is the last 4 digits of the account number. + AccountLast4 string `json:"accountLast4"` + + // Asset The asset for this payment method (e.g., `eur`, `gbp`). + Asset string `json:"asset"` + + // BankName The name of the bank. + BankName string `json:"bankName"` + + // Bic The Bank Identifier Code (BIC) / SWIFT code. + Bic string `json:"bic"` + + // IbanLast4 Deprecated: use `accountLast4` instead. The last 4 characters of the account identifier. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + IbanLast4 *string `json:"ibanLast4,omitempty"` +} + +// SwiftPaymentMethod defines model for SwiftPaymentMethod. +type SwiftPaymentMethod struct { + // Active Whether the payment method is active and can be used in transfers. A payment method may be inactive due to verification requirements or entity-level restrictions. + Active bool `json:"active"` + + // CreatedAt The timestamp when the payment method was created. + CreatedAt time.Time `json:"createdAt"` + + // PaymentMethodId The ID of the Payment Method, which is a UUID prefixed by the string `paymentMethod_`. + PaymentMethodId PaymentMethodId `json:"paymentMethodId"` + + // PaymentRail The payment rail for this payment method. + PaymentRail SwiftPaymentMethodPaymentRail `json:"paymentRail"` + + // Swift SWIFT (international wire) details. + Swift SwiftDetails `json:"swift"` + + // UpdatedAt The timestamp when the payment method was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// SwiftPaymentMethodPaymentRail The payment rail for this payment method. +type SwiftPaymentMethodPaymentRail string + // TelegramAuthentication Information about an end user who authenticates using Telegram. type TelegramAuthentication struct { // AuthDate The Telegram user's last login as a Unix timestamp. @@ -3368,84 +6363,399 @@ type TokenFee struct { Token string `json:"token"` } -// Uri A valid URI. -type Uri = string +// Transfer A Transfer represents all the information needed to execute a transfer and tracks the lifecycle of a transfer from initiation through completion or failure. +type Transfer struct { + // CompletedAt The date and time the transfer was completed. + CompletedAt *time.Time `json:"completedAt,omitempty"` -// Url A valid HTTP or HTTPS URL. -type Url = string + // CreatedAt The date and time the transfer was created. Required when validateOnly is false. + CreatedAt *time.Time `json:"createdAt,omitempty"` -// UserOperationReceipt The receipt that contains information about the execution of user operation. -type UserOperationReceipt struct { - // BlockHash The block hash of the block including the transaction as 0x-prefixed string. - BlockHash *string `json:"blockHash,omitempty"` + // Details Additional details about the transfer. For example, if the transfer was sent to a deposit destination, the information about that destination will be included in this field. + Details *TransferDetails `json:"details,omitempty"` - // BlockNumber The block height (number) of the block including the transaction. - BlockNumber *int `json:"blockNumber,omitempty"` + // Estimate A point-in-time snapshot of estimated values for a transfer where exact amounts cannot be locked in at quote time (e.g., when the executed rate is determined at execution time and moves with the market). + // + // Present in both pre-execution and post-execution states: + // * **Quoted state:** top-level fields whose values cannot be guaranteed are absent; + // `estimate` holds their estimated values. + // + // * **Completed state:** top-level fields contain the actual executed values; + // `estimate` is retained as an immutable audit snapshot of the pre-execution estimate. + Estimate *TransferEstimate `json:"estimate,omitempty"` - // GasUsed The gas used for landing this user operation. - GasUsed *string `json:"gasUsed,omitempty"` + // ExchangeRate Exchange rate information for currency conversion. The rate indicates how much of the target asset is equivalent to one unit of the source asset. + ExchangeRate *TransferExchangeRate `json:"exchangeRate,omitempty"` - // Revert The revert data if the user operation has reverted. - Revert *UserOperationReceiptRevert `json:"revert,omitempty"` + // ExecutedAt The date and time the transfer was executed and moved to processing. Only present when status has progressed beyond `quoted`. + ExecutedAt *time.Time `json:"executedAt,omitempty"` - // TransactionHash The hash of this transaction as 0x-prefixed string. - TransactionHash *string `json:"transactionHash,omitempty"` -} + // ExpiresAt The date and time when this transfer will expire if not executed. Only present for `quoted` status. A new transfer must be created to obtain an updated quote after expiration. Required when validateOnly is false. + ExpiresAt *time.Time `json:"expiresAt,omitempty"` -// UserOperationReceiptRevert The revert data if the user operation has reverted. -type UserOperationReceiptRevert struct { - // Data The 0x-prefixed raw hex string. - Data string `json:"data"` + // FailureReason The reason for failure, if the transfer failed. Only present when status is `failed`. + FailureReason *string `json:"failureReason,omitempty"` - // Message Human-readable revert reason if able to decode. - Message string `json:"message"` -} + // Fees The fees associated with this transfer. Different transfer types have different fee structures. + // + // **NOTE:** These examples are not exhaustive. + // + // Common examples: + // * **Crypto transfers**: Network fees (gas) paid in the native token + // * **Fiat conversions**: Processing fees + exchange fees in USD + // * **Wire transfers**: Wire fees ($15) + processing fees ($5) in USD + // * **Crypto conversions**: Spread fees paid in the source asset. + Fees *TransferFees `json:"fees,omitempty"` -// WebhookEventListResponse Response containing a list of webhook event delivery attempts. -type WebhookEventListResponse struct { - // Events The list of webhook event delivery attempts. - Events []WebhookEventResponse `json:"events"` -} + // Metadata Optional metadata as key-value pairs. Use this to store additional structured information on a resource, such as customer IDs, order references, or any application-specific data. Up to 10 key/value pairs may be provided. Keys and values are both strings. Keys must be ≤ 40 characters; values must be ≤ 500 characters. + Metadata *Metadata `json:"metadata,omitempty"` -// WebhookEventResponse Details of a webhook event delivery attempt for a subscription. -type WebhookEventResponse struct { - // CreatedAt Timestamp when the event delivery attempt was created. - CreatedAt time.Time `json:"createdAt"` + // Source The source of the transfer. + Source TransferSource `json:"source"` - // EventId Unique identifier for the webhook event. - EventId string `json:"eventId"` + // SourceAmount The amount of the source asset that will be transferred out, as a decimal string in standard unit denomination. + SourceAmount *string `json:"sourceAmount,omitempty"` - // EventTypeName The type of event that was delivered (e.g., "onchain.activity.detected"). - EventTypeName string `json:"eventTypeName"` + // SourceAsset The asset symbol of the source amount. + SourceAsset *Asset `json:"sourceAsset,omitempty"` - // Response Details of the HTTP response received from the webhook target. - Response *WebhookEventResponseDetail `json:"response,omitempty"` + // Status The current status of the transfer, indicating what action you need to take next. Required when validateOnly is false. + Status *TransferStatus `json:"status,omitempty"` - // RetryCount Number of delivery retry attempts so far. - RetryCount int `json:"retryCount"` + // Target The target of the transfer. + Target TransferTarget `json:"target"` - // Status Current delivery status of the event. - Status WebhookEventResponseStatus `json:"status"` + // TargetAmount The amount of the target asset that will be received, as a decimal string in standard unit denomination. + TargetAmount *string `json:"targetAmount,omitempty"` - // SucceededAt Timestamp when the event was successfully delivered. Only present if status is "succeeded". - SucceededAt *time.Time `json:"succeededAt,omitempty"` + // TargetAsset The asset symbol of the target amount. + TargetAsset *Asset `json:"targetAsset,omitempty"` + + // TransferId The ID of the transfer. Required when validateOnly is false. + TransferId *string `json:"transferId,omitempty"` + + // UpdatedAt The date and time the transfer was last updated. Required when validateOnly is false. + UpdatedAt *time.Time `json:"updatedAt,omitempty"` } -// WebhookEventResponseStatus Current delivery status of the event. -type WebhookEventResponseStatus string +// TransferDetails Additional details about the transfer. For example, if the transfer was sent to a deposit destination, the information about that destination will be included in this field. +type TransferDetails struct { + // DepositDestination A reference to the deposit destination associated with the transfer. + DepositDestination *DepositDestinationReference `json:"depositDestination,omitempty"` -// WebhookEventResponseDetail Details of the HTTP response received from the webhook target. -type WebhookEventResponseDetail struct { - // Body Response body returned by the webhook target. - Body *string `json:"body,omitempty"` + // OnchainTransactions The onchain transactions associated with the transfer. + OnchainTransactions *[]struct { + // Network The blockchain network for the payment. Supported networks depend on the account type. See [API and Network Support](https://docs.cdp.coinbase.com/api-reference/payment-apis/supported-networks-assets#by-asset-and-network) for more details. + Network Network `json:"network"` - // ElapsedTimeMs Round-trip time of the webhook delivery in milliseconds. - ElapsedTimeMs *int `json:"elapsedTimeMs,omitempty"` + // TransactionHash The transaction hash. + TransactionHash string `json:"transactionHash"` + } `json:"onchainTransactions,omitempty"` - // ErrorName Error name if the delivery failed (e.g., timeout, connection_refused). - ErrorName *string `json:"errorName,omitempty"` + // TravelRule Travel rule compliance status for deposit transfers. Present when the transfer requires travel rule information. + TravelRule *struct { + // Status The status of a travel rule submission. + Status *TravelRuleStatus `json:"status,omitempty"` - // HttpCode HTTP status code returned by the webhook target. + // StatusMessage Additional details about the current travel rule status. For example, when status is `incomplete`, this may indicate the specific missing information required to proceed. + StatusMessage *string `json:"statusMessage,omitempty"` + } `json:"travelRule,omitempty"` +} + +// TransferEstimate A point-in-time snapshot of estimated values for a transfer where exact amounts cannot be locked in at quote time (e.g., when the executed rate is determined at execution time and moves with the market). +// +// Present in both pre-execution and post-execution states: +// +// - **Quoted state:** top-level fields whose values cannot be guaranteed are absent; +// `estimate` holds their estimated values. +// +// - **Completed state:** top-level fields contain the actual executed values; +// `estimate` is retained as an immutable audit snapshot of the pre-execution estimate. +type TransferEstimate struct { + // EstimatedAt The date and time when this estimate was captured. + EstimatedAt time.Time `json:"estimatedAt"` + + // ExchangeRate Exchange rate information for currency conversion. The rate indicates how much of the target asset is equivalent to one unit of the source asset. + ExchangeRate *TransferExchangeRate `json:"exchangeRate,omitempty"` + + // Fees The fees associated with this transfer. Different transfer types have different fee structures. + // + // **NOTE:** These examples are not exhaustive. + // + // Common examples: + // * **Crypto transfers**: Network fees (gas) paid in the native token + // * **Fiat conversions**: Processing fees + exchange fees in USD + // * **Wire transfers**: Wire fees ($15) + processing fees ($5) in USD + // * **Crypto conversions**: Spread fees paid in the source asset. + Fees *TransferFees `json:"fees,omitempty"` + + // TargetAmount Estimated amount of the target asset that will be received, as a decimal string in standard unit denomination. + TargetAmount *string `json:"targetAmount,omitempty"` + + // TargetAsset The asset symbol of the estimated target amount. + TargetAsset *Asset `json:"targetAsset,omitempty"` +} + +// TransferExchangeRate Exchange rate information for currency conversion. The rate indicates how much of the target asset is equivalent to one unit of the source asset. +type TransferExchangeRate struct { + // Rate The exchange rate value as a decimal string. Indicates how many units of the target asset equal one unit of the source asset. + Rate string `json:"rate"` + + // SourceAsset The asset being converted from. + SourceAsset Asset `json:"sourceAsset"` + + // TargetAsset The asset being converted to. + TargetAsset Asset `json:"targetAsset"` +} + +// TransferFee A single fee for a transfer. +type TransferFee struct { + // Amount The amount of the fee in units of the asset specified by `asset`. + Amount string `json:"amount"` + + // Asset The asset symbol. + Asset Asset `json:"asset"` + + // Type The type of the fee, indicating its purpose. + Type TransferFeeType `json:"type"` +} + +// TransferFeeType The type of the fee, indicating its purpose. +type TransferFeeType string + +// TransferFees The fees associated with this transfer. Different transfer types have different fee structures. +// +// **NOTE:** These examples are not exhaustive. +// +// Common examples: +// * **Crypto transfers**: Network fees (gas) paid in the native token +// * **Fiat conversions**: Processing fees + exchange fees in USD +// * **Wire transfers**: Wire fees ($15) + processing fees ($5) in USD +// * **Crypto conversions**: Spread fees paid in the source asset. +type TransferFees = []TransferFee + +// TransferRequest A request to create a transfer. +type TransferRequest struct { + // Amount The amount of the transfer, as a decimal string in standard unit denomination of the asset specified by `asset` (e.g., "100.00" for 100 USD, "0.05" for 0.05 ETH). + Amount string `json:"amount"` + + // AmountType Specifies whether the given amount is to be received by the target or taken from the source. + // + // - `target`: The transfer `target` receives the exact value specified in `amount`. Fees are added to the amount taken from the transfer `source`. + // - `source`: The transfer `target` receives the value specified in `amount`, minus any fees. + AmountType *TransferRequestAmountType `json:"amountType,omitempty"` + + // Asset The symbol of the asset for the amount. This must be one of the assets of the source or target. + Asset Asset `json:"asset"` + + // Execute Whether to immediately execute the transfer. If false, the transfer will be created in quoted status and must be executed manually via the /execute endpoint. + Execute bool `json:"execute"` + + // Metadata Optional metadata as key-value pairs. Use this to store additional structured information on a resource, such as customer IDs, order references, or any application-specific data. Up to 10 key/value pairs may be provided. Keys and values are both strings. Keys must be ≤ 40 characters; values must be ≤ 500 characters. + Metadata *Metadata `json:"metadata,omitempty"` + + // Source The source of the transfer. + Source CreateTransferSource `json:"source"` + + // Target The target of the transfer. + Target TransferTarget `json:"target"` + + // TravelRule Required Travel Rule fields differ by region. These requirements are determined based on which Coinbase entity the customer has signed the service agreement for. + TravelRule *TravelRule `json:"travelRule,omitempty"` + + // ValidateOnly If true, validates the transfer without initiating it. If the request is valid, a 2xx will be returned. If the request is invalid, a 4xx error will be returned. The response will include an errorType, for e.g. invalid_target if the specified target cannot receive funds. + ValidateOnly *bool `json:"validateOnly,omitempty"` +} + +// TransferRequestAmountType Specifies whether the given amount is to be received by the target or taken from the source. +// +// - `target`: The transfer `target` receives the exact value specified in `amount`. Fees are added to the amount taken from the transfer `source`. +// - `source`: The transfer `target` receives the value specified in `amount`, minus any fees. +type TransferRequestAmountType string + +// TransferSource The source of the transfer. +type TransferSource struct { + union json.RawMessage +} + +// TransferStatus The current status of the transfer, indicating what action you need to take next. Required when validateOnly is false. +type TransferStatus string + +// TransferTarget The target of the transfer. +type TransferTarget struct { + union json.RawMessage +} + +// TravelRule Required Travel Rule fields differ by region. These requirements are determined based on which Coinbase entity the customer has signed the service agreement for. +type TravelRule struct { + // Beneficiary Beneficiary (receiver) party. + Beneficiary *TravelRuleBeneficiary `json:"beneficiary,omitempty"` + + // IsIntermediary Indicates whether Coinbase is being used as an intermediary Virtual Asset Service Provider (VASP) to send crypto on behalf of your customer. + // + // **Background:** + // + // The Travel Rule (FATF Recommendation 16) requires VASPs to share originator and beneficiary information for virtual asset transfers. When Coinbase acts as an intermediary, additional Travel Rule data must be provided to satisfy compliance requirements. + // + // **Set to `true` when:** + // + // - Your organization is a VASP using Coinbase to send crypto **on behalf of your end customer** + // - In this scenario, Coinbase acts as an intermediary in the transfer chain and handles Travel Rule data exchange with the beneficiary VASP + // + // **Set to `false` (or omit) when:** + // + // - You are transferring funds directly from your own Coinbase account, where **Coinbase is your primary VASP** rather than an intermediary for another institution + // + // **Impact on required fields:** + // + // When `isIntermediary` is `true`, you must provide the `originator` object with details about the original sender, including: + // - Originator name + // - Originator address + // - Your VASP information (`virtualAssetServiceProvider` object with `name`, `address`, and `identifier`) + IsIntermediary *bool `json:"isIntermediary,omitempty"` + + // IsSelf Indicates whether the user attests that the receiving wallet belongs to them. + IsSelf *bool `json:"isSelf,omitempty"` + + // Originator Originator (sender) party. + Originator *TravelRuleOriginator `json:"originator,omitempty"` +} + +// TravelRuleBeneficiary defines model for TravelRuleBeneficiary. +type TravelRuleBeneficiary struct { + // Address A physical address with standard address components including street, city, state/province, postal code, and country. + Address *PhysicalAddress `json:"address,omitempty"` + + // FinancialInstitution Name of the financial institution. + FinancialInstitution *string `json:"financialInstitution,omitempty"` + + // Name Full name of the party. + Name *string `json:"name,omitempty"` + + // WalletType The type of the beneficiary's wallet. + WalletType *TravelRuleBeneficiaryWalletType `json:"walletType,omitempty"` +} + +// TravelRuleBeneficiaryWalletType The type of the beneficiary's wallet. +type TravelRuleBeneficiaryWalletType string + +// TravelRuleOriginator defines model for TravelRuleOriginator. +type TravelRuleOriginator struct { + // Address A physical address with standard address components including street, city, state/province, postal code, and country. + Address *PhysicalAddress `json:"address,omitempty"` + + // FinancialInstitution Name of the financial institution. + FinancialInstitution *string `json:"financialInstitution,omitempty"` + + // Name Full name of the party. + Name *string `json:"name,omitempty"` + + // VirtualAssetServiceProvider Information about the originating Virtual Asset Service Provider (VASP) that handles cryptocurrency or other virtual assets on behalf of customers. + VirtualAssetServiceProvider *struct { + // Address A physical address with standard address components including street, city, state/province, postal code, and country. + Address *PhysicalAddress `json:"address,omitempty"` + + // Identifier The Legal Entity Identifier of the originating Virtual Asset Service Provider (VASP). + Identifier *string `json:"identifier,omitempty"` + + // Name The name of the originating Virtual Asset Service Provider (VASP). + Name *string `json:"name,omitempty"` + } `json:"virtualAssetServiceProvider,omitempty"` +} + +// TravelRuleParty Information about a party (originator or beneficiary) for travel rule compliance. +type TravelRuleParty struct { + // Address A physical address with standard address components including street, city, state/province, postal code, and country. + Address *PhysicalAddress `json:"address,omitempty"` + + // FinancialInstitution Name of the financial institution. + FinancialInstitution *string `json:"financialInstitution,omitempty"` + + // Name Full name of the party. + Name *string `json:"name,omitempty"` +} + +// TravelRuleStatus The status of a travel rule submission. +type TravelRuleStatus string + +// Uri A valid URI. +type Uri = string + +// Url A valid HTTP or HTTPS URL. +type Url = string + +// UserOperationReceipt The receipt that contains information about the execution of user operation. +type UserOperationReceipt struct { + // BlockHash The block hash of the block including the transaction as 0x-prefixed string. + BlockHash *string `json:"blockHash,omitempty"` + + // BlockNumber The block height (number) of the block including the transaction. + BlockNumber *int `json:"blockNumber,omitempty"` + + // GasUsed The gas used for landing this user operation. + GasUsed *string `json:"gasUsed,omitempty"` + + // Revert The revert data if the user operation has reverted. + Revert *UserOperationReceiptRevert `json:"revert,omitempty"` + + // TransactionHash The hash of this transaction as 0x-prefixed string. + TransactionHash *string `json:"transactionHash,omitempty"` +} + +// UserOperationReceiptRevert The revert data if the user operation has reverted. +type UserOperationReceiptRevert struct { + // Data The 0x-prefixed raw hex string. + Data string `json:"data"` + + // Message Human-readable revert reason if able to decode. + Message string `json:"message"` +} + +// WebhookEventListResponse Response containing a list of webhook event delivery attempts. +type WebhookEventListResponse struct { + // Events The list of webhook event delivery attempts. + Events []WebhookEventResponse `json:"events"` +} + +// WebhookEventResponse Details of a webhook event delivery attempt for a subscription. +type WebhookEventResponse struct { + // CreatedAt Timestamp when the event delivery attempt was created. + CreatedAt time.Time `json:"createdAt"` + + // EventId Unique identifier for the webhook event. + EventId string `json:"eventId"` + + // EventTypeName The type of event that was delivered (e.g., "onchain.activity.detected"). + EventTypeName string `json:"eventTypeName"` + + // Response Details of the HTTP response received from the webhook target. + Response *WebhookEventResponseDetail `json:"response,omitempty"` + + // RetryCount Number of delivery retry attempts so far. + RetryCount int `json:"retryCount"` + + // Status Current delivery status of the event. + Status WebhookEventResponseStatus `json:"status"` + + // SucceededAt Timestamp when the event was successfully delivered. Only present if status is "succeeded". + SucceededAt *time.Time `json:"succeededAt,omitempty"` +} + +// WebhookEventResponseStatus Current delivery status of the event. +type WebhookEventResponseStatus string + +// WebhookEventResponseDetail Details of the HTTP response received from the webhook target. +type WebhookEventResponseDetail struct { + // Body Response body returned by the webhook target. + Body *string `json:"body,omitempty"` + + // ElapsedTimeMs Round-trip time of the webhook delivery in milliseconds. + ElapsedTimeMs *int `json:"elapsedTimeMs,omitempty"` + + // ErrorName Error name if the delivery failed (e.g., timeout, connection_refused). + ErrorName *string `json:"errorName,omitempty"` + + // HttpCode HTTP status code returned by the webhook target. HttpCode *int `json:"httpCode,omitempty"` } @@ -3529,7 +6839,7 @@ type WebhookSubscriptionResponse struct { // WebhookSubscriptionResponse_Metadata defines model for WebhookSubscriptionResponse.Metadata. type WebhookSubscriptionResponse_Metadata struct { // Secret Use the root-level `secret` field instead. Maintained for backward compatibility only. - // Deprecated: + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set Secret *openapi_types.UUID `json:"secret,omitempty"` AdditionalProperties map[string]string `json:"-"` } @@ -3575,6 +6885,21 @@ type WebhookTarget struct { // X402Version The version of the x402 protocol. type X402Version int +// BalancesAsset An asset, e.g. fiat or crypto. +type BalancesAsset struct { + // Decimals The number of decimals (i.e. significant digits to the right of the decimal point) supported for the asset. + Decimals int `json:"decimals"` + + // Name The name of the asset. + Name string `json:"name"` + + // Symbol The symbol of the asset (e.g., eth, usd, usdc, usdt). + Symbol Asset `json:"symbol"` + + // Type The type of the asset. + Type AssetType `json:"type"` +} + // FromAmount The amount of the `fromToken` to send in atomic units of the token. For example, `1000000000000000000` when sending ETH equates to 1 ETH, `1000000` when sending USDC equates to 1 USDC, etc. type FromAmount = string @@ -3584,6 +6909,13 @@ type FromToken = string // GasPrice The target gas price for the swap transaction, in Wei. For EIP-1559 transactions, this value should be seen as the `maxFeePerGas` value. If not provided, the API will use an estimate based on the current network conditions. type GasPrice = string +// PaymentMethodsPaymentMethod A payment method linked to your entity. Payment methods represent external financial instruments that can be used as a target for transfers. +// +// The `paymentRail` field indicates which type-specific details object is present. Type-specific fields are nested under a key matching the rail name (e.g., `fedwire`, `swift`). +type PaymentMethodsPaymentMethod struct { + union json.RawMessage +} + // SignerAddress The 0x-prefixed Externally Owned Account (EOA) address that will sign the `Permit2` EIP-712 permit message. This is only needed if `taker` is a smart contract. type SignerAddress = string @@ -3596,6 +6928,15 @@ type Taker = string // ToToken The 0x-prefixed contract address of the token to receive. type ToToken = string +// TransfersAccount The Account specific details for the transfer. +type TransfersAccount struct { + // AccountId The ID of the Account. + AccountId string `json:"accountId"` + + // Asset The symbol of the asset (e.g., eth, usd, usdc, usdt). + Asset Asset `json:"asset"` +} + // X402DiscoveryMerchantResponse Response containing x402 resources associated with a merchant payment address. type X402DiscoveryMerchantResponse struct { // Pagination Pagination information for the response. @@ -3631,6 +6972,14 @@ type X402DiscoveryResource struct { // Extensions Map of x402 protocol extensions supported by the resource, keyed by extension name. Extensions *map[string]interface{} `json:"extensions,omitempty"` + // IconUrl URL of a square icon representing the service this resource belongs to. Distinct from a + // brand logo: this is intended for compact, list-view rendering (favicon-style) and is + // normalized to a square aspect ratio at ingestion. The image is moderated and re-hosted by + // Coinbase, so the URL is stable and safe to render directly in clients. Omitted when the + // provider did not supply an icon, when the supplied icon failed moderation, or when image + // processing was unavailable at ingestion time. + IconUrl *Url `json:"iconUrl,omitempty"` + // LastUpdated Timestamp of the last update. LastUpdated *time.Time `json:"lastUpdated,omitempty"` @@ -3640,6 +6989,16 @@ type X402DiscoveryResource struct { // Resource The URL of the resource. Resource string `json:"resource"` + // ServiceName Provider-supplied display name of the service this resource belongs to. This is a free-form + // label for grouping and presentation only — it is not a stable identifier, and two resources + // sharing the same `serviceName` are not guaranteed to belong to the same logical service. + ServiceName *string `json:"serviceName,omitempty"` + + // Tags Provider-supplied, low-cardinality string labels associated with the resource for client-side + // filtering and display. Values are free-form (no controlled vocabulary) and case-sensitive. + // Order is not significant and duplicates are not expected. + Tags *[]string `json:"tags,omitempty"` + // Type Communication protocol (e.g., "http", "mcp"). Type X402DiscoveryResourceType `json:"type"` @@ -3793,7 +7152,7 @@ type X402McpResponse struct { Error *X402McpError `json:"error,omitempty"` // Id Request identifier (matches the request ID, null for notifications). - Id *X402McpResponse_Id `json:"id"` + Id *X402McpResponse_Id `json:"id,omitempty"` // Jsonrpc JSON-RPC version. Jsonrpc X402McpResponseJsonrpc `json:"jsonrpc"` @@ -4106,6 +7465,12 @@ type BadGatewayError = Error // ClientClosedRequestError An error response including the code for the type of error and a human-readable message describing the error. type ClientClosedRequestError = Error +// DelegationForbiddenError An error response including the code for the type of error and a human-readable message describing the error. +type DelegationForbiddenError = Error + +// EndpointUnavailableError An error response including the code for the type of error and a human-readable message describing the error. +type EndpointUnavailableError = Error + // IdempotencyError An error response including the code for the type of error and a human-readable message describing the error. type IdempotencyError = Error @@ -4197,6 +7562,44 @@ type X402VerifyResponse struct { Payer string `json:"payer"` } +// apiKeyAuthContextKey is the context key for apiKeyAuth security scheme +type apiKeyAuthContextKey string + +// endUserAuthContextKey is the context key for endUserAuth security scheme +type endUserAuthContextKey string + +// unauthenticatedContextKey is the context key for unauthenticated security scheme +type unauthenticatedContextKey string + +// ListFoundationAccountsParams defines parameters for ListFoundationAccounts. +type ListFoundationAccountsParams struct { + // PageSize The number of resources to return per page. + PageSize *PageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // PageToken The token for the next page of resources, if any. + PageToken *PageToken `form:"pageToken,omitempty" json:"pageToken,omitempty"` + + // Type Filter accounts by account type. When omitted, accounts of any type are returned. Combined with `owner` using AND. + Type *AccountType `form:"type,omitempty" json:"type,omitempty"` +} + +// CreateFoundationAccountParams defines parameters for CreateFoundationAccount. +type CreateFoundationAccountParams struct { + // XIdempotencyKey An optional string request header for making requests safely retryable. + // When included, duplicate requests with the same key will return identical responses. + // Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + XIdempotencyKey *IdempotencyKey `json:"X-Idempotency-Key,omitempty"` +} + +// ListBalancesParams defines parameters for ListBalances. +type ListBalancesParams struct { + // PageSize The number of resources to return per page. + PageSize *PageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // PageToken The token for the next page of resources, if any. + PageToken *PageToken `form:"pageToken,omitempty" json:"pageToken,omitempty"` +} + // ListDataTokenBalancesParams defines parameters for ListDataTokenBalances. type ListDataTokenBalancesParams struct { // PageSize The number of resources to return per page. @@ -4245,6 +7648,35 @@ type ListWebhookSubscriptionEventsParams struct { EventTypeNames *string `form:"eventTypeNames,omitempty" json:"eventTypeNames,omitempty"` } +// ListDepositDestinationsParams defines parameters for ListDepositDestinations. +type ListDepositDestinationsParams struct { + // AccountId Filter deposit destinations by account ID. + AccountId *AccountId `form:"accountId,omitempty" json:"accountId,omitempty"` + + // Address Filter deposit destinations by the cryptocurrency address. + Address *string `form:"address,omitempty" json:"address,omitempty"` + + // Type Filter deposit destinations by type. + Type *DepositDestinationType `form:"type,omitempty" json:"type,omitempty"` + + // Network Filter deposit destinations by network. + Network *string `form:"network,omitempty" json:"network,omitempty"` + + // PageSize The number of resources to return per page. + PageSize *PageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // PageToken The token for the next page of resources, if any. + PageToken *PageToken `form:"pageToken,omitempty" json:"pageToken,omitempty"` +} + +// CreateDepositDestinationParams defines parameters for CreateDepositDestination. +type CreateDepositDestinationParams struct { + // XIdempotencyKey An optional string request header for making requests safely retryable. + // When included, duplicate requests with the same key will return identical responses. + // Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + XIdempotencyKey *IdempotencyKey `json:"X-Idempotency-Key,omitempty"` +} + // RevokeDelegationForEndUserAccountJSONBody defines parameters for RevokeDelegationForEndUserAccount. type RevokeDelegationForEndUserAccountJSONBody struct { // WalletSecretId When revoking with a wallet authentication scheme, the ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. @@ -5449,6 +8881,15 @@ type CreateOnrampSessionJSONBody struct { Subdivision *string `json:"subdivision,omitempty"` } +// ListPaymentMethodsParams defines parameters for ListPaymentMethods. +type ListPaymentMethodsParams struct { + // PageSize The number of resources to return per page. + PageSize *PageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // PageToken The token for the next page of resources, if any. + PageToken *PageToken `form:"pageToken,omitempty" json:"pageToken,omitempty"` +} + // ListPoliciesParams defines parameters for ListPolicies. type ListPoliciesParams struct { // PageSize The number of resources to return per page. @@ -5714,42 +9155,117 @@ type ListSolanaTokenBalancesParams struct { PageToken *string `form:"pageToken,omitempty" json:"pageToken,omitempty"` } -// ListX402DiscoveryMerchantParams defines parameters for ListX402DiscoveryMerchant. -type ListX402DiscoveryMerchantParams struct { - // PayTo The merchant's payment address to look up. - // This is the onchain address that payment requirements route funds to. - PayTo BlockchainAddress `form:"payTo" json:"payTo"` +// ListTransfersParams defines parameters for ListTransfers. +type ListTransfersParams struct { + // Status Filter transfers by status. Useful for building dashboards, monitoring active transfers, or finding transfers needing action. + Status *TransferStatus `form:"status,omitempty" json:"status,omitempty"` - // Limit The number of resources to return per page. - Limit *int `form:"limit,omitempty" json:"limit,omitempty"` + // AccountId Filter transfers by account ID. Returns transfers where the specified account is either the source or target (OR semantics). Cannot be combined with `sourceAccountId` or `targetAccountId`. + AccountId *AccountId `form:"accountId,omitempty" json:"accountId,omitempty"` - // Offset The offset of the first resource to return. - Offset *int `form:"offset,omitempty" json:"offset,omitempty"` -} + // SourceAccountId Filter transfers by source account ID. Returns only transfers where the specified account is the source. Cannot be combined with `accountId`. + SourceAccountId *AccountId `form:"sourceAccountId,omitempty" json:"sourceAccountId,omitempty"` -// ListX402DiscoveryResourcesParams defines parameters for ListX402DiscoveryResources. -type ListX402DiscoveryResourcesParams struct { - // Type Filter by protocol type (e.g., "http", "mcp"). - // Currently, the only supported protocol type is "http". - Type *string `form:"type,omitempty" json:"type,omitempty"` + // TargetAccountId Filter transfers by target account ID. Returns only transfers where the specified account is the target. Cannot be combined with `accountId`. + TargetAccountId *AccountId `form:"targetAccountId,omitempty" json:"targetAccountId,omitempty"` - // Limit The number of discovered x402 resources to return per page. - Limit *int `form:"limit,omitempty" json:"limit,omitempty"` + // CreatedAfter Filter transfers to those created at or after this datetime (inclusive). ISO 8601 format. + CreatedAfter *time.Time `form:"createdAfter,omitempty" json:"createdAfter,omitempty"` - // Offset The offset of the first discovered x402 resource to return. - Offset *int `form:"offset,omitempty" json:"offset,omitempty"` -} + // CreatedBefore Filter transfers to those created at or before this datetime (inclusive). ISO 8601 format. + CreatedBefore *time.Time `form:"createdBefore,omitempty" json:"createdBefore,omitempty"` -// SearchX402ResourcesParams defines parameters for SearchX402Resources. -type SearchX402ResourcesParams struct { - // Query Full-text or semantic search query to find matching resources. - Query *string `form:"query,omitempty" json:"query,omitempty"` + // UpdatedAfter Filter transfers to those updated at or after this datetime (inclusive). ISO 8601 format. Useful for incremental sync — poll for transfers that changed state since your last check. + UpdatedAfter *time.Time `form:"updatedAfter,omitempty" json:"updatedAfter,omitempty"` - // Network Filter results by network in CAIP-2 format (e.g., `eip155:8453`) or legacy name (e.g., `base`, `base-sepolia`, `solana`). - // Legacy names are normalized to their CAIP-2 equivalents before filtering. - Network *string `form:"network,omitempty" json:"network,omitempty"` + // UpdatedBefore Filter transfers to those updated at or before this datetime (inclusive). ISO 8601 format. + UpdatedBefore *time.Time `form:"updatedBefore,omitempty" json:"updatedBefore,omitempty"` - // Asset Filter results by asset address. + // SourceAsset Filter transfers by source asset symbol (e.g., `usd`, `usdc`). + SourceAsset *string `form:"sourceAsset,omitempty" json:"sourceAsset,omitempty"` + + // TargetAsset Filter transfers by target asset symbol (e.g., `usdc`, `eth`). + TargetAsset *string `form:"targetAsset,omitempty" json:"targetAsset,omitempty"` + + // SourceAddress Filter transfers by the on-chain address of the source. + SourceAddress *BlockchainAddress `form:"sourceAddress,omitempty" json:"sourceAddress,omitempty"` + + // TargetAddress Filter transfers by the on-chain destination address of the target. + TargetAddress *BlockchainAddress `form:"targetAddress,omitempty" json:"targetAddress,omitempty"` + + // TargetEmail Filter transfers by the email address of the target recipient. + TargetEmail *openapi_types.Email `form:"targetEmail,omitempty" json:"targetEmail,omitempty"` + + // TransferId Filter to a specific transfer by ID. When provided, returns only the matching transfer and bypasses pagination. + TransferId *string `form:"transferId,omitempty" json:"transferId,omitempty"` + + // PageSize The number of resources to return per page. + PageSize *PageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // PageToken The token for the next page of resources, if any. + PageToken *PageToken `form:"pageToken,omitempty" json:"pageToken,omitempty"` +} + +// CreateTransferParams defines parameters for CreateTransfer. +type CreateTransferParams struct { + // XIdempotencyKey An optional string request header for making requests safely retryable. + // When included, duplicate requests with the same key will return identical responses. + // Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + XIdempotencyKey *IdempotencyKey `json:"X-Idempotency-Key,omitempty"` +} + +// ExecuteFundTransferParams defines parameters for ExecuteFundTransfer. +type ExecuteFundTransferParams struct { + // XIdempotencyKey An optional string request header for making requests safely retryable. + // When included, duplicate requests with the same key will return identical responses. + // Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + XIdempotencyKey *IdempotencyKey `json:"X-Idempotency-Key,omitempty"` +} + +// SubmitDepositTravelRuleParams defines parameters for SubmitDepositTravelRule. +type SubmitDepositTravelRuleParams struct { + // XIdempotencyKey An optional string request header for making requests safely retryable. + // When included, duplicate requests with the same key will return identical responses. + // Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + XIdempotencyKey *IdempotencyKey `json:"X-Idempotency-Key,omitempty"` +} + +// ListX402DiscoveryMerchantParams defines parameters for ListX402DiscoveryMerchant. +type ListX402DiscoveryMerchantParams struct { + // PayTo The merchant's payment address to look up. + // This is the onchain address that payment requirements route funds to. + PayTo BlockchainAddress `form:"payTo" json:"payTo"` + + // Limit The number of resources to return per page. + Limit *int `form:"limit,omitempty" json:"limit,omitempty"` + + // Offset The offset of the first resource to return. + Offset *int `form:"offset,omitempty" json:"offset,omitempty"` +} + +// ListX402DiscoveryResourcesParams defines parameters for ListX402DiscoveryResources. +type ListX402DiscoveryResourcesParams struct { + // Type Filter by protocol type (e.g., "http", "mcp"). + // Currently, the only supported protocol type is "http". + Type *string `form:"type,omitempty" json:"type,omitempty"` + + // Limit The number of discovered x402 resources to return per page. + Limit *int `form:"limit,omitempty" json:"limit,omitempty"` + + // Offset The offset of the first discovered x402 resource to return. + Offset *int `form:"offset,omitempty" json:"offset,omitempty"` +} + +// SearchX402ResourcesParams defines parameters for SearchX402Resources. +type SearchX402ResourcesParams struct { + // Query Full-text or semantic search query to find matching resources. + Query *string `form:"query,omitempty" json:"query,omitempty"` + + // Network Filter results by network in CAIP-2 format (e.g., `eip155:8453`) or legacy name (e.g., `base`, `base-sepolia`, `solana`). + // Legacy names are normalized to their CAIP-2 equivalents before filtering. + Network *string `form:"network,omitempty" json:"network,omitempty"` + + // Asset Filter results by asset address. // For EVM networks, provide a 0x-prefixed EVM address. For Solana networks, provide a base58-encoded address. // Matching is case-insensitive. Asset *string `form:"asset,omitempty" json:"asset,omitempty"` @@ -5803,6 +9319,9 @@ type VerifyX402PaymentJSONBody struct { X402Version X402Version `json:"x402Version"` } +// CreateFoundationAccountJSONRequestBody defines body for CreateFoundationAccount for application/json ContentType. +type CreateFoundationAccountJSONRequestBody = CreateAccountRequest + // RunSQLQueryJSONRequestBody defines body for RunSQLQuery for application/json ContentType. type RunSQLQueryJSONRequestBody = OnchainDataQuery @@ -5812,6 +9331,9 @@ type CreateWebhookSubscriptionJSONRequestBody = WebhookSubscriptionRequest // UpdateWebhookSubscriptionJSONRequestBody defines body for UpdateWebhookSubscription for application/json ContentType. type UpdateWebhookSubscriptionJSONRequestBody = WebhookSubscriptionUpdateRequest +// CreateDepositDestinationJSONRequestBody defines body for CreateDepositDestination for application/json ContentType. +type CreateDepositDestinationJSONRequestBody = CreateDepositDestinationRequest + // RevokeDelegationForEndUserAccountJSONRequestBody defines body for RevokeDelegationForEndUserAccount for application/json ContentType. type RevokeDelegationForEndUserAccountJSONRequestBody RevokeDelegationForEndUserAccountJSONBody @@ -5977,6 +9499,12 @@ type SignSolanaTransactionJSONRequestBody SignSolanaTransactionJSONBody // RequestSolanaFaucetJSONRequestBody defines body for RequestSolanaFaucet for application/json ContentType. type RequestSolanaFaucetJSONRequestBody RequestSolanaFaucetJSONBody +// CreateTransferJSONRequestBody defines body for CreateTransfer for application/json ContentType. +type CreateTransferJSONRequestBody = TransferRequest + +// SubmitDepositTravelRuleJSONRequestBody defines body for SubmitDepositTravelRule for application/json ContentType. +type SubmitDepositTravelRuleJSONRequestBody = DepositTravelRuleRequest + // PostX402DiscoveryMcpJSONRequestBody defines body for PostX402DiscoveryMcp for application/json ContentType. type PostX402DiscoveryMcpJSONRequestBody = X402McpRequest @@ -6075,7 +9603,7 @@ func (t *Abi_Item) MergeAbiFunction(v AbiFunction) error { return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6101,7 +9629,7 @@ func (t *Abi_Item) MergeAbiInput(v AbiInput) error { return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6137,7 +9665,7 @@ func (t *AuthenticationMethod) MergeEmailAuthentication(v EmailAuthentication) e return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6163,7 +9691,7 @@ func (t *AuthenticationMethod) MergeSmsAuthentication(v SmsAuthentication) error return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6189,7 +9717,7 @@ func (t *AuthenticationMethod) MergeDeveloperJWTAuthentication(v DeveloperJWTAut return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6215,7 +9743,7 @@ func (t *AuthenticationMethod) MergeOAuth2Authentication(v OAuth2Authentication) return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6241,7 +9769,7 @@ func (t *AuthenticationMethod) MergeTelegramAuthentication(v TelegramAuthenticat return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6267,7 +9795,7 @@ func (t *AuthenticationMethod) MergeSiweAuthentication(v SiweAuthentication) err return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6282,6 +9810,65 @@ func (t *AuthenticationMethod) UnmarshalJSON(b []byte) error { return err } +// AsCreateCryptoDepositDestinationRequest returns the union data inside the CreateDepositDestinationRequest as a CreateCryptoDepositDestinationRequest +func (t CreateDepositDestinationRequest) AsCreateCryptoDepositDestinationRequest() (CreateCryptoDepositDestinationRequest, error) { + var body CreateCryptoDepositDestinationRequest + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCreateCryptoDepositDestinationRequest overwrites any union data inside the CreateDepositDestinationRequest as the provided CreateCryptoDepositDestinationRequest +func (t *CreateDepositDestinationRequest) FromCreateCryptoDepositDestinationRequest(v CreateCryptoDepositDestinationRequest) error { + v.Type = "crypto" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCreateCryptoDepositDestinationRequest performs a merge with any union data inside the CreateDepositDestinationRequest, using the provided CreateCryptoDepositDestinationRequest +func (t *CreateDepositDestinationRequest) MergeCreateCryptoDepositDestinationRequest(v CreateCryptoDepositDestinationRequest) error { + v.Type = "crypto" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t CreateDepositDestinationRequest) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t CreateDepositDestinationRequest) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "crypto": + return t.AsCreateCryptoDepositDestinationRequest() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t CreateDepositDestinationRequest) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *CreateDepositDestinationRequest) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + // AsEvmNetworkCriterion returns the union data inside the CreateEndUserEvmSwapCriteria_Item as a EvmNetworkCriterion func (t CreateEndUserEvmSwapCriteria_Item) AsEvmNetworkCriterion() (EvmNetworkCriterion, error) { var body EvmNetworkCriterion @@ -6303,7 +9890,7 @@ func (t *CreateEndUserEvmSwapCriteria_Item) MergeEvmNetworkCriterion(v EvmNetwor return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6329,7 +9916,7 @@ func (t *CreateEndUserEvmSwapCriteria_Item) MergeEvmDataCriterion(v EvmDataCrite return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6355,7 +9942,7 @@ func (t *CreateEndUserEvmSwapCriteria_Item) MergeNetUSDChangeCriterion(v NetUSDC return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6391,7 +9978,7 @@ func (t *CreateSwapQuoteResponseWrapper) MergeCreateSwapQuoteResponse(v CreateSw return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6417,7 +10004,7 @@ func (t *CreateSwapQuoteResponseWrapper) MergeSwapUnavailableResponse(v SwapUnav return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6432,6 +10019,163 @@ func (t *CreateSwapQuoteResponseWrapper) UnmarshalJSON(b []byte) error { return err } +// AsTransfersAccount returns the union data inside the CreateTransferSource as a TransfersAccount +func (t CreateTransferSource) AsTransfersAccount() (TransfersAccount, error) { + var body TransfersAccount + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromTransfersAccount overwrites any union data inside the CreateTransferSource as the provided TransfersAccount +func (t *CreateTransferSource) FromTransfersAccount(v TransfersAccount) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeTransfersAccount performs a merge with any union data inside the CreateTransferSource, using the provided TransfersAccount +func (t *CreateTransferSource) MergeTransfersAccount(v TransfersAccount) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsPaymentMethod returns the union data inside the CreateTransferSource as a PaymentMethod +func (t CreateTransferSource) AsPaymentMethod() (PaymentMethod, error) { + var body PaymentMethod + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromPaymentMethod overwrites any union data inside the CreateTransferSource as the provided PaymentMethod +func (t *CreateTransferSource) FromPaymentMethod(v PaymentMethod) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergePaymentMethod performs a merge with any union data inside the CreateTransferSource, using the provided PaymentMethod +func (t *CreateTransferSource) MergePaymentMethod(v PaymentMethod) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t CreateTransferSource) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *CreateTransferSource) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsCryptoDepositDestination returns the union data inside the DepositDestination as a CryptoDepositDestination +func (t DepositDestination) AsCryptoDepositDestination() (CryptoDepositDestination, error) { + var body CryptoDepositDestination + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCryptoDepositDestination overwrites any union data inside the DepositDestination as the provided CryptoDepositDestination +func (t *DepositDestination) FromCryptoDepositDestination(v CryptoDepositDestination) error { + v.Type = "crypto" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCryptoDepositDestination performs a merge with any union data inside the DepositDestination, using the provided CryptoDepositDestination +func (t *DepositDestination) MergeCryptoDepositDestination(v CryptoDepositDestination) error { + v.Type = "crypto" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t DepositDestination) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t DepositDestination) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "crypto": + return t.AsCryptoDepositDestination() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t DepositDestination) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *DepositDestination) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsDepositDestinationTargetAccount returns the union data inside the DepositDestinationTarget as a DepositDestinationTargetAccount +func (t DepositDestinationTarget) AsDepositDestinationTargetAccount() (DepositDestinationTargetAccount, error) { + var body DepositDestinationTargetAccount + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromDepositDestinationTargetAccount overwrites any union data inside the DepositDestinationTarget as the provided DepositDestinationTargetAccount +func (t *DepositDestinationTarget) FromDepositDestinationTargetAccount(v DepositDestinationTargetAccount) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeDepositDestinationTargetAccount performs a merge with any union data inside the DepositDestinationTarget, using the provided DepositDestinationTargetAccount +func (t *DepositDestinationTarget) MergeDepositDestinationTargetAccount(v DepositDestinationTargetAccount) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t DepositDestinationTarget) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *DepositDestinationTarget) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + // AsEvmDataParameterCondition returns the union data inside the EvmDataCondition_Params_Item as a EvmDataParameterCondition func (t EvmDataCondition_Params_Item) AsEvmDataParameterCondition() (EvmDataParameterCondition, error) { var body EvmDataParameterCondition @@ -6453,7 +10197,7 @@ func (t *EvmDataCondition_Params_Item) MergeEvmDataParameterCondition(v EvmDataP return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6479,7 +10223,7 @@ func (t *EvmDataCondition_Params_Item) MergeEvmDataParameterConditionList(v EvmD return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6515,7 +10259,7 @@ func (t *EvmDataCriterion_Abi) MergeKnownAbiType(v KnownAbiType) error { return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6541,7 +10285,7 @@ func (t *EvmDataCriterion_Abi) MergeAbi(v Abi) error { return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6577,7 +10321,7 @@ func (t *GetSwapPriceResponseWrapper) MergeGetSwapPriceResponse(v GetSwapPriceRe return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6603,7 +10347,7 @@ func (t *GetSwapPriceResponseWrapper) MergeSwapUnavailableResponse(v SwapUnavail return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6639,7 +10383,7 @@ func (t *PrepareUserOperationCriteria_Item) MergeEthValueCriterion(v EthValueCri return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6665,7 +10409,7 @@ func (t *PrepareUserOperationCriteria_Item) MergeEvmAddressCriterion(v EvmAddres return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6691,7 +10435,7 @@ func (t *PrepareUserOperationCriteria_Item) MergeEvmNetworkCriterion(v EvmNetwor return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6717,7 +10461,7 @@ func (t *PrepareUserOperationCriteria_Item) MergeEvmDataCriterion(v EvmDataCrite return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6743,7 +10487,7 @@ func (t *PrepareUserOperationCriteria_Item) MergeNetUSDChangeCriterion(v NetUSDC return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6779,7 +10523,7 @@ func (t *Rule) MergeSignEvmTransactionRule(v SignEvmTransactionRule) error { return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6805,7 +10549,7 @@ func (t *Rule) MergeSendEvmTransactionRule(v SendEvmTransactionRule) error { return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6831,7 +10575,7 @@ func (t *Rule) MergeSignEvmMessageRule(v SignEvmMessageRule) error { return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6857,7 +10601,7 @@ func (t *Rule) MergeSignEvmTypedDataRule(v SignEvmTypedDataRule) error { return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6883,7 +10627,7 @@ func (t *Rule) MergeSignSolTransactionRule(v SignSolTransactionRule) error { return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6909,7 +10653,7 @@ func (t *Rule) MergeSendSolTransactionRule(v SendSolTransactionRule) error { return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6935,7 +10679,7 @@ func (t *Rule) MergeSignSolMessageRule(v SignSolMessageRule) error { return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6961,7 +10705,7 @@ func (t *Rule) MergeSignEvmHashRule(v SignEvmHashRule) error { return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -6987,7 +10731,7 @@ func (t *Rule) MergePrepareUserOperationRule(v PrepareUserOperationRule) error { return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7013,7 +10757,7 @@ func (t *Rule) MergeSendUserOperationRule(v SendUserOperationRule) error { return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7039,7 +10783,7 @@ func (t *Rule) MergeSignEndUserEvmTransactionRule(v SignEndUserEvmTransactionRul return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7065,7 +10809,7 @@ func (t *Rule) MergeSendEndUserEvmTransactionRule(v SendEndUserEvmTransactionRul return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7091,7 +10835,7 @@ func (t *Rule) MergeSignEndUserEvmMessageRule(v SignEndUserEvmMessageRule) error return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7117,7 +10861,7 @@ func (t *Rule) MergeSignEndUserEvmTypedDataRule(v SignEndUserEvmTypedDataRule) e return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7143,7 +10887,7 @@ func (t *Rule) MergeSignEndUserEvmHashRule(v SignEndUserEvmHashRule) error { return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7169,7 +10913,7 @@ func (t *Rule) MergeSignEndUserSolTransactionRule(v SignEndUserSolTransactionRul return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7195,7 +10939,7 @@ func (t *Rule) MergeSendEndUserSolTransactionRule(v SendEndUserSolTransactionRul return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7221,7 +10965,7 @@ func (t *Rule) MergeSignEndUserSolMessageRule(v SignEndUserSolMessageRule) error return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7247,7 +10991,7 @@ func (t *Rule) MergeSendEndUserEvmAssetRule(v SendEndUserEvmAssetRule) error { return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7273,7 +11017,7 @@ func (t *Rule) MergeSendEndUserSolAssetRule(v SendEndUserSolAssetRule) error { return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7299,7 +11043,7 @@ func (t *Rule) MergeCreateEndUserEvmSwapRule(v CreateEndUserEvmSwapRule) error { return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7335,7 +11079,7 @@ func (t *SendEndUserEvmAssetCriteria_Item) MergeEvmNetworkCriterion(v EvmNetwork return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7361,7 +11105,7 @@ func (t *SendEndUserEvmAssetCriteria_Item) MergeEvmDataCriterion(v EvmDataCriter return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7387,7 +11131,7 @@ func (t *SendEndUserEvmAssetCriteria_Item) MergeNetUSDChangeCriterion(v NetUSDCh return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7423,7 +11167,7 @@ func (t *SendEndUserEvmTransactionCriteria_Item) MergeEthValueCriterion(v EthVal return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7449,7 +11193,7 @@ func (t *SendEndUserEvmTransactionCriteria_Item) MergeEvmAddressCriterion(v EvmA return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7475,7 +11219,7 @@ func (t *SendEndUserEvmTransactionCriteria_Item) MergeEvmNetworkCriterion(v EvmN return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7501,7 +11245,7 @@ func (t *SendEndUserEvmTransactionCriteria_Item) MergeEvmDataCriterion(v EvmData return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7527,7 +11271,7 @@ func (t *SendEndUserEvmTransactionCriteria_Item) MergeNetUSDChangeCriterion(v Ne return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7563,7 +11307,7 @@ func (t *SendEndUserSolAssetCriteria_Item) MergeSplAddressCriterion(v SplAddress return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7589,7 +11333,7 @@ func (t *SendEndUserSolAssetCriteria_Item) MergeSplValueCriterion(v SplValueCrit return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7615,7 +11359,7 @@ func (t *SendEndUserSolAssetCriteria_Item) MergeSolDataCriterion(v SolDataCriter return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7641,7 +11385,7 @@ func (t *SendEndUserSolAssetCriteria_Item) MergeSolNetworkCriterion(v SolNetwork return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7677,7 +11421,7 @@ func (t *SendEndUserSolTransactionCriteria_Item) MergeSolAddressCriterion(v SolA return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7703,7 +11447,7 @@ func (t *SendEndUserSolTransactionCriteria_Item) MergeSolValueCriterion(v SolVal return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7729,7 +11473,7 @@ func (t *SendEndUserSolTransactionCriteria_Item) MergeSplAddressCriterion(v SplA return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7755,7 +11499,7 @@ func (t *SendEndUserSolTransactionCriteria_Item) MergeSplValueCriterion(v SplVal return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7781,7 +11525,7 @@ func (t *SendEndUserSolTransactionCriteria_Item) MergeMintAddressCriterion(v Min return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7807,7 +11551,7 @@ func (t *SendEndUserSolTransactionCriteria_Item) MergeSolDataCriterion(v SolData return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7833,7 +11577,7 @@ func (t *SendEndUserSolTransactionCriteria_Item) MergeProgramIdCriterion(v Progr return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7859,7 +11603,7 @@ func (t *SendEndUserSolTransactionCriteria_Item) MergeSolNetworkCriterion(v SolN return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7895,7 +11639,7 @@ func (t *SendEvmTransactionCriteria_Item) MergeEthValueCriterion(v EthValueCrite return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7921,7 +11665,7 @@ func (t *SendEvmTransactionCriteria_Item) MergeEvmAddressCriterion(v EvmAddressC return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7947,7 +11691,7 @@ func (t *SendEvmTransactionCriteria_Item) MergeEvmNetworkCriterion(v EvmNetworkC return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7973,7 +11717,7 @@ func (t *SendEvmTransactionCriteria_Item) MergeEvmDataCriterion(v EvmDataCriteri return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -7999,7 +11743,7 @@ func (t *SendEvmTransactionCriteria_Item) MergeNetUSDChangeCriterion(v NetUSDCha return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8035,7 +11779,7 @@ func (t *SendSolTransactionCriteria_Item) MergeSolAddressCriterion(v SolAddressC return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8061,7 +11805,7 @@ func (t *SendSolTransactionCriteria_Item) MergeSolValueCriterion(v SolValueCrite return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8087,7 +11831,7 @@ func (t *SendSolTransactionCriteria_Item) MergeSplAddressCriterion(v SplAddressC return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8113,7 +11857,7 @@ func (t *SendSolTransactionCriteria_Item) MergeSplValueCriterion(v SplValueCrite return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8139,7 +11883,7 @@ func (t *SendSolTransactionCriteria_Item) MergeMintAddressCriterion(v MintAddres return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8165,7 +11909,7 @@ func (t *SendSolTransactionCriteria_Item) MergeSolDataCriterion(v SolDataCriteri return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8191,7 +11935,7 @@ func (t *SendSolTransactionCriteria_Item) MergeProgramIdCriterion(v ProgramIdCri return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8217,7 +11961,7 @@ func (t *SendSolTransactionCriteria_Item) MergeSolNetworkCriterion(v SolNetworkC return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8253,7 +11997,7 @@ func (t *SendUserOperationCriteria_Item) MergeEthValueCriterion(v EthValueCriter return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8279,7 +12023,33 @@ func (t *SendUserOperationCriteria_Item) MergeEvmAddressCriterion(v EvmAddressCr return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEvmNetworkCriterion returns the union data inside the SendUserOperationCriteria_Item as a EvmNetworkCriterion +func (t SendUserOperationCriteria_Item) AsEvmNetworkCriterion() (EvmNetworkCriterion, error) { + var body EvmNetworkCriterion + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEvmNetworkCriterion overwrites any union data inside the SendUserOperationCriteria_Item as the provided EvmNetworkCriterion +func (t *SendUserOperationCriteria_Item) FromEvmNetworkCriterion(v EvmNetworkCriterion) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEvmNetworkCriterion performs a merge with any union data inside the SendUserOperationCriteria_Item, using the provided EvmNetworkCriterion +func (t *SendUserOperationCriteria_Item) MergeEvmNetworkCriterion(v EvmNetworkCriterion) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8305,7 +12075,7 @@ func (t *SendUserOperationCriteria_Item) MergeEvmDataCriterion(v EvmDataCriterio return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8331,7 +12101,7 @@ func (t *SendUserOperationCriteria_Item) MergeNetUSDChangeCriterion(v NetUSDChan return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8367,7 +12137,7 @@ func (t *SignEndUserEvmMessageCriteria_Item) MergeEvmMessageCriterion(v EvmMessa return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8403,7 +12173,7 @@ func (t *SignEndUserEvmTransactionCriteria_Item) MergeEthValueCriterion(v EthVal return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8429,7 +12199,7 @@ func (t *SignEndUserEvmTransactionCriteria_Item) MergeEvmAddressCriterion(v EvmA return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8455,7 +12225,7 @@ func (t *SignEndUserEvmTransactionCriteria_Item) MergeEvmDataCriterion(v EvmData return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8481,7 +12251,7 @@ func (t *SignEndUserEvmTransactionCriteria_Item) MergeNetUSDChangeCriterion(v Ne return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8517,7 +12287,7 @@ func (t *SignEndUserEvmTypedDataCriteria_Item) MergeSignEvmTypedDataFieldCriteri return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8543,7 +12313,7 @@ func (t *SignEndUserEvmTypedDataCriteria_Item) MergeSignEvmTypedDataVerifyingCon return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8579,7 +12349,7 @@ func (t *SignEndUserSolMessageCriteria_Item) MergeSolMessageCriterion(v SolMessa return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8615,7 +12385,7 @@ func (t *SignEndUserSolTransactionCriteria_Item) MergeSolAddressCriterion(v SolA return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8641,7 +12411,7 @@ func (t *SignEndUserSolTransactionCriteria_Item) MergeSolValueCriterion(v SolVal return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8667,7 +12437,7 @@ func (t *SignEndUserSolTransactionCriteria_Item) MergeSplAddressCriterion(v SplA return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8693,7 +12463,7 @@ func (t *SignEndUserSolTransactionCriteria_Item) MergeSplValueCriterion(v SplVal return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8719,7 +12489,7 @@ func (t *SignEndUserSolTransactionCriteria_Item) MergeMintAddressCriterion(v Min return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8745,7 +12515,7 @@ func (t *SignEndUserSolTransactionCriteria_Item) MergeSolDataCriterion(v SolData return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8771,7 +12541,7 @@ func (t *SignEndUserSolTransactionCriteria_Item) MergeProgramIdCriterion(v Progr return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8807,7 +12577,7 @@ func (t *SignEvmMessageCriteria_Item) MergeEvmMessageCriterion(v EvmMessageCrite return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8843,7 +12613,7 @@ func (t *SignEvmTransactionCriteria_Item) MergeEthValueCriterion(v EthValueCrite return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8869,7 +12639,7 @@ func (t *SignEvmTransactionCriteria_Item) MergeEvmAddressCriterion(v EvmAddressC return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8895,7 +12665,7 @@ func (t *SignEvmTransactionCriteria_Item) MergeEvmDataCriterion(v EvmDataCriteri return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8921,7 +12691,7 @@ func (t *SignEvmTransactionCriteria_Item) MergeNetUSDChangeCriterion(v NetUSDCha return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8957,7 +12727,7 @@ func (t *SignEvmTypedDataCriteria_Item) MergeSignEvmTypedDataFieldCriterion(v Si return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -8983,7 +12753,7 @@ func (t *SignEvmTypedDataCriteria_Item) MergeSignEvmTypedDataVerifyingContractCr return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9019,7 +12789,7 @@ func (t *SignEvmTypedDataFieldCriterion_Conditions_Item) MergeEvmTypedAddressCon return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9045,7 +12815,7 @@ func (t *SignEvmTypedDataFieldCriterion_Conditions_Item) MergeEvmTypedNumericalC return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9071,7 +12841,7 @@ func (t *SignEvmTypedDataFieldCriterion_Conditions_Item) MergeEvmTypedStringCond return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9107,7 +12877,7 @@ func (t *SignSolMessageCriteria_Item) MergeSolMessageCriterion(v SolMessageCrite return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9143,7 +12913,7 @@ func (t *SignSolTransactionCriteria_Item) MergeSolAddressCriterion(v SolAddressC return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9169,7 +12939,7 @@ func (t *SignSolTransactionCriteria_Item) MergeSolValueCriterion(v SolValueCrite return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9195,7 +12965,7 @@ func (t *SignSolTransactionCriteria_Item) MergeSplAddressCriterion(v SplAddressC return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9221,7 +12991,7 @@ func (t *SignSolTransactionCriteria_Item) MergeSplValueCriterion(v SplValueCrite return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9247,7 +13017,7 @@ func (t *SignSolTransactionCriteria_Item) MergeMintAddressCriterion(v MintAddres return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9273,7 +13043,7 @@ func (t *SignSolTransactionCriteria_Item) MergeSolDataCriterion(v SolDataCriteri return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9299,7 +13069,7 @@ func (t *SignSolTransactionCriteria_Item) MergeProgramIdCriterion(v ProgramIdCri return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9335,7 +13105,7 @@ func (t *SolDataCondition_Params_Item) MergeSolDataParameterCondition(v SolDataP return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9361,7 +13131,7 @@ func (t *SolDataCondition_Params_Item) MergeSolDataParameterConditionList(v SolD return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9397,7 +13167,7 @@ func (t *SolDataCriterion_Idls_Item) MergeKnownIdlType(v KnownIdlType) error { return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9423,7 +13193,7 @@ func (t *SolDataCriterion_Idls_Item) MergeIdl(v Idl) error { return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9438,71 +13208,418 @@ func (t *SolDataCriterion_Idls_Item) UnmarshalJSON(b []byte) error { return err } -// AsX402McpRequestId0 returns the union data inside the X402McpRequest_Id as a X402McpRequestId0 -func (t X402McpRequest_Id) AsX402McpRequestId0() (X402McpRequestId0, error) { - var body X402McpRequestId0 +// AsTransfersAccount returns the union data inside the TransferSource as a TransfersAccount +func (t TransferSource) AsTransfersAccount() (TransfersAccount, error) { + var body TransfersAccount err := json.Unmarshal(t.union, &body) return body, err } -// FromX402McpRequestId0 overwrites any union data inside the X402McpRequest_Id as the provided X402McpRequestId0 -func (t *X402McpRequest_Id) FromX402McpRequestId0(v X402McpRequestId0) error { +// FromTransfersAccount overwrites any union data inside the TransferSource as the provided TransfersAccount +func (t *TransferSource) FromTransfersAccount(v TransfersAccount) error { b, err := json.Marshal(v) t.union = b return err } -// MergeX402McpRequestId0 performs a merge with any union data inside the X402McpRequest_Id, using the provided X402McpRequestId0 -func (t *X402McpRequest_Id) MergeX402McpRequestId0(v X402McpRequestId0) error { +// MergeTransfersAccount performs a merge with any union data inside the TransferSource, using the provided TransfersAccount +func (t *TransferSource) MergeTransfersAccount(v TransfersAccount) error { b, err := json.Marshal(v) if err != nil { return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } -// AsX402McpRequestId1 returns the union data inside the X402McpRequest_Id as a X402McpRequestId1 -func (t X402McpRequest_Id) AsX402McpRequestId1() (X402McpRequestId1, error) { - var body X402McpRequestId1 +// AsPaymentMethod returns the union data inside the TransferSource as a PaymentMethod +func (t TransferSource) AsPaymentMethod() (PaymentMethod, error) { + var body PaymentMethod err := json.Unmarshal(t.union, &body) return body, err } -// FromX402McpRequestId1 overwrites any union data inside the X402McpRequest_Id as the provided X402McpRequestId1 -func (t *X402McpRequest_Id) FromX402McpRequestId1(v X402McpRequestId1) error { +// FromPaymentMethod overwrites any union data inside the TransferSource as the provided PaymentMethod +func (t *TransferSource) FromPaymentMethod(v PaymentMethod) error { b, err := json.Marshal(v) t.union = b return err } -// MergeX402McpRequestId1 performs a merge with any union data inside the X402McpRequest_Id, using the provided X402McpRequestId1 -func (t *X402McpRequest_Id) MergeX402McpRequestId1(v X402McpRequestId1) error { +// MergePaymentMethod performs a merge with any union data inside the TransferSource, using the provided PaymentMethod +func (t *TransferSource) MergePaymentMethod(v PaymentMethod) error { b, err := json.Marshal(v) if err != nil { return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } -func (t X402McpRequest_Id) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err +// AsOnchainAddress returns the union data inside the TransferSource as a OnchainAddress +func (t TransferSource) AsOnchainAddress() (OnchainAddress, error) { + var body OnchainAddress + err := json.Unmarshal(t.union, &body) + return body, err } -func (t *X402McpRequest_Id) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) +// FromOnchainAddress overwrites any union data inside the TransferSource as the provided OnchainAddress +func (t *TransferSource) FromOnchainAddress(v OnchainAddress) error { + b, err := json.Marshal(v) + t.union = b return err } -// AsX402McpResponseId0 returns the union data inside the X402McpResponse_Id as a X402McpResponseId0 -func (t X402McpResponse_Id) AsX402McpResponseId0() (X402McpResponseId0, error) { - var body X402McpResponseId0 +// MergeOnchainAddress performs a merge with any union data inside the TransferSource, using the provided OnchainAddress +func (t *TransferSource) MergeOnchainAddress(v OnchainAddress) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsOriginatingBankAccountUS returns the union data inside the TransferSource as a OriginatingBankAccountUS +func (t TransferSource) AsOriginatingBankAccountUS() (OriginatingBankAccountUS, error) { + var body OriginatingBankAccountUS + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromOriginatingBankAccountUS overwrites any union data inside the TransferSource as the provided OriginatingBankAccountUS +func (t *TransferSource) FromOriginatingBankAccountUS(v OriginatingBankAccountUS) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeOriginatingBankAccountUS performs a merge with any union data inside the TransferSource, using the provided OriginatingBankAccountUS +func (t *TransferSource) MergeOriginatingBankAccountUS(v OriginatingBankAccountUS) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t TransferSource) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *TransferSource) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsTransfersAccount returns the union data inside the TransferTarget as a TransfersAccount +func (t TransferTarget) AsTransfersAccount() (TransfersAccount, error) { + var body TransfersAccount + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromTransfersAccount overwrites any union data inside the TransferTarget as the provided TransfersAccount +func (t *TransferTarget) FromTransfersAccount(v TransfersAccount) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeTransfersAccount performs a merge with any union data inside the TransferTarget, using the provided TransfersAccount +func (t *TransferTarget) MergeTransfersAccount(v TransfersAccount) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsPaymentMethod returns the union data inside the TransferTarget as a PaymentMethod +func (t TransferTarget) AsPaymentMethod() (PaymentMethod, error) { + var body PaymentMethod + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromPaymentMethod overwrites any union data inside the TransferTarget as the provided PaymentMethod +func (t *TransferTarget) FromPaymentMethod(v PaymentMethod) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergePaymentMethod performs a merge with any union data inside the TransferTarget, using the provided PaymentMethod +func (t *TransferTarget) MergePaymentMethod(v PaymentMethod) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsOnchainAddress returns the union data inside the TransferTarget as a OnchainAddress +func (t TransferTarget) AsOnchainAddress() (OnchainAddress, error) { + var body OnchainAddress + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromOnchainAddress overwrites any union data inside the TransferTarget as the provided OnchainAddress +func (t *TransferTarget) FromOnchainAddress(v OnchainAddress) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeOnchainAddress performs a merge with any union data inside the TransferTarget, using the provided OnchainAddress +func (t *TransferTarget) MergeOnchainAddress(v OnchainAddress) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEmailInstrument returns the union data inside the TransferTarget as a EmailInstrument +func (t TransferTarget) AsEmailInstrument() (EmailInstrument, error) { + var body EmailInstrument + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEmailInstrument overwrites any union data inside the TransferTarget as the provided EmailInstrument +func (t *TransferTarget) FromEmailInstrument(v EmailInstrument) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEmailInstrument performs a merge with any union data inside the TransferTarget, using the provided EmailInstrument +func (t *TransferTarget) MergeEmailInstrument(v EmailInstrument) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t TransferTarget) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *TransferTarget) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsFedwirePaymentMethod returns the union data inside the PaymentMethodsPaymentMethod as a FedwirePaymentMethod +func (t PaymentMethodsPaymentMethod) AsFedwirePaymentMethod() (FedwirePaymentMethod, error) { + var body FedwirePaymentMethod + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromFedwirePaymentMethod overwrites any union data inside the PaymentMethodsPaymentMethod as the provided FedwirePaymentMethod +func (t *PaymentMethodsPaymentMethod) FromFedwirePaymentMethod(v FedwirePaymentMethod) error { + v.PaymentRail = "fedwire" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeFedwirePaymentMethod performs a merge with any union data inside the PaymentMethodsPaymentMethod, using the provided FedwirePaymentMethod +func (t *PaymentMethodsPaymentMethod) MergeFedwirePaymentMethod(v FedwirePaymentMethod) error { + v.PaymentRail = "fedwire" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsSwiftPaymentMethod returns the union data inside the PaymentMethodsPaymentMethod as a SwiftPaymentMethod +func (t PaymentMethodsPaymentMethod) AsSwiftPaymentMethod() (SwiftPaymentMethod, error) { + var body SwiftPaymentMethod + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromSwiftPaymentMethod overwrites any union data inside the PaymentMethodsPaymentMethod as the provided SwiftPaymentMethod +func (t *PaymentMethodsPaymentMethod) FromSwiftPaymentMethod(v SwiftPaymentMethod) error { + v.PaymentRail = "swift" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeSwiftPaymentMethod performs a merge with any union data inside the PaymentMethodsPaymentMethod, using the provided SwiftPaymentMethod +func (t *PaymentMethodsPaymentMethod) MergeSwiftPaymentMethod(v SwiftPaymentMethod) error { + v.PaymentRail = "swift" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsSepaPaymentMethod returns the union data inside the PaymentMethodsPaymentMethod as a SepaPaymentMethod +func (t PaymentMethodsPaymentMethod) AsSepaPaymentMethod() (SepaPaymentMethod, error) { + var body SepaPaymentMethod + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromSepaPaymentMethod overwrites any union data inside the PaymentMethodsPaymentMethod as the provided SepaPaymentMethod +func (t *PaymentMethodsPaymentMethod) FromSepaPaymentMethod(v SepaPaymentMethod) error { + v.PaymentRail = "sepa" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeSepaPaymentMethod performs a merge with any union data inside the PaymentMethodsPaymentMethod, using the provided SepaPaymentMethod +func (t *PaymentMethodsPaymentMethod) MergeSepaPaymentMethod(v SepaPaymentMethod) error { + v.PaymentRail = "sepa" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t PaymentMethodsPaymentMethod) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"paymentRail"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t PaymentMethodsPaymentMethod) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "fedwire": + return t.AsFedwirePaymentMethod() + case "sepa": + return t.AsSepaPaymentMethod() + case "swift": + return t.AsSwiftPaymentMethod() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t PaymentMethodsPaymentMethod) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *PaymentMethodsPaymentMethod) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsX402McpRequestId0 returns the union data inside the X402McpRequest_Id as a X402McpRequestId0 +func (t X402McpRequest_Id) AsX402McpRequestId0() (X402McpRequestId0, error) { + var body X402McpRequestId0 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromX402McpRequestId0 overwrites any union data inside the X402McpRequest_Id as the provided X402McpRequestId0 +func (t *X402McpRequest_Id) FromX402McpRequestId0(v X402McpRequestId0) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeX402McpRequestId0 performs a merge with any union data inside the X402McpRequest_Id, using the provided X402McpRequestId0 +func (t *X402McpRequest_Id) MergeX402McpRequestId0(v X402McpRequestId0) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsX402McpRequestId1 returns the union data inside the X402McpRequest_Id as a X402McpRequestId1 +func (t X402McpRequest_Id) AsX402McpRequestId1() (X402McpRequestId1, error) { + var body X402McpRequestId1 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromX402McpRequestId1 overwrites any union data inside the X402McpRequest_Id as the provided X402McpRequestId1 +func (t *X402McpRequest_Id) FromX402McpRequestId1(v X402McpRequestId1) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeX402McpRequestId1 performs a merge with any union data inside the X402McpRequest_Id, using the provided X402McpRequestId1 +func (t *X402McpRequest_Id) MergeX402McpRequestId1(v X402McpRequestId1) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t X402McpRequest_Id) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *X402McpRequest_Id) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsX402McpResponseId0 returns the union data inside the X402McpResponse_Id as a X402McpResponseId0 +func (t X402McpResponse_Id) AsX402McpResponseId0() (X402McpResponseId0, error) { + var body X402McpResponseId0 err := json.Unmarshal(t.union, &body) return body, err } @@ -9521,7 +13638,7 @@ func (t *X402McpResponse_Id) MergeX402McpResponseId0(v X402McpResponseId0) error return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9547,7 +13664,7 @@ func (t *X402McpResponse_Id) MergeX402McpResponseId1(v X402McpResponseId1) error return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9583,7 +13700,7 @@ func (t *X402PaymentPayload) MergeX402V2PaymentPayload(v X402V2PaymentPayload) e return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9609,7 +13726,7 @@ func (t *X402PaymentPayload) MergeX402V1PaymentPayload(v X402V1PaymentPayload) e return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9645,7 +13762,7 @@ func (t *X402PaymentRequirements) MergeX402V2PaymentRequirements(v X402V2Payment return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9671,7 +13788,7 @@ func (t *X402PaymentRequirements) MergeX402V1PaymentRequirements(v X402V1Payment return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9707,7 +13824,7 @@ func (t *X402V1PaymentPayload_Payload) MergeX402ExactEvmPayload(v X402ExactEvmPa return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9733,7 +13850,7 @@ func (t *X402V1PaymentPayload_Payload) MergeX402ExactEvmPermit2Payload(v X402Exa return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9759,7 +13876,7 @@ func (t *X402V1PaymentPayload_Payload) MergeX402ExactSolanaPayload(v X402ExactSo return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9795,7 +13912,7 @@ func (t *X402V2PaymentPayload_Payload) MergeX402ExactEvmPayload(v X402ExactEvmPa return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9821,7 +13938,7 @@ func (t *X402V2PaymentPayload_Payload) MergeX402ExactEvmPermit2Payload(v X402Exa return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9847,7 +13964,7 @@ func (t *X402V2PaymentPayload_Payload) MergeX402ExactSolanaPayload(v X402ExactSo return err } - merged, err := runtime.JsonMerge(t.union, b) + merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } @@ -9935,6 +14052,23 @@ func WithRequestEditorFn(fn RequestEditorFn) ClientOption { // The interface specification for the client above. type ClientInterface interface { + // ListFoundationAccounts request + ListFoundationAccounts(ctx context.Context, params *ListFoundationAccountsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateFoundationAccountWithBody request with any body + CreateFoundationAccountWithBody(ctx context.Context, params *CreateFoundationAccountParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateFoundationAccount(ctx context.Context, params *CreateFoundationAccountParams, body CreateFoundationAccountJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetFoundationAccountById request + GetFoundationAccountById(ctx context.Context, accountId AccountId, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListBalances request + ListBalances(ctx context.Context, accountId AccountId, params *ListBalancesParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetBalanceByAsset request + GetBalanceByAsset(ctx context.Context, accountId AccountId, asset Asset, reqEditors ...RequestEditorFn) (*http.Response, error) + // ListDataTokenBalances request ListDataTokenBalances(ctx context.Context, network ListEvmTokenBalancesNetwork, address string, params *ListDataTokenBalancesParams, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -9974,7 +14108,18 @@ type ClientInterface interface { // ListWebhookSubscriptionEvents request ListWebhookSubscriptionEvents(ctx context.Context, subscriptionId openapi_types.UUID, params *ListWebhookSubscriptionEventsParams, reqEditors ...RequestEditorFn) (*http.Response, error) - // RevokeDelegationForEndUserAccountWithBody request with any body + // ListDepositDestinations request + ListDepositDestinations(ctx context.Context, params *ListDepositDestinationsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateDepositDestinationWithBody request with any body + CreateDepositDestinationWithBody(ctx context.Context, params *CreateDepositDestinationParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateDepositDestination(ctx context.Context, params *CreateDepositDestinationParams, body CreateDepositDestinationJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetDepositDestinationById request + GetDepositDestinationById(ctx context.Context, depositDestinationId DepositDestinationId, reqEditors ...RequestEditorFn) (*http.Response, error) + + // RevokeDelegationForEndUserAccountWithBody request with any body RevokeDelegationForEndUserAccountWithBody(ctx context.Context, userId string, address BlockchainAddress, params *RevokeDelegationForEndUserAccountParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) RevokeDelegationForEndUserAccount(ctx context.Context, userId string, address BlockchainAddress, params *RevokeDelegationForEndUserAccountParams, body RevokeDelegationForEndUserAccountJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -10245,6 +14390,12 @@ type ClientInterface interface { CreateOnrampSession(ctx context.Context, body CreateOnrampSessionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + // ListPaymentMethods request + ListPaymentMethods(ctx context.Context, params *ListPaymentMethodsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetPaymentMethod request + GetPaymentMethod(ctx context.Context, paymentMethodId PaymentMethodId, reqEditors ...RequestEditorFn) (*http.Response, error) + // ListPolicies request ListPolicies(ctx context.Context, params *ListPoliciesParams, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -10321,6 +14472,25 @@ type ClientInterface interface { // ListSolanaTokenBalances request ListSolanaTokenBalances(ctx context.Context, network ListSolanaTokenBalancesNetwork, address string, params *ListSolanaTokenBalancesParams, reqEditors ...RequestEditorFn) (*http.Response, error) + // ListTransfers request + ListTransfers(ctx context.Context, params *ListTransfersParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateTransferWithBody request with any body + CreateTransferWithBody(ctx context.Context, params *CreateTransferParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateTransfer(ctx context.Context, params *CreateTransferParams, body CreateTransferJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetTransferById request + GetTransferById(ctx context.Context, transferId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ExecuteFundTransfer request + ExecuteFundTransfer(ctx context.Context, transferId string, params *ExecuteFundTransferParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // SubmitDepositTravelRuleWithBody request with any body + SubmitDepositTravelRuleWithBody(ctx context.Context, transferId string, params *SubmitDepositTravelRuleParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + SubmitDepositTravelRule(ctx context.Context, transferId string, params *SubmitDepositTravelRuleParams, body SubmitDepositTravelRuleJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + // PostX402DiscoveryMcpWithBody request with any body PostX402DiscoveryMcpWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -10349,6 +14519,78 @@ type ClientInterface interface { VerifyX402Payment(ctx context.Context, body VerifyX402PaymentJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) } +func (c *CDPClient) ListFoundationAccounts(ctx context.Context, params *ListFoundationAccountsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListFoundationAccountsRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *CDPClient) CreateFoundationAccountWithBody(ctx context.Context, params *CreateFoundationAccountParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateFoundationAccountRequestWithBody(c.Server, params, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *CDPClient) CreateFoundationAccount(ctx context.Context, params *CreateFoundationAccountParams, body CreateFoundationAccountJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateFoundationAccountRequest(c.Server, params, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *CDPClient) GetFoundationAccountById(ctx context.Context, accountId AccountId, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetFoundationAccountByIdRequest(c.Server, accountId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *CDPClient) ListBalances(ctx context.Context, accountId AccountId, params *ListBalancesParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListBalancesRequest(c.Server, accountId, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *CDPClient) GetBalanceByAsset(ctx context.Context, accountId AccountId, asset Asset, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetBalanceByAssetRequest(c.Server, accountId, asset) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + func (c *CDPClient) ListDataTokenBalances(ctx context.Context, network ListEvmTokenBalancesNetwork, address string, params *ListDataTokenBalancesParams, reqEditors ...RequestEditorFn) (*http.Response, error) { req, err := NewListDataTokenBalancesRequest(c.Server, network, address, params) if err != nil { @@ -10517,6 +14759,54 @@ func (c *CDPClient) ListWebhookSubscriptionEvents(ctx context.Context, subscript return c.Client.Do(req) } +func (c *CDPClient) ListDepositDestinations(ctx context.Context, params *ListDepositDestinationsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListDepositDestinationsRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *CDPClient) CreateDepositDestinationWithBody(ctx context.Context, params *CreateDepositDestinationParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateDepositDestinationRequestWithBody(c.Server, params, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *CDPClient) CreateDepositDestination(ctx context.Context, params *CreateDepositDestinationParams, body CreateDepositDestinationJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateDepositDestinationRequest(c.Server, params, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *CDPClient) GetDepositDestinationById(ctx context.Context, depositDestinationId DepositDestinationId, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetDepositDestinationByIdRequest(c.Server, depositDestinationId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + func (c *CDPClient) RevokeDelegationForEndUserAccountWithBody(ctx context.Context, userId string, address BlockchainAddress, params *RevokeDelegationForEndUserAccountParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { req, err := NewRevokeDelegationForEndUserAccountRequestWithBody(c.Server, userId, address, params, contentType, body) if err != nil { @@ -11777,6 +16067,30 @@ func (c *CDPClient) CreateOnrampSession(ctx context.Context, body CreateOnrampSe return c.Client.Do(req) } +func (c *CDPClient) ListPaymentMethods(ctx context.Context, params *ListPaymentMethodsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListPaymentMethodsRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *CDPClient) GetPaymentMethod(ctx context.Context, paymentMethodId PaymentMethodId, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetPaymentMethodRequest(c.Server, paymentMethodId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + func (c *CDPClient) ListPolicies(ctx context.Context, params *ListPoliciesParams, reqEditors ...RequestEditorFn) (*http.Response, error) { req, err := NewListPoliciesRequest(c.Server, params) if err != nil { @@ -12125,6 +16439,90 @@ func (c *CDPClient) ListSolanaTokenBalances(ctx context.Context, network ListSol return c.Client.Do(req) } +func (c *CDPClient) ListTransfers(ctx context.Context, params *ListTransfersParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListTransfersRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *CDPClient) CreateTransferWithBody(ctx context.Context, params *CreateTransferParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateTransferRequestWithBody(c.Server, params, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *CDPClient) CreateTransfer(ctx context.Context, params *CreateTransferParams, body CreateTransferJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateTransferRequest(c.Server, params, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *CDPClient) GetTransferById(ctx context.Context, transferId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetTransferByIdRequest(c.Server, transferId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *CDPClient) ExecuteFundTransfer(ctx context.Context, transferId string, params *ExecuteFundTransferParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewExecuteFundTransferRequest(c.Server, transferId, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *CDPClient) SubmitDepositTravelRuleWithBody(ctx context.Context, transferId string, params *SubmitDepositTravelRuleParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewSubmitDepositTravelRuleRequestWithBody(c.Server, transferId, params, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *CDPClient) SubmitDepositTravelRule(ctx context.Context, transferId string, params *SubmitDepositTravelRuleParams, body SubmitDepositTravelRuleJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewSubmitDepositTravelRuleRequest(c.Server, transferId, params, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + func (c *CDPClient) PostX402DiscoveryMcpWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { req, err := NewPostX402DiscoveryMcpRequestWithBody(c.Server, contentType, body) if err != nil { @@ -12245,30 +16643,16 @@ func (c *CDPClient) VerifyX402Payment(ctx context.Context, body VerifyX402Paymen return c.Client.Do(req) } -// NewListDataTokenBalancesRequest generates requests for ListDataTokenBalances -func NewListDataTokenBalancesRequest(server string, network ListEvmTokenBalancesNetwork, address string, params *ListDataTokenBalancesParams) (*http.Request, error) { +// NewListFoundationAccountsRequest generates requests for ListFoundationAccounts +func NewListFoundationAccountsRequest(server string, params *ListFoundationAccountsParams) (*http.Request, error) { var err error - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "network", runtime.ParamLocationPath, network) - if err != nil { - return nil, err - } - - var pathParam1 string - - pathParam1, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) - if err != nil { - return nil, err - } - serverURL, err := url.Parse(server) if err != nil { return nil, err } - operationPath := fmt.Sprintf("/v2/data/evm/token-balances/%s/%s", pathParam0, pathParam1) + operationPath := fmt.Sprintf("/v2/accounts") if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -12279,19 +16663,21 @@ func NewListDataTokenBalancesRequest(server string, network ListEvmTokenBalances } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.PageSize != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "pageSize", runtime.ParamLocationQuery, *params.PageSize); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } @@ -12299,24 +16685,35 @@ func NewListDataTokenBalancesRequest(server string, network ListEvmTokenBalances if params.PageToken != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "pageToken", runtime.ParamLocationQuery, *params.PageToken); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageToken", *params.PageToken, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Type != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "type", *params.Type, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -12324,30 +16721,27 @@ func NewListDataTokenBalancesRequest(server string, network ListEvmTokenBalances return req, nil } -// NewListTokensForAccountRequest generates requests for ListTokensForAccount -func NewListTokensForAccountRequest(server string, network ListTokensForAccountParamsNetwork, address string) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "network", runtime.ParamLocationPath, network) +// NewCreateFoundationAccountRequest calls the generic CreateFoundationAccount builder with application/json body +func NewCreateFoundationAccountRequest(server string, params *CreateFoundationAccountParams, body CreateFoundationAccountJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) if err != nil { return nil, err } + bodyReader = bytes.NewReader(buf) + return NewCreateFoundationAccountRequestWithBody(server, params, "application/json", bodyReader) +} - var pathParam1 string - - pathParam1, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) - if err != nil { - return nil, err - } +// NewCreateFoundationAccountRequestWithBody generates requests for CreateFoundationAccount with any type of body +func NewCreateFoundationAccountRequestWithBody(server string, params *CreateFoundationAccountParams, contentType string, body io.Reader) (*http.Request, error) { + var err error serverURL, err := url.Parse(server) if err != nil { return nil, err } - operationPath := fmt.Sprintf("/v2/data/evm/token-ownership/%s/%s", pathParam0, pathParam1) + operationPath := fmt.Sprintf("/v2/accounts") if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -12357,21 +16751,307 @@ func NewListTokensForAccountRequest(server string, network ListTokensForAccountP return nil, err } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } - return req, nil -} + req.Header.Add("Content-Type", contentType) -// NewGetSQLGrammarRequest generates requests for GetSQLGrammar -func NewGetSQLGrammarRequest(server string) (*http.Request, error) { - var err error + if params != nil { - serverURL, err := url.Parse(server) - if err != nil { - return nil, err + if params.XIdempotencyKey != nil { + var headerParam0 string + + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + req.Header.Set("X-Idempotency-Key", headerParam0) + } + + } + + return req, nil +} + +// NewGetFoundationAccountByIdRequest generates requests for GetFoundationAccountById +func NewGetFoundationAccountByIdRequest(server string, accountId AccountId) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "accountId", accountId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v2/accounts/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListBalancesRequest generates requests for ListBalances +func NewListBalancesRequest(server string, accountId AccountId, params *ListBalancesParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "accountId", accountId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v2/accounts/%s/balances", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageToken != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageToken", *params.PageToken, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetBalanceByAssetRequest generates requests for GetBalanceByAsset +func NewGetBalanceByAssetRequest(server string, accountId AccountId, asset Asset) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "accountId", accountId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "asset", asset, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v2/accounts/%s/balances/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListDataTokenBalancesRequest generates requests for ListDataTokenBalances +func NewListDataTokenBalancesRequest(server string, network ListEvmTokenBalancesNetwork, address string, params *ListDataTokenBalancesParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "network", network, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v2/data/evm/token-balances/%s/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageToken != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageToken", *params.PageToken, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListTokensForAccountRequest generates requests for ListTokensForAccount +func NewListTokensForAccountRequest(server string, network ListTokensForAccountParamsNetwork, address string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "network", network, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v2/data/evm/token-ownership/%s/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetSQLGrammarRequest generates requests for GetSQLGrammar +func NewGetSQLGrammarRequest(server string) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err } operationPath := fmt.Sprintf("/v2/data/query/grammar") @@ -12384,7 +17064,7 @@ func NewGetSQLGrammarRequest(server string) (*http.Request, error) { return nil, err } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -12422,7 +17102,7 @@ func NewRunSQLQueryRequestWithBody(server string, contentType string, body io.Re return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -12452,19 +17132,21 @@ func NewGetSQLSchemaRequest(server string, params *GetSQLSchemaParams) (*http.Re } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.Database != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "database", runtime.ParamLocationQuery, *params.Database); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "database", *params.Database, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } @@ -12472,24 +17154,23 @@ func NewGetSQLSchemaRequest(server string, params *GetSQLSchemaParams) (*http.Re if params.Table != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "table", runtime.ParamLocationQuery, *params.Table); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "table", *params.Table, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -12517,19 +17198,21 @@ func NewListWebhookSubscriptionsRequest(server string, params *ListWebhookSubscr } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.PageSize != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "pageSize", runtime.ParamLocationQuery, *params.PageSize); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } @@ -12537,24 +17220,23 @@ func NewListWebhookSubscriptionsRequest(server string, params *ListWebhookSubscr if params.PageToken != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "pageToken", runtime.ParamLocationQuery, *params.PageToken); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageToken", *params.PageToken, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -12592,7 +17274,7 @@ func NewCreateWebhookSubscriptionRequestWithBody(server string, contentType stri return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -12608,7 +17290,7 @@ func NewDeleteWebhookSubscriptionRequest(server string, subscriptionId openapi_t var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "subscriptionId", runtime.ParamLocationPath, subscriptionId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subscriptionId", subscriptionId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) if err != nil { return nil, err } @@ -12628,7 +17310,7 @@ func NewDeleteWebhookSubscriptionRequest(server string, subscriptionId openapi_t return nil, err } - req, err := http.NewRequest("DELETE", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) if err != nil { return nil, err } @@ -12642,7 +17324,7 @@ func NewGetWebhookSubscriptionRequest(server string, subscriptionId openapi_type var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "subscriptionId", runtime.ParamLocationPath, subscriptionId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subscriptionId", subscriptionId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) if err != nil { return nil, err } @@ -12662,7 +17344,7 @@ func NewGetWebhookSubscriptionRequest(server string, subscriptionId openapi_type return nil, err } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -12687,7 +17369,7 @@ func NewUpdateWebhookSubscriptionRequestWithBody(server string, subscriptionId o var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "subscriptionId", runtime.ParamLocationPath, subscriptionId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subscriptionId", subscriptionId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) if err != nil { return nil, err } @@ -12707,7 +17389,7 @@ func NewUpdateWebhookSubscriptionRequestWithBody(server string, subscriptionId o return nil, err } - req, err := http.NewRequest("PUT", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPut, queryURL.String(), body) if err != nil { return nil, err } @@ -12723,7 +17405,7 @@ func NewListWebhookSubscriptionEventsRequest(server string, subscriptionId opena var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "subscriptionId", runtime.ParamLocationPath, subscriptionId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subscriptionId", subscriptionId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) if err != nil { return nil, err } @@ -12744,19 +17426,21 @@ func NewListWebhookSubscriptionEventsRequest(server string, subscriptionId opena } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.EventId != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "eventId", runtime.ParamLocationQuery, *params.EventId); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "eventId", *params.EventId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "uuid"}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } @@ -12764,15 +17448,11 @@ func NewListWebhookSubscriptionEventsRequest(server string, subscriptionId opena if params.MinCreatedAt != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "minCreatedAt", runtime.ParamLocationQuery, *params.MinCreatedAt); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "minCreatedAt", *params.MinCreatedAt, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } @@ -12780,15 +17460,11 @@ func NewListWebhookSubscriptionEventsRequest(server string, subscriptionId opena if params.MaxCreatedAt != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "maxCreatedAt", runtime.ParamLocationQuery, *params.MaxCreatedAt); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "maxCreatedAt", *params.MaxCreatedAt, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } @@ -12796,24 +17472,23 @@ func NewListWebhookSubscriptionEventsRequest(server string, subscriptionId opena if params.EventTypeNames != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "eventTypeNames", runtime.ParamLocationQuery, *params.EventTypeNames); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "eventTypeNames", *params.EventTypeNames, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -12821,12 +17496,215 @@ func NewListWebhookSubscriptionEventsRequest(server string, subscriptionId opena return req, nil } -// NewRevokeDelegationForEndUserAccountRequest calls the generic RevokeDelegationForEndUserAccount builder with application/json body -func NewRevokeDelegationForEndUserAccountRequest(server string, userId string, address BlockchainAddress, params *RevokeDelegationForEndUserAccountParams, body RevokeDelegationForEndUserAccountJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err +// NewListDepositDestinationsRequest generates requests for ListDepositDestinations +func NewListDepositDestinationsRequest(server string, params *ListDepositDestinationsParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v2/deposit-destinations") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.AccountId != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "accountId", *params.AccountId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Address != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "address", *params.Address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Type != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "type", *params.Type, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Network != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "network", *params.Network, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageToken != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageToken", *params.PageToken, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewCreateDepositDestinationRequest calls the generic CreateDepositDestination builder with application/json body +func NewCreateDepositDestinationRequest(server string, params *CreateDepositDestinationParams, body CreateDepositDestinationJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreateDepositDestinationRequestWithBody(server, params, "application/json", bodyReader) +} + +// NewCreateDepositDestinationRequestWithBody generates requests for CreateDepositDestination with any type of body +func NewCreateDepositDestinationRequestWithBody(server string, params *CreateDepositDestinationParams, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v2/deposit-destinations") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + if params != nil { + + if params.XIdempotencyKey != nil { + var headerParam0 string + + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + req.Header.Set("X-Idempotency-Key", headerParam0) + } + + } + + return req, nil +} + +// NewGetDepositDestinationByIdRequest generates requests for GetDepositDestinationById +func NewGetDepositDestinationByIdRequest(server string, depositDestinationId DepositDestinationId) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "depositDestinationId", depositDestinationId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v2/deposit-destinations/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewRevokeDelegationForEndUserAccountRequest calls the generic RevokeDelegationForEndUserAccount builder with application/json body +func NewRevokeDelegationForEndUserAccountRequest(server string, userId string, address BlockchainAddress, params *RevokeDelegationForEndUserAccountParams, body RevokeDelegationForEndUserAccountJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err } bodyReader = bytes.NewReader(buf) return NewRevokeDelegationForEndUserAccountRequestWithBody(server, userId, address, params, "application/json", bodyReader) @@ -12838,14 +17716,14 @@ func NewRevokeDelegationForEndUserAccountRequestWithBody(server string, userId s var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "userId", userId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } var pathParam1 string - pathParam1, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -12866,28 +17744,33 @@ func NewRevokeDelegationForEndUserAccountRequestWithBody(server string, userId s } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.ProjectID != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "projectID", runtime.ParamLocationQuery, *params.ProjectID); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "projectID", *params.ProjectID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("DELETE", queryURL.String(), body) + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), body) if err != nil { return nil, err } @@ -12899,7 +17782,7 @@ func NewRevokeDelegationForEndUserAccountRequestWithBody(server string, userId s if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -12910,7 +17793,7 @@ func NewRevokeDelegationForEndUserAccountRequestWithBody(server string, userId s if params.XDeveloperAuth != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Developer-Auth", runtime.ParamLocationHeader, *params.XDeveloperAuth) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Developer-Auth", *params.XDeveloperAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -12921,7 +17804,7 @@ func NewRevokeDelegationForEndUserAccountRequestWithBody(server string, userId s if params.XIdempotencyKey != nil { var headerParam2 string - headerParam2, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam2, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -12940,14 +17823,14 @@ func NewGetDelegationForEndUserAccountRequest(server string, userId string, addr var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "userId", userId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } var pathParam1 string - pathParam1, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -12968,28 +17851,33 @@ func NewGetDelegationForEndUserAccountRequest(server string, userId string, addr } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.ProjectID != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "projectID", runtime.ParamLocationQuery, *params.ProjectID); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "projectID", *params.ProjectID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -13014,14 +17902,14 @@ func NewCreateDelegationForEndUserAccountRequestWithBody(server string, userId s var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "userId", userId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } var pathParam1 string - pathParam1, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13042,28 +17930,33 @@ func NewCreateDelegationForEndUserAccountRequestWithBody(server string, userId s } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.ProjectID != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "projectID", runtime.ParamLocationQuery, *params.ProjectID); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "projectID", *params.ProjectID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -13075,7 +17968,7 @@ func NewCreateDelegationForEndUserAccountRequestWithBody(server string, userId s if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13086,7 +17979,7 @@ func NewCreateDelegationForEndUserAccountRequestWithBody(server string, userId s if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13116,7 +18009,7 @@ func NewRevokeDelegationForEndUserRequestWithBody(server string, userId string, var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "userId", userId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13137,28 +18030,33 @@ func NewRevokeDelegationForEndUserRequestWithBody(server string, userId string, } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.ProjectID != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "projectID", runtime.ParamLocationQuery, *params.ProjectID); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "projectID", *params.ProjectID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("DELETE", queryURL.String(), body) + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), body) if err != nil { return nil, err } @@ -13170,7 +18068,7 @@ func NewRevokeDelegationForEndUserRequestWithBody(server string, userId string, if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13181,7 +18079,7 @@ func NewRevokeDelegationForEndUserRequestWithBody(server string, userId string, if params.XDeveloperAuth != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Developer-Auth", runtime.ParamLocationHeader, *params.XDeveloperAuth) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Developer-Auth", *params.XDeveloperAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13192,7 +18090,7 @@ func NewRevokeDelegationForEndUserRequestWithBody(server string, userId string, if params.XIdempotencyKey != nil { var headerParam2 string - headerParam2, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam2, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13211,7 +18109,7 @@ func NewGetDelegationForEndUserRequest(server string, userId string, params *Get var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "userId", userId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13232,28 +18130,33 @@ func NewGetDelegationForEndUserRequest(server string, userId string, params *Get } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.ProjectID != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "projectID", runtime.ParamLocationQuery, *params.ProjectID); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "projectID", *params.ProjectID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -13278,7 +18181,7 @@ func NewCreateEvmEip7702DelegationWithEndUserAccountRequestWithBody(server strin var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "userId", userId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13299,28 +18202,33 @@ func NewCreateEvmEip7702DelegationWithEndUserAccountRequestWithBody(server strin } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.ProjectID != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "projectID", runtime.ParamLocationQuery, *params.ProjectID); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "projectID", *params.ProjectID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -13332,7 +18240,7 @@ func NewCreateEvmEip7702DelegationWithEndUserAccountRequestWithBody(server strin if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13343,7 +18251,7 @@ func NewCreateEvmEip7702DelegationWithEndUserAccountRequestWithBody(server strin if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13354,7 +18262,7 @@ func NewCreateEvmEip7702DelegationWithEndUserAccountRequestWithBody(server strin if params.XDeveloperAuth != nil { var headerParam2 string - headerParam2, err = runtime.StyleParamWithLocation("simple", false, "X-Developer-Auth", runtime.ParamLocationHeader, *params.XDeveloperAuth) + headerParam2, err = runtime.StyleParamWithOptions("simple", false, "X-Developer-Auth", *params.XDeveloperAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13384,7 +18292,7 @@ func NewSendEvmTransactionWithEndUserAccountRequestWithBody(server string, userI var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "userId", userId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13405,28 +18313,33 @@ func NewSendEvmTransactionWithEndUserAccountRequestWithBody(server string, userI } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.ProjectID != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "projectID", runtime.ParamLocationQuery, *params.ProjectID); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "projectID", *params.ProjectID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -13438,7 +18351,7 @@ func NewSendEvmTransactionWithEndUserAccountRequestWithBody(server string, userI if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13449,7 +18362,7 @@ func NewSendEvmTransactionWithEndUserAccountRequestWithBody(server string, userI if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13460,7 +18373,7 @@ func NewSendEvmTransactionWithEndUserAccountRequestWithBody(server string, userI if params.XDeveloperAuth != nil { var headerParam2 string - headerParam2, err = runtime.StyleParamWithLocation("simple", false, "X-Developer-Auth", runtime.ParamLocationHeader, *params.XDeveloperAuth) + headerParam2, err = runtime.StyleParamWithOptions("simple", false, "X-Developer-Auth", *params.XDeveloperAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13490,7 +18403,7 @@ func NewSignEvmMessageWithEndUserAccountRequestWithBody(server string, userId st var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "userId", userId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13511,28 +18424,33 @@ func NewSignEvmMessageWithEndUserAccountRequestWithBody(server string, userId st } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.ProjectID != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "projectID", runtime.ParamLocationQuery, *params.ProjectID); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "projectID", *params.ProjectID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -13544,7 +18462,7 @@ func NewSignEvmMessageWithEndUserAccountRequestWithBody(server string, userId st if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13555,7 +18473,7 @@ func NewSignEvmMessageWithEndUserAccountRequestWithBody(server string, userId st if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13566,7 +18484,7 @@ func NewSignEvmMessageWithEndUserAccountRequestWithBody(server string, userId st if params.XDeveloperAuth != nil { var headerParam2 string - headerParam2, err = runtime.StyleParamWithLocation("simple", false, "X-Developer-Auth", runtime.ParamLocationHeader, *params.XDeveloperAuth) + headerParam2, err = runtime.StyleParamWithOptions("simple", false, "X-Developer-Auth", *params.XDeveloperAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13596,7 +18514,7 @@ func NewSignEvmTransactionWithEndUserAccountRequestWithBody(server string, userI var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "userId", userId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13617,28 +18535,33 @@ func NewSignEvmTransactionWithEndUserAccountRequestWithBody(server string, userI } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.ProjectID != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "projectID", runtime.ParamLocationQuery, *params.ProjectID); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "projectID", *params.ProjectID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -13650,7 +18573,7 @@ func NewSignEvmTransactionWithEndUserAccountRequestWithBody(server string, userI if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13661,7 +18584,7 @@ func NewSignEvmTransactionWithEndUserAccountRequestWithBody(server string, userI if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13672,7 +18595,7 @@ func NewSignEvmTransactionWithEndUserAccountRequestWithBody(server string, userI if params.XDeveloperAuth != nil { var headerParam2 string - headerParam2, err = runtime.StyleParamWithLocation("simple", false, "X-Developer-Auth", runtime.ParamLocationHeader, *params.XDeveloperAuth) + headerParam2, err = runtime.StyleParamWithOptions("simple", false, "X-Developer-Auth", *params.XDeveloperAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13702,7 +18625,7 @@ func NewSignEvmTypedDataWithEndUserAccountRequestWithBody(server string, userId var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "userId", userId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13723,28 +18646,33 @@ func NewSignEvmTypedDataWithEndUserAccountRequestWithBody(server string, userId } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.ProjectID != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "projectID", runtime.ParamLocationQuery, *params.ProjectID); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "projectID", *params.ProjectID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -13756,7 +18684,7 @@ func NewSignEvmTypedDataWithEndUserAccountRequestWithBody(server string, userId if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13767,7 +18695,7 @@ func NewSignEvmTypedDataWithEndUserAccountRequestWithBody(server string, userId if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13778,7 +18706,7 @@ func NewSignEvmTypedDataWithEndUserAccountRequestWithBody(server string, userId if params.XDeveloperAuth != nil { var headerParam2 string - headerParam2, err = runtime.StyleParamWithLocation("simple", false, "X-Developer-Auth", runtime.ParamLocationHeader, *params.XDeveloperAuth) + headerParam2, err = runtime.StyleParamWithOptions("simple", false, "X-Developer-Auth", *params.XDeveloperAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13808,14 +18736,14 @@ func NewSendUserOperationWithEndUserAccountRequestWithBody(server string, userId var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "userId", userId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } var pathParam1 string - pathParam1, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13836,28 +18764,33 @@ func NewSendUserOperationWithEndUserAccountRequestWithBody(server string, userId } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.ProjectID != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "projectID", runtime.ParamLocationQuery, *params.ProjectID); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "projectID", *params.ProjectID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -13869,7 +18802,7 @@ func NewSendUserOperationWithEndUserAccountRequestWithBody(server string, userId if params.XIdempotencyKey != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13880,7 +18813,7 @@ func NewSendUserOperationWithEndUserAccountRequestWithBody(server string, userId if params.XWalletAuth != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13891,7 +18824,7 @@ func NewSendUserOperationWithEndUserAccountRequestWithBody(server string, userId if params.XDeveloperAuth != nil { var headerParam2 string - headerParam2, err = runtime.StyleParamWithLocation("simple", false, "X-Developer-Auth", runtime.ParamLocationHeader, *params.XDeveloperAuth) + headerParam2, err = runtime.StyleParamWithOptions("simple", false, "X-Developer-Auth", *params.XDeveloperAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -13921,21 +18854,21 @@ func NewSendEvmAssetWithEndUserAccountRequestWithBody(server string, userId stri var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "userId", userId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } var pathParam1 string - pathParam1, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) if err != nil { return nil, err } var pathParam2 string - pathParam2, err = runtime.StyleParamWithLocation("simple", false, "asset", runtime.ParamLocationPath, asset) + pathParam2, err = runtime.StyleParamWithOptions("simple", false, "asset", asset, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) if err != nil { return nil, err } @@ -13956,28 +18889,33 @@ func NewSendEvmAssetWithEndUserAccountRequestWithBody(server string, userId stri } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.ProjectID != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "projectID", runtime.ParamLocationQuery, *params.ProjectID); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "projectID", *params.ProjectID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -13989,7 +18927,7 @@ func NewSendEvmAssetWithEndUserAccountRequestWithBody(server string, userId stri if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14000,7 +18938,7 @@ func NewSendEvmAssetWithEndUserAccountRequestWithBody(server string, userId stri if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14011,7 +18949,7 @@ func NewSendEvmAssetWithEndUserAccountRequestWithBody(server string, userId stri if params.XDeveloperAuth != nil { var headerParam2 string - headerParam2, err = runtime.StyleParamWithLocation("simple", false, "X-Developer-Auth", runtime.ParamLocationHeader, *params.XDeveloperAuth) + headerParam2, err = runtime.StyleParamWithOptions("simple", false, "X-Developer-Auth", *params.XDeveloperAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14041,7 +18979,7 @@ func NewSendSolanaTransactionWithEndUserAccountRequestWithBody(server string, us var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "userId", userId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14062,28 +19000,33 @@ func NewSendSolanaTransactionWithEndUserAccountRequestWithBody(server string, us } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.ProjectID != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "projectID", runtime.ParamLocationQuery, *params.ProjectID); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "projectID", *params.ProjectID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -14095,7 +19038,7 @@ func NewSendSolanaTransactionWithEndUserAccountRequestWithBody(server string, us if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14106,7 +19049,7 @@ func NewSendSolanaTransactionWithEndUserAccountRequestWithBody(server string, us if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14117,7 +19060,7 @@ func NewSendSolanaTransactionWithEndUserAccountRequestWithBody(server string, us if params.XDeveloperAuth != nil { var headerParam2 string - headerParam2, err = runtime.StyleParamWithLocation("simple", false, "X-Developer-Auth", runtime.ParamLocationHeader, *params.XDeveloperAuth) + headerParam2, err = runtime.StyleParamWithOptions("simple", false, "X-Developer-Auth", *params.XDeveloperAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14147,7 +19090,7 @@ func NewSignSolanaMessageWithEndUserAccountRequestWithBody(server string, userId var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "userId", userId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14168,28 +19111,33 @@ func NewSignSolanaMessageWithEndUserAccountRequestWithBody(server string, userId } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.ProjectID != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "projectID", runtime.ParamLocationQuery, *params.ProjectID); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "projectID", *params.ProjectID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -14201,7 +19149,7 @@ func NewSignSolanaMessageWithEndUserAccountRequestWithBody(server string, userId if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14212,7 +19160,7 @@ func NewSignSolanaMessageWithEndUserAccountRequestWithBody(server string, userId if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14223,7 +19171,7 @@ func NewSignSolanaMessageWithEndUserAccountRequestWithBody(server string, userId if params.XDeveloperAuth != nil { var headerParam2 string - headerParam2, err = runtime.StyleParamWithLocation("simple", false, "X-Developer-Auth", runtime.ParamLocationHeader, *params.XDeveloperAuth) + headerParam2, err = runtime.StyleParamWithOptions("simple", false, "X-Developer-Auth", *params.XDeveloperAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14253,7 +19201,7 @@ func NewSignSolanaTransactionWithEndUserAccountRequestWithBody(server string, us var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "userId", userId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14274,28 +19222,33 @@ func NewSignSolanaTransactionWithEndUserAccountRequestWithBody(server string, us } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.ProjectID != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "projectID", runtime.ParamLocationQuery, *params.ProjectID); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "projectID", *params.ProjectID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -14307,7 +19260,7 @@ func NewSignSolanaTransactionWithEndUserAccountRequestWithBody(server string, us if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14318,7 +19271,7 @@ func NewSignSolanaTransactionWithEndUserAccountRequestWithBody(server string, us if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14329,7 +19282,7 @@ func NewSignSolanaTransactionWithEndUserAccountRequestWithBody(server string, us if params.XDeveloperAuth != nil { var headerParam2 string - headerParam2, err = runtime.StyleParamWithLocation("simple", false, "X-Developer-Auth", runtime.ParamLocationHeader, *params.XDeveloperAuth) + headerParam2, err = runtime.StyleParamWithOptions("simple", false, "X-Developer-Auth", *params.XDeveloperAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14359,21 +19312,21 @@ func NewSendSolanaAssetWithEndUserAccountRequestWithBody(server string, userId s var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "userId", userId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } var pathParam1 string - pathParam1, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) if err != nil { return nil, err } var pathParam2 string - pathParam2, err = runtime.StyleParamWithLocation("simple", false, "asset", runtime.ParamLocationPath, asset) + pathParam2, err = runtime.StyleParamWithOptions("simple", false, "asset", asset, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) if err != nil { return nil, err } @@ -14394,28 +19347,33 @@ func NewSendSolanaAssetWithEndUserAccountRequestWithBody(server string, userId s } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.ProjectID != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "projectID", runtime.ParamLocationQuery, *params.ProjectID); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "projectID", *params.ProjectID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -14427,7 +19385,7 @@ func NewSendSolanaAssetWithEndUserAccountRequestWithBody(server string, userId s if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14438,7 +19396,7 @@ func NewSendSolanaAssetWithEndUserAccountRequestWithBody(server string, userId s if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14449,7 +19407,7 @@ func NewSendSolanaAssetWithEndUserAccountRequestWithBody(server string, userId s if params.XDeveloperAuth != nil { var headerParam2 string - headerParam2, err = runtime.StyleParamWithLocation("simple", false, "X-Developer-Auth", runtime.ParamLocationHeader, *params.XDeveloperAuth) + headerParam2, err = runtime.StyleParamWithOptions("simple", false, "X-Developer-Auth", *params.XDeveloperAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14482,19 +19440,21 @@ func NewListEndUsersRequest(server string, params *ListEndUsersParams) (*http.Re } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.PageSize != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "pageSize", runtime.ParamLocationQuery, *params.PageSize); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } @@ -14502,15 +19462,11 @@ func NewListEndUsersRequest(server string, params *ListEndUsersParams) (*http.Re if params.PageToken != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "pageToken", runtime.ParamLocationQuery, *params.PageToken); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageToken", *params.PageToken, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } @@ -14518,24 +19474,23 @@ func NewListEndUsersRequest(server string, params *ListEndUsersParams) (*http.Re if params.Sort != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", false, "sort", runtime.ParamLocationQuery, *params.Sort); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "sort", *params.Sort, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -14573,7 +19528,7 @@ func NewCreateEndUserRequestWithBody(server string, params *CreateEndUserParams, return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -14585,7 +19540,7 @@ func NewCreateEndUserRequestWithBody(server string, params *CreateEndUserParams, if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14596,7 +19551,7 @@ func NewCreateEndUserRequestWithBody(server string, params *CreateEndUserParams, if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14639,7 +19594,7 @@ func NewValidateEndUserAccessTokenRequestWithBody(server string, contentType str return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -14679,7 +19634,7 @@ func NewImportEndUserRequestWithBody(server string, params *ImportEndUserParams, return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -14691,7 +19646,7 @@ func NewImportEndUserRequestWithBody(server string, params *ImportEndUserParams, if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14702,7 +19657,7 @@ func NewImportEndUserRequestWithBody(server string, params *ImportEndUserParams, if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14735,19 +19690,21 @@ func NewLookupEndUserRequest(server string, params *LookupEndUserParams) (*http. } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.Email != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "email", runtime.ParamLocationQuery, *params.Email); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "email", *params.Email, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "email"}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } @@ -14755,15 +19712,11 @@ func NewLookupEndUserRequest(server string, params *LookupEndUserParams) (*http. if params.OauthProvider != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "oauthProvider", runtime.ParamLocationQuery, *params.OauthProvider); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "oauthProvider", *params.OauthProvider, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } @@ -14771,15 +19724,11 @@ func NewLookupEndUserRequest(server string, params *LookupEndUserParams) (*http. if params.OauthSubject != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "oauthSubject", runtime.ParamLocationQuery, *params.OauthSubject); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "oauthSubject", *params.OauthSubject, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } @@ -14787,24 +19736,23 @@ func NewLookupEndUserRequest(server string, params *LookupEndUserParams) (*http. if params.PhoneNumber != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "phoneNumber", runtime.ParamLocationQuery, *params.PhoneNumber); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "phoneNumber", *params.PhoneNumber, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -14818,7 +19766,7 @@ func NewGetEndUserRequest(server string, userId string) (*http.Request, error) { var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "userId", userId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14838,7 +19786,7 @@ func NewGetEndUserRequest(server string, userId string) (*http.Request, error) { return nil, err } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -14863,7 +19811,7 @@ func NewAddEndUserEvmAccountRequestWithBody(server string, userId string, params var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "userId", userId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14883,7 +19831,7 @@ func NewAddEndUserEvmAccountRequestWithBody(server string, userId string, params return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -14895,7 +19843,7 @@ func NewAddEndUserEvmAccountRequestWithBody(server string, userId string, params if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14906,7 +19854,7 @@ func NewAddEndUserEvmAccountRequestWithBody(server string, userId string, params if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14936,7 +19884,7 @@ func NewAddEndUserEvmSmartAccountRequestWithBody(server string, userId string, p var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "userId", userId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14956,7 +19904,7 @@ func NewAddEndUserEvmSmartAccountRequestWithBody(server string, userId string, p return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -14968,7 +19916,7 @@ func NewAddEndUserEvmSmartAccountRequestWithBody(server string, userId string, p if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -14979,7 +19927,7 @@ func NewAddEndUserEvmSmartAccountRequestWithBody(server string, userId string, p if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15009,7 +19957,7 @@ func NewAddEndUserSolanaAccountRequestWithBody(server string, userId string, par var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "userId", userId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15029,7 +19977,7 @@ func NewAddEndUserSolanaAccountRequestWithBody(server string, userId string, par return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -15041,7 +19989,7 @@ func NewAddEndUserSolanaAccountRequestWithBody(server string, userId string, par if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15052,7 +20000,7 @@ func NewAddEndUserSolanaAccountRequestWithBody(server string, userId string, par if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15085,19 +20033,21 @@ func NewListEvmAccountsRequest(server string, params *ListEvmAccountsParams) (*h } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.PageSize != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "pageSize", runtime.ParamLocationQuery, *params.PageSize); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } @@ -15105,24 +20055,23 @@ func NewListEvmAccountsRequest(server string, params *ListEvmAccountsParams) (*h if params.PageToken != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "pageToken", runtime.ParamLocationQuery, *params.PageToken); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageToken", *params.PageToken, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -15160,7 +20109,7 @@ func NewCreateEvmAccountRequestWithBody(server string, params *CreateEvmAccountP return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -15172,7 +20121,7 @@ func NewCreateEvmAccountRequestWithBody(server string, params *CreateEvmAccountP if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15183,7 +20132,7 @@ func NewCreateEvmAccountRequestWithBody(server string, params *CreateEvmAccountP if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15202,7 +20151,7 @@ func NewGetEvmAccountByNameRequest(server string, name string) (*http.Request, e var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "name", runtime.ParamLocationPath, name) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "name", name, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15222,7 +20171,7 @@ func NewGetEvmAccountByNameRequest(server string, name string) (*http.Request, e return nil, err } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -15247,7 +20196,7 @@ func NewExportEvmAccountByNameRequestWithBody(server string, name string, params var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "name", runtime.ParamLocationPath, name) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "name", name, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15267,7 +20216,7 @@ func NewExportEvmAccountByNameRequestWithBody(server string, name string, params return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -15279,7 +20228,7 @@ func NewExportEvmAccountByNameRequestWithBody(server string, name string, params if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15290,7 +20239,7 @@ func NewExportEvmAccountByNameRequestWithBody(server string, name string, params if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15333,7 +20282,7 @@ func NewImportEvmAccountRequestWithBody(server string, params *ImportEvmAccountP return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -15345,7 +20294,7 @@ func NewImportEvmAccountRequestWithBody(server string, params *ImportEvmAccountP if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15356,7 +20305,7 @@ func NewImportEvmAccountRequestWithBody(server string, params *ImportEvmAccountP if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15375,7 +20324,7 @@ func NewGetEvmAccountRequest(server string, address string) (*http.Request, erro var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15395,7 +20344,7 @@ func NewGetEvmAccountRequest(server string, address string) (*http.Request, erro return nil, err } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -15420,7 +20369,7 @@ func NewUpdateEvmAccountRequestWithBody(server string, address string, params *U var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15440,7 +20389,7 @@ func NewUpdateEvmAccountRequestWithBody(server string, address string, params *U return nil, err } - req, err := http.NewRequest("PUT", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPut, queryURL.String(), body) if err != nil { return nil, err } @@ -15452,7 +20401,7 @@ func NewUpdateEvmAccountRequestWithBody(server string, address string, params *U if params.XIdempotencyKey != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15482,7 +20431,7 @@ func NewCreateEvmEip7702DelegationRequestWithBody(server string, address string, var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15502,7 +20451,7 @@ func NewCreateEvmEip7702DelegationRequestWithBody(server string, address string, return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -15514,7 +20463,7 @@ func NewCreateEvmEip7702DelegationRequestWithBody(server string, address string, if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15525,7 +20474,7 @@ func NewCreateEvmEip7702DelegationRequestWithBody(server string, address string, if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15555,7 +20504,7 @@ func NewExportEvmAccountRequestWithBody(server string, address string, params *E var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15575,7 +20524,7 @@ func NewExportEvmAccountRequestWithBody(server string, address string, params *E return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -15587,7 +20536,7 @@ func NewExportEvmAccountRequestWithBody(server string, address string, params *E if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15598,7 +20547,7 @@ func NewExportEvmAccountRequestWithBody(server string, address string, params *E if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15628,7 +20577,7 @@ func NewSendEvmTransactionRequestWithBody(server string, address string, params var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15648,7 +20597,7 @@ func NewSendEvmTransactionRequestWithBody(server string, address string, params return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -15660,7 +20609,7 @@ func NewSendEvmTransactionRequestWithBody(server string, address string, params if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15671,7 +20620,7 @@ func NewSendEvmTransactionRequestWithBody(server string, address string, params if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15701,7 +20650,7 @@ func NewSignEvmHashRequestWithBody(server string, address string, params *SignEv var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15721,7 +20670,7 @@ func NewSignEvmHashRequestWithBody(server string, address string, params *SignEv return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -15733,7 +20682,7 @@ func NewSignEvmHashRequestWithBody(server string, address string, params *SignEv if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15744,7 +20693,7 @@ func NewSignEvmHashRequestWithBody(server string, address string, params *SignEv if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15774,7 +20723,7 @@ func NewSignEvmMessageRequestWithBody(server string, address string, params *Sig var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15794,7 +20743,7 @@ func NewSignEvmMessageRequestWithBody(server string, address string, params *Sig return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -15806,7 +20755,7 @@ func NewSignEvmMessageRequestWithBody(server string, address string, params *Sig if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15817,7 +20766,7 @@ func NewSignEvmMessageRequestWithBody(server string, address string, params *Sig if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15847,7 +20796,7 @@ func NewSignEvmTransactionRequestWithBody(server string, address string, params var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15867,7 +20816,7 @@ func NewSignEvmTransactionRequestWithBody(server string, address string, params return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -15879,7 +20828,7 @@ func NewSignEvmTransactionRequestWithBody(server string, address string, params if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15890,7 +20839,7 @@ func NewSignEvmTransactionRequestWithBody(server string, address string, params if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15920,7 +20869,7 @@ func NewSignEvmTypedDataRequestWithBody(server string, address string, params *S var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15940,7 +20889,7 @@ func NewSignEvmTypedDataRequestWithBody(server string, address string, params *S return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -15952,7 +20901,7 @@ func NewSignEvmTypedDataRequestWithBody(server string, address string, params *S if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15963,7 +20912,7 @@ func NewSignEvmTypedDataRequestWithBody(server string, address string, params *S if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -15982,7 +20931,7 @@ func NewGetEvmEip7702DelegationOperationByIdRequest(server string, delegationOpe var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "delegationOperationId", runtime.ParamLocationPath, delegationOperationId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "delegationOperationId", delegationOperationId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) if err != nil { return nil, err } @@ -16002,7 +20951,7 @@ func NewGetEvmEip7702DelegationOperationByIdRequest(server string, delegationOpe return nil, err } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -16040,7 +20989,7 @@ func NewRequestEvmFaucetRequestWithBody(server string, contentType string, body return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -16070,19 +21019,21 @@ func NewListEvmSmartAccountsRequest(server string, params *ListEvmSmartAccountsP } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.PageSize != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "pageSize", runtime.ParamLocationQuery, *params.PageSize); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } @@ -16090,24 +21041,23 @@ func NewListEvmSmartAccountsRequest(server string, params *ListEvmSmartAccountsP if params.PageToken != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "pageToken", runtime.ParamLocationQuery, *params.PageToken); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageToken", *params.PageToken, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -16145,7 +21095,7 @@ func NewCreateEvmSmartAccountRequestWithBody(server string, params *CreateEvmSma return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -16157,7 +21107,7 @@ func NewCreateEvmSmartAccountRequestWithBody(server string, params *CreateEvmSma if params.XIdempotencyKey != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -16176,7 +21126,7 @@ func NewGetEvmSmartAccountByNameRequest(server string, name string) (*http.Reque var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "name", runtime.ParamLocationPath, name) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "name", name, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -16196,7 +21146,7 @@ func NewGetEvmSmartAccountByNameRequest(server string, name string) (*http.Reque return nil, err } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -16210,7 +21160,7 @@ func NewGetEvmSmartAccountRequest(server string, address string) (*http.Request, var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -16230,7 +21180,7 @@ func NewGetEvmSmartAccountRequest(server string, address string) (*http.Request, return nil, err } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -16255,7 +21205,7 @@ func NewUpdateEvmSmartAccountRequestWithBody(server string, address string, cont var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -16275,7 +21225,7 @@ func NewUpdateEvmSmartAccountRequestWithBody(server string, address string, cont return nil, err } - req, err := http.NewRequest("PUT", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPut, queryURL.String(), body) if err != nil { return nil, err } @@ -16302,7 +21252,7 @@ func NewCreateSpendPermissionRequestWithBody(server string, address string, para var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -16322,7 +21272,7 @@ func NewCreateSpendPermissionRequestWithBody(server string, address string, para return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -16334,7 +21284,7 @@ func NewCreateSpendPermissionRequestWithBody(server string, address string, para if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -16345,7 +21295,7 @@ func NewCreateSpendPermissionRequestWithBody(server string, address string, para if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -16364,7 +21314,7 @@ func NewListSpendPermissionsRequest(server string, address string, params *ListS var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -16385,19 +21335,21 @@ func NewListSpendPermissionsRequest(server string, address string, params *ListS } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.PageSize != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "pageSize", runtime.ParamLocationQuery, *params.PageSize); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } @@ -16405,24 +21357,23 @@ func NewListSpendPermissionsRequest(server string, address string, params *ListS if params.PageToken != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "pageToken", runtime.ParamLocationQuery, *params.PageToken); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageToken", *params.PageToken, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -16447,7 +21398,7 @@ func NewRevokeSpendPermissionRequestWithBody(server string, address string, para var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -16467,7 +21418,7 @@ func NewRevokeSpendPermissionRequestWithBody(server string, address string, para return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -16479,7 +21430,7 @@ func NewRevokeSpendPermissionRequestWithBody(server string, address string, para if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -16490,7 +21441,7 @@ func NewRevokeSpendPermissionRequestWithBody(server string, address string, para if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -16520,7 +21471,7 @@ func NewPrepareUserOperationRequestWithBody(server string, address string, conte var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -16540,7 +21491,7 @@ func NewPrepareUserOperationRequestWithBody(server string, address string, conte return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -16567,7 +21518,7 @@ func NewPrepareAndSendUserOperationRequestWithBody(server string, address string var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -16587,7 +21538,7 @@ func NewPrepareAndSendUserOperationRequestWithBody(server string, address string return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -16599,7 +21550,7 @@ func NewPrepareAndSendUserOperationRequestWithBody(server string, address string if params.XIdempotencyKey != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -16610,7 +21561,7 @@ func NewPrepareAndSendUserOperationRequestWithBody(server string, address string if params.XWalletAuth != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -16629,14 +21580,14 @@ func NewGetUserOperationRequest(server string, address string, userOpHash string var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } var pathParam1 string - pathParam1, err = runtime.StyleParamWithLocation("simple", false, "userOpHash", runtime.ParamLocationPath, userOpHash) + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "userOpHash", userOpHash, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -16656,7 +21607,7 @@ func NewGetUserOperationRequest(server string, address string, userOpHash string return nil, err } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -16681,14 +21632,14 @@ func NewSendUserOperationRequestWithBody(server string, address string, userOpHa var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } var pathParam1 string - pathParam1, err = runtime.StyleParamWithLocation("simple", false, "userOpHash", runtime.ParamLocationPath, userOpHash) + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "userOpHash", userOpHash, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -16708,7 +21659,7 @@ func NewSendUserOperationRequestWithBody(server string, address string, userOpHa return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -16748,7 +21699,7 @@ func NewCreateEvmSwapQuoteRequestWithBody(server string, params *CreateEvmSwapQu return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -16760,7 +21711,7 @@ func NewCreateEvmSwapQuoteRequestWithBody(server string, params *CreateEvmSwapQu if params.XIdempotencyKey != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -16793,79 +21744,61 @@ func NewGetEvmSwapPriceRequest(server string, params *GetEvmSwapPriceParams) (*h } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "network", runtime.ParamLocationQuery, params.Network); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "network", params.Network, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "toToken", runtime.ParamLocationQuery, params.ToToken); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "toToken", params.ToToken, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "fromToken", runtime.ParamLocationQuery, params.FromToken); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "fromToken", params.FromToken, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "fromAmount", runtime.ParamLocationQuery, params.FromAmount); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "fromAmount", params.FromAmount, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "taker", runtime.ParamLocationQuery, params.Taker); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "taker", params.Taker, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } if params.SignerAddress != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "signerAddress", runtime.ParamLocationQuery, *params.SignerAddress); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "signerAddress", *params.SignerAddress, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } @@ -16873,15 +21806,11 @@ func NewGetEvmSwapPriceRequest(server string, params *GetEvmSwapPriceParams) (*h if params.GasPrice != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "gasPrice", runtime.ParamLocationQuery, *params.GasPrice); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "gasPrice", *params.GasPrice, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } @@ -16889,24 +21818,23 @@ func NewGetEvmSwapPriceRequest(server string, params *GetEvmSwapPriceParams) (*h if params.SlippageBps != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "slippageBps", runtime.ParamLocationQuery, *params.SlippageBps); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "slippageBps", *params.SlippageBps, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -16920,14 +21848,14 @@ func NewListEvmTokenBalancesRequest(server string, network ListEvmTokenBalancesN var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "network", runtime.ParamLocationPath, network) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "network", network, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } var pathParam1 string - pathParam1, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -16948,19 +21876,21 @@ func NewListEvmTokenBalancesRequest(server string, network ListEvmTokenBalancesN } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.PageSize != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "pageSize", runtime.ParamLocationQuery, *params.PageSize); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } @@ -16968,24 +21898,23 @@ func NewListEvmTokenBalancesRequest(server string, network ListEvmTokenBalancesN if params.PageToken != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "pageToken", runtime.ParamLocationQuery, *params.PageToken); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageToken", *params.PageToken, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -17023,7 +21952,7 @@ func NewGetOnrampUserLimitsRequestWithBody(server string, contentType string, bo return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -17063,7 +21992,7 @@ func NewRequestLimitsUpgradeRequestWithBody(server string, contentType string, b return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -17103,7 +22032,7 @@ func NewCreateOnrampOrderRequestWithBody(server string, contentType string, body return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -17119,7 +22048,7 @@ func NewGetOnrampOrderByIdRequest(server string, orderId string) (*http.Request, var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "orderId", runtime.ParamLocationPath, orderId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "orderId", orderId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -17139,7 +22068,7 @@ func NewGetOnrampOrderByIdRequest(server string, orderId string) (*http.Request, return nil, err } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -17177,7 +22106,7 @@ func NewCreateOnrampSessionRequestWithBody(server string, contentType string, bo return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -17187,8 +22116,8 @@ func NewCreateOnrampSessionRequestWithBody(server string, contentType string, bo return req, nil } -// NewListPoliciesRequest generates requests for ListPolicies -func NewListPoliciesRequest(server string, params *ListPoliciesParams) (*http.Request, error) { +// NewListPaymentMethodsRequest generates requests for ListPaymentMethods +func NewListPaymentMethodsRequest(server string, params *ListPaymentMethodsParams) (*http.Request, error) { var err error serverURL, err := url.Parse(server) @@ -17196,7 +22125,7 @@ func NewListPoliciesRequest(server string, params *ListPoliciesParams) (*http.Re return nil, err } - operationPath := fmt.Sprintf("/v2/policy-engine/policies") + operationPath := fmt.Sprintf("/v2/payment-methods") if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -17207,19 +22136,21 @@ func NewListPoliciesRequest(server string, params *ListPoliciesParams) (*http.Re } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.PageSize != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "pageSize", runtime.ParamLocationQuery, *params.PageSize); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } @@ -17227,40 +22158,23 @@ func NewListPoliciesRequest(server string, params *ListPoliciesParams) (*http.Re if params.PageToken != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "pageToken", runtime.ParamLocationQuery, *params.PageToken); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageToken", *params.PageToken, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - if params.Scope != nil { - - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "scope", runtime.ParamLocationQuery, *params.Scope); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } - } - } - + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) } - - queryURL.RawQuery = queryValues.Encode() + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -17268,18 +22182,130 @@ func NewListPoliciesRequest(server string, params *ListPoliciesParams) (*http.Re return req, nil } -// NewCreatePolicyRequest calls the generic CreatePolicy builder with application/json body -func NewCreatePolicyRequest(server string, params *CreatePolicyParams, body CreatePolicyJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) +// NewGetPaymentMethodRequest generates requests for GetPaymentMethod +func NewGetPaymentMethodRequest(server string, paymentMethodId PaymentMethodId) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "paymentMethodId", paymentMethodId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } - bodyReader = bytes.NewReader(buf) - return NewCreatePolicyRequestWithBody(server, params, "application/json", bodyReader) -} -// NewCreatePolicyRequestWithBody generates requests for CreatePolicy with any type of body + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v2/payment-methods/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListPoliciesRequest generates requests for ListPolicies +func NewListPoliciesRequest(server string, params *ListPoliciesParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v2/policy-engine/policies") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageToken != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageToken", *params.PageToken, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Scope != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "scope", *params.Scope, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewCreatePolicyRequest calls the generic CreatePolicy builder with application/json body +func NewCreatePolicyRequest(server string, params *CreatePolicyParams, body CreatePolicyJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreatePolicyRequestWithBody(server, params, "application/json", bodyReader) +} + +// NewCreatePolicyRequestWithBody generates requests for CreatePolicy with any type of body func NewCreatePolicyRequestWithBody(server string, params *CreatePolicyParams, contentType string, body io.Reader) (*http.Request, error) { var err error @@ -17298,7 +22324,7 @@ func NewCreatePolicyRequestWithBody(server string, params *CreatePolicyParams, c return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -17310,7 +22336,7 @@ func NewCreatePolicyRequestWithBody(server string, params *CreatePolicyParams, c if params.XIdempotencyKey != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -17329,7 +22355,7 @@ func NewDeletePolicyRequest(server string, policyId string, params *DeletePolicy var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "policyId", runtime.ParamLocationPath, policyId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "policyId", policyId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -17349,7 +22375,7 @@ func NewDeletePolicyRequest(server string, policyId string, params *DeletePolicy return nil, err } - req, err := http.NewRequest("DELETE", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) if err != nil { return nil, err } @@ -17359,7 +22385,7 @@ func NewDeletePolicyRequest(server string, policyId string, params *DeletePolicy if params.XIdempotencyKey != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -17378,7 +22404,7 @@ func NewGetPolicyByIdRequest(server string, policyId string) (*http.Request, err var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "policyId", runtime.ParamLocationPath, policyId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "policyId", policyId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -17398,7 +22424,7 @@ func NewGetPolicyByIdRequest(server string, policyId string) (*http.Request, err return nil, err } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -17423,7 +22449,7 @@ func NewUpdatePolicyRequestWithBody(server string, policyId string, params *Upda var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "policyId", runtime.ParamLocationPath, policyId) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "policyId", policyId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -17443,7 +22469,7 @@ func NewUpdatePolicyRequestWithBody(server string, policyId string, params *Upda return nil, err } - req, err := http.NewRequest("PUT", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPut, queryURL.String(), body) if err != nil { return nil, err } @@ -17455,7 +22481,7 @@ func NewUpdatePolicyRequestWithBody(server string, policyId string, params *Upda if params.XIdempotencyKey != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -17488,19 +22514,21 @@ func NewListSolanaAccountsRequest(server string, params *ListSolanaAccountsParam } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.PageSize != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "pageSize", runtime.ParamLocationQuery, *params.PageSize); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } @@ -17508,24 +22536,23 @@ func NewListSolanaAccountsRequest(server string, params *ListSolanaAccountsParam if params.PageToken != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "pageToken", runtime.ParamLocationQuery, *params.PageToken); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageToken", *params.PageToken, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -17563,7 +22590,7 @@ func NewCreateSolanaAccountRequestWithBody(server string, params *CreateSolanaAc return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -17575,7 +22602,7 @@ func NewCreateSolanaAccountRequestWithBody(server string, params *CreateSolanaAc if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -17586,7 +22613,7 @@ func NewCreateSolanaAccountRequestWithBody(server string, params *CreateSolanaAc if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -17605,7 +22632,7 @@ func NewGetSolanaAccountByNameRequest(server string, name string) (*http.Request var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "name", runtime.ParamLocationPath, name) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "name", name, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -17625,7 +22652,7 @@ func NewGetSolanaAccountByNameRequest(server string, name string) (*http.Request return nil, err } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -17650,7 +22677,7 @@ func NewExportSolanaAccountByNameRequestWithBody(server string, name string, par var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "name", runtime.ParamLocationPath, name) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "name", name, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -17670,7 +22697,7 @@ func NewExportSolanaAccountByNameRequestWithBody(server string, name string, par return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -17682,7 +22709,7 @@ func NewExportSolanaAccountByNameRequestWithBody(server string, name string, par if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -17693,7 +22720,7 @@ func NewExportSolanaAccountByNameRequestWithBody(server string, name string, par if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -17736,7 +22763,7 @@ func NewImportSolanaAccountRequestWithBody(server string, params *ImportSolanaAc return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -17748,7 +22775,7 @@ func NewImportSolanaAccountRequestWithBody(server string, params *ImportSolanaAc if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -17759,7 +22786,7 @@ func NewImportSolanaAccountRequestWithBody(server string, params *ImportSolanaAc if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -17802,7 +22829,7 @@ func NewSendSolanaTransactionRequestWithBody(server string, params *SendSolanaTr return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -17814,7 +22841,7 @@ func NewSendSolanaTransactionRequestWithBody(server string, params *SendSolanaTr if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -17825,7 +22852,7 @@ func NewSendSolanaTransactionRequestWithBody(server string, params *SendSolanaTr if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -17844,7 +22871,7 @@ func NewGetSolanaAccountRequest(server string, address string) (*http.Request, e var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -17864,7 +22891,7 @@ func NewGetSolanaAccountRequest(server string, address string) (*http.Request, e return nil, err } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -17889,7 +22916,7 @@ func NewUpdateSolanaAccountRequestWithBody(server string, address string, params var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -17909,7 +22936,7 @@ func NewUpdateSolanaAccountRequestWithBody(server string, address string, params return nil, err } - req, err := http.NewRequest("PUT", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPut, queryURL.String(), body) if err != nil { return nil, err } @@ -17921,7 +22948,7 @@ func NewUpdateSolanaAccountRequestWithBody(server string, address string, params if params.XIdempotencyKey != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -17951,7 +22978,7 @@ func NewExportSolanaAccountRequestWithBody(server string, address string, params var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -17971,7 +22998,7 @@ func NewExportSolanaAccountRequestWithBody(server string, address string, params return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -17983,7 +23010,7 @@ func NewExportSolanaAccountRequestWithBody(server string, address string, params if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -17994,7 +23021,7 @@ func NewExportSolanaAccountRequestWithBody(server string, address string, params if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -18024,7 +23051,7 @@ func NewSignSolanaMessageRequestWithBody(server string, address string, params * var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -18044,7 +23071,7 @@ func NewSignSolanaMessageRequestWithBody(server string, address string, params * return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -18056,7 +23083,7 @@ func NewSignSolanaMessageRequestWithBody(server string, address string, params * if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -18067,7 +23094,7 @@ func NewSignSolanaMessageRequestWithBody(server string, address string, params * if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -18097,7 +23124,7 @@ func NewSignSolanaTransactionRequestWithBody(server string, address string, para var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -18117,7 +23144,7 @@ func NewSignSolanaTransactionRequestWithBody(server string, address string, para return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -18129,7 +23156,7 @@ func NewSignSolanaTransactionRequestWithBody(server string, address string, para if params.XWalletAuth != nil { var headerParam0 string - headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Wallet-Auth", runtime.ParamLocationHeader, *params.XWalletAuth) + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Wallet-Auth", *params.XWalletAuth, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -18140,7 +23167,7 @@ func NewSignSolanaTransactionRequestWithBody(server string, address string, para if params.XIdempotencyKey != nil { var headerParam1 string - headerParam1, err = runtime.StyleParamWithLocation("simple", false, "X-Idempotency-Key", runtime.ParamLocationHeader, *params.XIdempotencyKey) + headerParam1, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -18183,7 +23210,7 @@ func NewRequestSolanaFaucetRequestWithBody(server string, contentType string, bo return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -18199,14 +23226,14 @@ func NewListSolanaTokenBalancesRequest(server string, network ListSolanaTokenBal var pathParam0 string - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "network", runtime.ParamLocationPath, network) + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "network", network, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } var pathParam1 string - pathParam1, err = runtime.StyleParamWithLocation("simple", false, "address", runtime.ParamLocationPath, address) + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "address", address, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) if err != nil { return nil, err } @@ -18227,19 +23254,21 @@ func NewListSolanaTokenBalancesRequest(server string, network ListSolanaTokenBal } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string if params.PageSize != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "pageSize", runtime.ParamLocationQuery, *params.PageSize); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } @@ -18247,73 +23276,32 @@ func NewListSolanaTokenBalancesRequest(server string, network ListSolanaTokenBal if params.PageToken != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "pageToken", runtime.ParamLocationQuery, *params.PageToken); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageToken", *params.PageToken, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewPostX402DiscoveryMcpRequest calls the generic PostX402DiscoveryMcp builder with application/json body -func NewPostX402DiscoveryMcpRequest(server string, body PostX402DiscoveryMcpJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewPostX402DiscoveryMcpRequestWithBody(server, "application/json", bodyReader) -} - -// NewPostX402DiscoveryMcpRequestWithBody generates requests for PostX402DiscoveryMcp with any type of body -func NewPostX402DiscoveryMcpRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/v2/x402/discovery/mcp") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } - req.Header.Add("Content-Type", contentType) - return req, nil } -// NewListX402DiscoveryMerchantRequest generates requests for ListX402DiscoveryMerchant -func NewListX402DiscoveryMerchantRequest(server string, params *ListX402DiscoveryMerchantParams) (*http.Request, error) { +// NewListTransfersRequest generates requests for ListTransfers +func NewListTransfersRequest(server string, params *ListTransfersParams) (*http.Request, error) { var err error serverURL, err := url.Parse(server) @@ -18321,7 +23309,7 @@ func NewListX402DiscoveryMerchantRequest(server string, params *ListX402Discover return nil, err } - operationPath := fmt.Sprintf("/v2/x402/discovery/merchant") + operationPath := fmt.Sprintf("/v2/transfers") if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -18332,314 +23320,213 @@ func NewListX402DiscoveryMerchantRequest(server string, params *ListX402Discover } if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "payTo", runtime.ParamLocationQuery, params.PayTo); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) + if params.Status != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "status", *params.Status, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } + } - if params.Limit != nil { + if params.AccountId != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "limit", runtime.ParamLocationQuery, *params.Limit); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "accountId", *params.AccountId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - if params.Offset != nil { + if params.SourceAccountId != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "offset", runtime.ParamLocationQuery, *params.Offset); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "sourceAccountId", *params.SourceAccountId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewListX402DiscoveryResourcesRequest generates requests for ListX402DiscoveryResources -func NewListX402DiscoveryResourcesRequest(server string, params *ListX402DiscoveryResourcesParams) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/v2/x402/discovery/resources") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - if params != nil { - queryValues := queryURL.Query() - - if params.Type != nil { + if params.TargetAccountId != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "type", runtime.ParamLocationQuery, *params.Type); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "targetAccountId", *params.TargetAccountId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - if params.Limit != nil { + if params.CreatedAfter != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "limit", runtime.ParamLocationQuery, *params.Limit); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "createdAfter", *params.CreatedAfter, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - if params.Offset != nil { + if params.CreatedBefore != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "offset", runtime.ParamLocationQuery, *params.Offset); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "createdBefore", *params.CreatedBefore, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewSearchX402ResourcesRequest generates requests for SearchX402Resources -func NewSearchX402ResourcesRequest(server string, params *SearchX402ResourcesParams) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/v2/x402/discovery/search") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } + if params.UpdatedAfter != nil { - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "updatedAfter", *params.UpdatedAfter, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } - if params != nil { - queryValues := queryURL.Query() + } - if params.Query != nil { + if params.UpdatedBefore != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "query", runtime.ParamLocationQuery, *params.Query); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "updatedBefore", *params.UpdatedBefore, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - if params.Network != nil { + if params.SourceAsset != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "network", runtime.ParamLocationQuery, *params.Network); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "sourceAsset", *params.SourceAsset, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - if params.Asset != nil { + if params.TargetAsset != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "asset", runtime.ParamLocationQuery, *params.Asset); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "targetAsset", *params.TargetAsset, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - if params.Scheme != nil { + if params.SourceAddress != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "scheme", runtime.ParamLocationQuery, *params.Scheme); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "sourceAddress", *params.SourceAddress, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - if params.PayTo != nil { + if params.TargetAddress != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "payTo", runtime.ParamLocationQuery, *params.PayTo); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "targetAddress", *params.TargetAddress, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - if params.UrlSubstring != nil { + if params.TargetEmail != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "urlSubstring", runtime.ParamLocationQuery, *params.UrlSubstring); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "targetEmail", *params.TargetEmail, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "email"}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - if params.MaxUsdPrice != nil { + if params.TransferId != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "maxUsdPrice", runtime.ParamLocationQuery, *params.MaxUsdPrice); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "transferId", *params.TransferId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - if params.Extensions != nil { + if params.PageSize != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "extensions", runtime.ParamLocationQuery, *params.Extensions); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - if params.Limit != nil { + if params.PageToken != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "limit", runtime.ParamLocationQuery, *params.Limit); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "pageToken", *params.PageToken, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { return nil, err } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) } } } - queryURL.RawQuery = queryValues.Encode() + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -18647,19 +23534,19 @@ func NewSearchX402ResourcesRequest(server string, params *SearchX402ResourcesPar return req, nil } -// NewSettleX402PaymentRequest calls the generic SettleX402Payment builder with application/json body -func NewSettleX402PaymentRequest(server string, body SettleX402PaymentJSONRequestBody) (*http.Request, error) { +// NewCreateTransferRequest calls the generic CreateTransfer builder with application/json body +func NewCreateTransferRequest(server string, params *CreateTransferParams, body CreateTransferJSONRequestBody) (*http.Request, error) { var bodyReader io.Reader buf, err := json.Marshal(body) if err != nil { return nil, err } bodyReader = bytes.NewReader(buf) - return NewSettleX402PaymentRequestWithBody(server, "application/json", bodyReader) + return NewCreateTransferRequestWithBody(server, params, "application/json", bodyReader) } -// NewSettleX402PaymentRequestWithBody generates requests for SettleX402Payment with any type of body -func NewSettleX402PaymentRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { +// NewCreateTransferRequestWithBody generates requests for CreateTransfer with any type of body +func NewCreateTransferRequestWithBody(server string, params *CreateTransferParams, contentType string, body io.Reader) (*http.Request, error) { var err error serverURL, err := url.Parse(server) @@ -18667,7 +23554,7 @@ func NewSettleX402PaymentRequestWithBody(server string, contentType string, body return nil, err } - operationPath := fmt.Sprintf("/v2/x402/settle") + operationPath := fmt.Sprintf("/v2/transfers") if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -18677,19 +23564,561 @@ func NewSettleX402PaymentRequestWithBody(server string, contentType string, body return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } req.Header.Add("Content-Type", contentType) - return req, nil -} + if params != nil { -// NewSupportedX402PaymentKindsRequest generates requests for SupportedX402PaymentKinds -func NewSupportedX402PaymentKindsRequest(server string) (*http.Request, error) { - var err error + if params.XIdempotencyKey != nil { + var headerParam0 string + + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + req.Header.Set("X-Idempotency-Key", headerParam0) + } + + } + + return req, nil +} + +// NewGetTransferByIdRequest generates requests for GetTransferById +func NewGetTransferByIdRequest(server string, transferId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "transferId", transferId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v2/transfers/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewExecuteFundTransferRequest generates requests for ExecuteFundTransfer +func NewExecuteFundTransferRequest(server string, transferId string, params *ExecuteFundTransferParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "transferId", transferId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v2/transfers/%s/execute", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil) + if err != nil { + return nil, err + } + + if params != nil { + + if params.XIdempotencyKey != nil { + var headerParam0 string + + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + req.Header.Set("X-Idempotency-Key", headerParam0) + } + + } + + return req, nil +} + +// NewSubmitDepositTravelRuleRequest calls the generic SubmitDepositTravelRule builder with application/json body +func NewSubmitDepositTravelRuleRequest(server string, transferId string, params *SubmitDepositTravelRuleParams, body SubmitDepositTravelRuleJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewSubmitDepositTravelRuleRequestWithBody(server, transferId, params, "application/json", bodyReader) +} + +// NewSubmitDepositTravelRuleRequestWithBody generates requests for SubmitDepositTravelRule with any type of body +func NewSubmitDepositTravelRuleRequestWithBody(server string, transferId string, params *SubmitDepositTravelRuleParams, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "transferId", transferId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v2/transfers/%s/travel-rule", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + if params != nil { + + if params.XIdempotencyKey != nil { + var headerParam0 string + + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Idempotency-Key", *params.XIdempotencyKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + req.Header.Set("X-Idempotency-Key", headerParam0) + } + + } + + return req, nil +} + +// NewPostX402DiscoveryMcpRequest calls the generic PostX402DiscoveryMcp builder with application/json body +func NewPostX402DiscoveryMcpRequest(server string, body PostX402DiscoveryMcpJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewPostX402DiscoveryMcpRequestWithBody(server, "application/json", bodyReader) +} + +// NewPostX402DiscoveryMcpRequestWithBody generates requests for PostX402DiscoveryMcp with any type of body +func NewPostX402DiscoveryMcpRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v2/x402/discovery/mcp") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewListX402DiscoveryMerchantRequest generates requests for ListX402DiscoveryMerchant +func NewListX402DiscoveryMerchantRequest(server string, params *ListX402DiscoveryMerchantParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v2/x402/discovery/merchant") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "payTo", params.PayTo, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "limit", *params.Limit, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Offset != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "offset", *params.Offset, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListX402DiscoveryResourcesRequest generates requests for ListX402DiscoveryResources +func NewListX402DiscoveryResourcesRequest(server string, params *ListX402DiscoveryResourcesParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v2/x402/discovery/resources") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Type != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "type", *params.Type, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "limit", *params.Limit, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Offset != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "offset", *params.Offset, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewSearchX402ResourcesRequest generates requests for SearchX402Resources +func NewSearchX402ResourcesRequest(server string, params *SearchX402ResourcesParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v2/x402/discovery/search") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Query != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "query", *params.Query, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Network != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "network", *params.Network, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Asset != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "asset", *params.Asset, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Scheme != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "scheme", *params.Scheme, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PayTo != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "payTo", *params.PayTo, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.UrlSubstring != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "urlSubstring", *params.UrlSubstring, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.MaxUsdPrice != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "maxUsdPrice", *params.MaxUsdPrice, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Extensions != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "extensions", *params.Extensions, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "limit", *params.Limit, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewSettleX402PaymentRequest calls the generic SettleX402Payment builder with application/json body +func NewSettleX402PaymentRequest(server string, body SettleX402PaymentJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewSettleX402PaymentRequestWithBody(server, "application/json", bodyReader) +} + +// NewSettleX402PaymentRequestWithBody generates requests for SettleX402Payment with any type of body +func NewSettleX402PaymentRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v2/x402/settle") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewSupportedX402PaymentKindsRequest generates requests for SupportedX402PaymentKinds +func NewSupportedX402PaymentKindsRequest(server string) (*http.Request, error) { + var err error serverURL, err := url.Parse(server) if err != nil { @@ -18706,7 +24135,7 @@ func NewSupportedX402PaymentKindsRequest(server string) (*http.Request, error) { return nil, err } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) if err != nil { return nil, err } @@ -18744,7 +24173,7 @@ func NewVerifyX402PaymentRequestWithBody(server string, contentType string, body return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) if err != nil { return nil, err } @@ -18797,6 +24226,23 @@ func WithBaseURL(baseURL string) ClientOption { // ClientWithResponsesInterface is the interface specification for the client with responses above. type ClientWithResponsesInterface interface { + // ListFoundationAccountsWithResponse request + ListFoundationAccountsWithResponse(ctx context.Context, params *ListFoundationAccountsParams, reqEditors ...RequestEditorFn) (*ListFoundationAccountsResponse, error) + + // CreateFoundationAccountWithBodyWithResponse request with any body + CreateFoundationAccountWithBodyWithResponse(ctx context.Context, params *CreateFoundationAccountParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateFoundationAccountResponse, error) + + CreateFoundationAccountWithResponse(ctx context.Context, params *CreateFoundationAccountParams, body CreateFoundationAccountJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateFoundationAccountResponse, error) + + // GetFoundationAccountByIdWithResponse request + GetFoundationAccountByIdWithResponse(ctx context.Context, accountId AccountId, reqEditors ...RequestEditorFn) (*GetFoundationAccountByIdResponse, error) + + // ListBalancesWithResponse request + ListBalancesWithResponse(ctx context.Context, accountId AccountId, params *ListBalancesParams, reqEditors ...RequestEditorFn) (*ListBalancesResponse, error) + + // GetBalanceByAssetWithResponse request + GetBalanceByAssetWithResponse(ctx context.Context, accountId AccountId, asset Asset, reqEditors ...RequestEditorFn) (*GetBalanceByAssetResponse, error) + // ListDataTokenBalancesWithResponse request ListDataTokenBalancesWithResponse(ctx context.Context, network ListEvmTokenBalancesNetwork, address string, params *ListDataTokenBalancesParams, reqEditors ...RequestEditorFn) (*ListDataTokenBalancesResponse, error) @@ -18836,6 +24282,17 @@ type ClientWithResponsesInterface interface { // ListWebhookSubscriptionEventsWithResponse request ListWebhookSubscriptionEventsWithResponse(ctx context.Context, subscriptionId openapi_types.UUID, params *ListWebhookSubscriptionEventsParams, reqEditors ...RequestEditorFn) (*ListWebhookSubscriptionEventsResponse, error) + // ListDepositDestinationsWithResponse request + ListDepositDestinationsWithResponse(ctx context.Context, params *ListDepositDestinationsParams, reqEditors ...RequestEditorFn) (*ListDepositDestinationsResponse, error) + + // CreateDepositDestinationWithBodyWithResponse request with any body + CreateDepositDestinationWithBodyWithResponse(ctx context.Context, params *CreateDepositDestinationParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateDepositDestinationResponse, error) + + CreateDepositDestinationWithResponse(ctx context.Context, params *CreateDepositDestinationParams, body CreateDepositDestinationJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateDepositDestinationResponse, error) + + // GetDepositDestinationByIdWithResponse request + GetDepositDestinationByIdWithResponse(ctx context.Context, depositDestinationId DepositDestinationId, reqEditors ...RequestEditorFn) (*GetDepositDestinationByIdResponse, error) + // RevokeDelegationForEndUserAccountWithBodyWithResponse request with any body RevokeDelegationForEndUserAccountWithBodyWithResponse(ctx context.Context, userId string, address BlockchainAddress, params *RevokeDelegationForEndUserAccountParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*RevokeDelegationForEndUserAccountResponse, error) @@ -19107,6 +24564,12 @@ type ClientWithResponsesInterface interface { CreateOnrampSessionWithResponse(ctx context.Context, body CreateOnrampSessionJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateOnrampSessionResponse, error) + // ListPaymentMethodsWithResponse request + ListPaymentMethodsWithResponse(ctx context.Context, params *ListPaymentMethodsParams, reqEditors ...RequestEditorFn) (*ListPaymentMethodsResponse, error) + + // GetPaymentMethodWithResponse request + GetPaymentMethodWithResponse(ctx context.Context, paymentMethodId PaymentMethodId, reqEditors ...RequestEditorFn) (*GetPaymentMethodResponse, error) + // ListPoliciesWithResponse request ListPoliciesWithResponse(ctx context.Context, params *ListPoliciesParams, reqEditors ...RequestEditorFn) (*ListPoliciesResponse, error) @@ -19180,35 +24643,232 @@ type ClientWithResponsesInterface interface { RequestSolanaFaucetWithResponse(ctx context.Context, body RequestSolanaFaucetJSONRequestBody, reqEditors ...RequestEditorFn) (*RequestSolanaFaucetResponse, error) - // ListSolanaTokenBalancesWithResponse request - ListSolanaTokenBalancesWithResponse(ctx context.Context, network ListSolanaTokenBalancesNetwork, address string, params *ListSolanaTokenBalancesParams, reqEditors ...RequestEditorFn) (*ListSolanaTokenBalancesResponse, error) + // ListSolanaTokenBalancesWithResponse request + ListSolanaTokenBalancesWithResponse(ctx context.Context, network ListSolanaTokenBalancesNetwork, address string, params *ListSolanaTokenBalancesParams, reqEditors ...RequestEditorFn) (*ListSolanaTokenBalancesResponse, error) + + // ListTransfersWithResponse request + ListTransfersWithResponse(ctx context.Context, params *ListTransfersParams, reqEditors ...RequestEditorFn) (*ListTransfersResponse, error) + + // CreateTransferWithBodyWithResponse request with any body + CreateTransferWithBodyWithResponse(ctx context.Context, params *CreateTransferParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateTransferResponse, error) + + CreateTransferWithResponse(ctx context.Context, params *CreateTransferParams, body CreateTransferJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateTransferResponse, error) + + // GetTransferByIdWithResponse request + GetTransferByIdWithResponse(ctx context.Context, transferId string, reqEditors ...RequestEditorFn) (*GetTransferByIdResponse, error) + + // ExecuteFundTransferWithResponse request + ExecuteFundTransferWithResponse(ctx context.Context, transferId string, params *ExecuteFundTransferParams, reqEditors ...RequestEditorFn) (*ExecuteFundTransferResponse, error) + + // SubmitDepositTravelRuleWithBodyWithResponse request with any body + SubmitDepositTravelRuleWithBodyWithResponse(ctx context.Context, transferId string, params *SubmitDepositTravelRuleParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*SubmitDepositTravelRuleResponse, error) + + SubmitDepositTravelRuleWithResponse(ctx context.Context, transferId string, params *SubmitDepositTravelRuleParams, body SubmitDepositTravelRuleJSONRequestBody, reqEditors ...RequestEditorFn) (*SubmitDepositTravelRuleResponse, error) + + // PostX402DiscoveryMcpWithBodyWithResponse request with any body + PostX402DiscoveryMcpWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostX402DiscoveryMcpResponse, error) + + PostX402DiscoveryMcpWithResponse(ctx context.Context, body PostX402DiscoveryMcpJSONRequestBody, reqEditors ...RequestEditorFn) (*PostX402DiscoveryMcpResponse, error) + + // ListX402DiscoveryMerchantWithResponse request + ListX402DiscoveryMerchantWithResponse(ctx context.Context, params *ListX402DiscoveryMerchantParams, reqEditors ...RequestEditorFn) (*ListX402DiscoveryMerchantResponse, error) + + // ListX402DiscoveryResourcesWithResponse request + ListX402DiscoveryResourcesWithResponse(ctx context.Context, params *ListX402DiscoveryResourcesParams, reqEditors ...RequestEditorFn) (*ListX402DiscoveryResourcesResponse, error) + + // SearchX402ResourcesWithResponse request + SearchX402ResourcesWithResponse(ctx context.Context, params *SearchX402ResourcesParams, reqEditors ...RequestEditorFn) (*SearchX402ResourcesResponse, error) + + // SettleX402PaymentWithBodyWithResponse request with any body + SettleX402PaymentWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*SettleX402PaymentResponse, error) + + SettleX402PaymentWithResponse(ctx context.Context, body SettleX402PaymentJSONRequestBody, reqEditors ...RequestEditorFn) (*SettleX402PaymentResponse, error) + + // SupportedX402PaymentKindsWithResponse request + SupportedX402PaymentKindsWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*SupportedX402PaymentKindsResponse, error) + + // VerifyX402PaymentWithBodyWithResponse request with any body + VerifyX402PaymentWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*VerifyX402PaymentResponse, error) + + VerifyX402PaymentWithResponse(ctx context.Context, body VerifyX402PaymentJSONRequestBody, reqEditors ...RequestEditorFn) (*VerifyX402PaymentResponse, error) +} + +type ListFoundationAccountsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *struct { + // Accounts The list of accounts. + Accounts []Account `json:"accounts"` + + // NextPageToken The token for the next page of items, if any. + NextPageToken *string `json:"nextPageToken,omitempty"` + } + JSON400 *Error +} + +// Status returns HTTPResponse.Status +func (r ListFoundationAccountsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListFoundationAccountsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListFoundationAccountsResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type CreateFoundationAccountResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Account + JSON400 *Error + JSON422 *IdempotencyError + JSON503 *EndpointUnavailableError +} + +// Status returns HTTPResponse.Status +func (r CreateFoundationAccountResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateFoundationAccountResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r CreateFoundationAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type GetFoundationAccountByIdResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Account + JSON400 *Error + JSON404 *Error +} + +// Status returns HTTPResponse.Status +func (r GetFoundationAccountByIdResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetFoundationAccountByIdResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} - // PostX402DiscoveryMcpWithBodyWithResponse request with any body - PostX402DiscoveryMcpWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostX402DiscoveryMcpResponse, error) +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetFoundationAccountByIdResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} - PostX402DiscoveryMcpWithResponse(ctx context.Context, body PostX402DiscoveryMcpJSONRequestBody, reqEditors ...RequestEditorFn) (*PostX402DiscoveryMcpResponse, error) +type ListBalancesResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *struct { + // Balances The list of balances. + Balances []Balance `json:"balances"` - // ListX402DiscoveryMerchantWithResponse request - ListX402DiscoveryMerchantWithResponse(ctx context.Context, params *ListX402DiscoveryMerchantParams, reqEditors ...RequestEditorFn) (*ListX402DiscoveryMerchantResponse, error) + // NextPageToken The token for the next page of items, if any. + NextPageToken *string `json:"nextPageToken,omitempty"` + } + JSON400 *Error + JSON401 *Error + JSON404 *Error + JSON500 *Error + JSON503 *EndpointUnavailableError +} - // ListX402DiscoveryResourcesWithResponse request - ListX402DiscoveryResourcesWithResponse(ctx context.Context, params *ListX402DiscoveryResourcesParams, reqEditors ...RequestEditorFn) (*ListX402DiscoveryResourcesResponse, error) +// Status returns HTTPResponse.Status +func (r ListBalancesResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} - // SearchX402ResourcesWithResponse request - SearchX402ResourcesWithResponse(ctx context.Context, params *SearchX402ResourcesParams, reqEditors ...RequestEditorFn) (*SearchX402ResourcesResponse, error) +// StatusCode returns HTTPResponse.StatusCode +func (r ListBalancesResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} - // SettleX402PaymentWithBodyWithResponse request with any body - SettleX402PaymentWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*SettleX402PaymentResponse, error) +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListBalancesResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} - SettleX402PaymentWithResponse(ctx context.Context, body SettleX402PaymentJSONRequestBody, reqEditors ...RequestEditorFn) (*SettleX402PaymentResponse, error) +type GetBalanceByAssetResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Balance + JSON400 *Error + JSON401 *Error + JSON404 *Error + JSON500 *Error + JSON503 *EndpointUnavailableError +} - // SupportedX402PaymentKindsWithResponse request - SupportedX402PaymentKindsWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*SupportedX402PaymentKindsResponse, error) +// Status returns HTTPResponse.Status +func (r GetBalanceByAssetResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} - // VerifyX402PaymentWithBodyWithResponse request with any body - VerifyX402PaymentWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*VerifyX402PaymentResponse, error) +// StatusCode returns HTTPResponse.StatusCode +func (r GetBalanceByAssetResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} - VerifyX402PaymentWithResponse(ctx context.Context, body VerifyX402PaymentJSONRequestBody, reqEditors ...RequestEditorFn) (*VerifyX402PaymentResponse, error) +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetBalanceByAssetResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" } type ListDataTokenBalancesResponse struct { @@ -19244,6 +24904,14 @@ func (r ListDataTokenBalancesResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListDataTokenBalancesResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ListTokensForAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -19270,6 +24938,14 @@ func (r ListTokensForAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListTokensForAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type GetSQLGrammarResponse struct { Body []byte HTTPResponse *http.Response @@ -19296,6 +24972,14 @@ func (r GetSQLGrammarResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetSQLGrammarResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type RunSQLQueryResponse struct { Body []byte HTTPResponse *http.Response @@ -19326,6 +25010,14 @@ func (r RunSQLQueryResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r RunSQLQueryResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type GetSQLSchemaResponse struct { Body []byte HTTPResponse *http.Response @@ -19350,6 +25042,14 @@ func (r GetSQLSchemaResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetSQLSchemaResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ListWebhookSubscriptionsResponse struct { Body []byte HTTPResponse *http.Response @@ -19376,6 +25076,14 @@ func (r ListWebhookSubscriptionsResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListWebhookSubscriptionsResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type CreateWebhookSubscriptionResponse struct { Body []byte HTTPResponse *http.Response @@ -19402,6 +25110,14 @@ func (r CreateWebhookSubscriptionResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r CreateWebhookSubscriptionResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type DeleteWebhookSubscriptionResponse struct { Body []byte HTTPResponse *http.Response @@ -19427,6 +25143,14 @@ func (r DeleteWebhookSubscriptionResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r DeleteWebhookSubscriptionResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type GetWebhookSubscriptionResponse struct { Body []byte HTTPResponse *http.Response @@ -19453,6 +25177,14 @@ func (r GetWebhookSubscriptionResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetWebhookSubscriptionResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type UpdateWebhookSubscriptionResponse struct { Body []byte HTTPResponse *http.Response @@ -19480,6 +25212,14 @@ func (r UpdateWebhookSubscriptionResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r UpdateWebhookSubscriptionResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ListWebhookSubscriptionEventsResponse struct { Body []byte HTTPResponse *http.Response @@ -19507,6 +25247,123 @@ func (r ListWebhookSubscriptionEventsResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListWebhookSubscriptionEventsResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type ListDepositDestinationsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *struct { + // DepositDestinations The list of deposit destinations. + DepositDestinations []DepositDestination `json:"depositDestinations"` + + // NextPageToken The token for the next page of items, if any. + NextPageToken *string `json:"nextPageToken,omitempty"` + } + JSON400 *Error + JSON401 *Error + JSON500 *Error +} + +// Status returns HTTPResponse.Status +func (r ListDepositDestinationsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListDepositDestinationsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListDepositDestinationsResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type CreateDepositDestinationResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *DepositDestination + JSON400 *Error + JSON401 *Error + JSON404 *Error + JSON422 *IdempotencyError + JSON500 *Error + JSON503 *EndpointUnavailableError +} + +// Status returns HTTPResponse.Status +func (r CreateDepositDestinationResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateDepositDestinationResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r CreateDepositDestinationResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type GetDepositDestinationByIdResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DepositDestination + JSON400 *Error + JSON401 *Error + JSON404 *Error + JSON500 *Error +} + +// Status returns HTTPResponse.Status +func (r GetDepositDestinationByIdResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetDepositDestinationByIdResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetDepositDestinationByIdResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type RevokeDelegationForEndUserAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -19533,6 +25390,14 @@ func (r RevokeDelegationForEndUserAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r RevokeDelegationForEndUserAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type GetDelegationForEndUserAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -19563,6 +25428,14 @@ func (r GetDelegationForEndUserAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetDelegationForEndUserAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type CreateDelegationForEndUserAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -19598,6 +25471,14 @@ func (r CreateDelegationForEndUserAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r CreateDelegationForEndUserAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type RevokeDelegationForEndUserResponse struct { Body []byte HTTPResponse *http.Response @@ -19624,6 +25505,14 @@ func (r RevokeDelegationForEndUserResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r RevokeDelegationForEndUserResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type GetDelegationForEndUserResponse struct { Body []byte HTTPResponse *http.Response @@ -19654,6 +25543,14 @@ func (r GetDelegationForEndUserResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetDelegationForEndUserResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type CreateEvmEip7702DelegationWithEndUserAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -19664,6 +25561,7 @@ type CreateEvmEip7702DelegationWithEndUserAccountResponse struct { JSON400 *Error JSON401 *UnauthorizedError JSON402 *PaymentMethodRequiredError + JSON403 *DelegationForbiddenError JSON404 *Error JSON409 *Error JSON422 *IdempotencyError @@ -19689,6 +25587,14 @@ func (r CreateEvmEip7702DelegationWithEndUserAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r CreateEvmEip7702DelegationWithEndUserAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type SendEvmTransactionWithEndUserAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -19699,7 +25605,7 @@ type SendEvmTransactionWithEndUserAccountResponse struct { JSON400 *Error JSON401 *UnauthorizedError JSON402 *PaymentMethodRequiredError - JSON403 *Error + JSON403 *DelegationForbiddenError JSON404 *Error JSON409 *AlreadyExistsError JSON422 *IdempotencyError @@ -19724,6 +25630,14 @@ func (r SendEvmTransactionWithEndUserAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SendEvmTransactionWithEndUserAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type SignEvmMessageWithEndUserAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -19733,6 +25647,7 @@ type SignEvmMessageWithEndUserAccountResponse struct { } JSON401 *UnauthorizedError JSON402 *PaymentMethodRequiredError + JSON403 *DelegationForbiddenError JSON404 *Error JSON409 *AlreadyExistsError JSON422 *IdempotencyError @@ -19757,6 +25672,14 @@ func (r SignEvmMessageWithEndUserAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SignEvmMessageWithEndUserAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type SignEvmTransactionWithEndUserAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -19767,7 +25690,7 @@ type SignEvmTransactionWithEndUserAccountResponse struct { JSON400 *Error JSON401 *UnauthorizedError JSON402 *PaymentMethodRequiredError - JSON403 *Error + JSON403 *DelegationForbiddenError JSON404 *Error JSON409 *AlreadyExistsError JSON422 *IdempotencyError @@ -19792,6 +25715,14 @@ func (r SignEvmTransactionWithEndUserAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SignEvmTransactionWithEndUserAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type SignEvmTypedDataWithEndUserAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -19802,6 +25733,7 @@ type SignEvmTypedDataWithEndUserAccountResponse struct { JSON400 *Error JSON401 *UnauthorizedError JSON402 *PaymentMethodRequiredError + JSON403 *DelegationForbiddenError JSON404 *Error JSON422 *IdempotencyError JSON500 *InternalServerError @@ -19825,6 +25757,14 @@ func (r SignEvmTypedDataWithEndUserAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SignEvmTypedDataWithEndUserAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type SendUserOperationWithEndUserAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -19832,7 +25772,7 @@ type SendUserOperationWithEndUserAccountResponse struct { JSON400 *Error JSON401 *UnauthorizedError JSON402 *PaymentMethodRequiredError - JSON403 *Error + JSON403 *DelegationForbiddenError JSON404 *Error JSON429 *Error JSON500 *InternalServerError @@ -19856,19 +25796,28 @@ func (r SendUserOperationWithEndUserAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SendUserOperationWithEndUserAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type SendEvmAssetWithEndUserAccountResponse struct { Body []byte HTTPResponse *http.Response JSON200 *struct { // TransactionHash The hash of the transaction, as a 0x-prefixed hex string. Populated for EOA accounts. Null for Smart Accounts (use userOpHash instead). - TransactionHash *string `json:"transactionHash"` + TransactionHash *string `json:"transactionHash,omitempty"` // UserOpHash The hash of the user operation, as a 0x-prefixed hex string. Populated for Smart Accounts. Null for EOA accounts (use transactionHash instead). - UserOpHash *string `json:"userOpHash"` + UserOpHash *string `json:"userOpHash,omitempty"` } JSON400 *Error JSON401 *UnauthorizedError JSON402 *PaymentMethodRequiredError + JSON403 *DelegationForbiddenError JSON404 *Error JSON422 *IdempotencyError JSON500 *InternalServerError @@ -19892,6 +25841,14 @@ func (r SendEvmAssetWithEndUserAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SendEvmAssetWithEndUserAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type SendSolanaTransactionWithEndUserAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -19902,7 +25859,7 @@ type SendSolanaTransactionWithEndUserAccountResponse struct { JSON400 *Error JSON401 *UnauthorizedError JSON402 *PaymentMethodRequiredError - JSON403 *Error + JSON403 *DelegationForbiddenError JSON404 *Error JSON422 *IdempotencyError JSON500 *InternalServerError @@ -19921,9 +25878,17 @@ func (r SendSolanaTransactionWithEndUserAccountResponse) Status() string { // StatusCode returns HTTPResponse.StatusCode func (r SendSolanaTransactionWithEndUserAccountResponse) StatusCode() int { if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SendSolanaTransactionWithEndUserAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") } - return 0 + return "" } type SignSolanaMessageWithEndUserAccountResponse struct { @@ -19936,6 +25901,7 @@ type SignSolanaMessageWithEndUserAccountResponse struct { JSON400 *Error JSON401 *UnauthorizedError JSON402 *PaymentMethodRequiredError + JSON403 *DelegationForbiddenError JSON404 *Error JSON409 *AlreadyExistsError JSON422 *IdempotencyError @@ -19960,6 +25926,14 @@ func (r SignSolanaMessageWithEndUserAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SignSolanaMessageWithEndUserAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type SignSolanaTransactionWithEndUserAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -19970,7 +25944,7 @@ type SignSolanaTransactionWithEndUserAccountResponse struct { JSON400 *Error JSON401 *UnauthorizedError JSON402 *PaymentMethodRequiredError - JSON403 *Error + JSON403 *DelegationForbiddenError JSON404 *Error JSON409 *AlreadyExistsError JSON422 *IdempotencyError @@ -19995,6 +25969,14 @@ func (r SignSolanaTransactionWithEndUserAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SignSolanaTransactionWithEndUserAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type SendSolanaAssetWithEndUserAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -20005,6 +25987,7 @@ type SendSolanaAssetWithEndUserAccountResponse struct { JSON400 *Error JSON401 *UnauthorizedError JSON402 *PaymentMethodRequiredError + JSON403 *DelegationForbiddenError JSON404 *Error JSON422 *IdempotencyError JSON500 *InternalServerError @@ -20028,6 +26011,14 @@ func (r SendSolanaAssetWithEndUserAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SendSolanaAssetWithEndUserAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ListEndUsersResponse struct { Body []byte HTTPResponse *http.Response @@ -20061,6 +26052,14 @@ func (r ListEndUsersResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListEndUsersResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type CreateEndUserResponse struct { Body []byte HTTPResponse *http.Response @@ -20088,6 +26087,14 @@ func (r CreateEndUserResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r CreateEndUserResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ValidateEndUserAccessTokenResponse struct { Body []byte HTTPResponse *http.Response @@ -20114,6 +26121,14 @@ func (r ValidateEndUserAccessTokenResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ValidateEndUserAccessTokenResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ImportEndUserResponse struct { Body []byte HTTPResponse *http.Response @@ -20144,6 +26159,14 @@ func (r ImportEndUserResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ImportEndUserResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type LookupEndUserResponse struct { Body []byte HTTPResponse *http.Response @@ -20172,6 +26195,14 @@ func (r LookupEndUserResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r LookupEndUserResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type GetEndUserResponse struct { Body []byte HTTPResponse *http.Response @@ -20196,6 +26227,14 @@ func (r GetEndUserResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetEndUserResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type AddEndUserEvmAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -20229,6 +26268,14 @@ func (r AddEndUserEvmAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r AddEndUserEvmAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type AddEndUserEvmSmartAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -20262,6 +26309,14 @@ func (r AddEndUserEvmSmartAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r AddEndUserEvmSmartAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type AddEndUserSolanaAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -20295,6 +26350,14 @@ func (r AddEndUserSolanaAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r AddEndUserSolanaAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ListEvmAccountsResponse struct { Body []byte HTTPResponse *http.Response @@ -20326,6 +26389,14 @@ func (r ListEvmAccountsResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListEvmAccountsResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type CreateEvmAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -20356,6 +26427,14 @@ func (r CreateEvmAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r CreateEvmAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type GetEvmAccountByNameResponse struct { Body []byte HTTPResponse *http.Response @@ -20383,6 +26462,14 @@ func (r GetEvmAccountByNameResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetEvmAccountByNameResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ExportEvmAccountByNameResponse struct { Body []byte HTTPResponse *http.Response @@ -20416,6 +26503,14 @@ func (r ExportEvmAccountByNameResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ExportEvmAccountByNameResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ImportEvmAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -20446,6 +26541,14 @@ func (r ImportEvmAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ImportEvmAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type GetEvmAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -20473,6 +26576,14 @@ func (r GetEvmAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetEvmAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type UpdateEvmAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -20502,6 +26613,14 @@ func (r UpdateEvmAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r UpdateEvmAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type CreateEvmEip7702DelegationResponse struct { Body []byte HTTPResponse *http.Response @@ -20536,6 +26655,14 @@ func (r CreateEvmEip7702DelegationResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r CreateEvmEip7702DelegationResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ExportEvmAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -20569,6 +26696,14 @@ func (r ExportEvmAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ExportEvmAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type SendEvmTransactionResponse struct { Body []byte HTTPResponse *http.Response @@ -20604,6 +26739,14 @@ func (r SendEvmTransactionResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SendEvmTransactionResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type SignEvmHashResponse struct { Body []byte HTTPResponse *http.Response @@ -20637,6 +26780,14 @@ func (r SignEvmHashResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SignEvmHashResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type SignEvmMessageResponse struct { Body []byte HTTPResponse *http.Response @@ -20670,6 +26821,14 @@ func (r SignEvmMessageResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SignEvmMessageResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type SignEvmTransactionResponse struct { Body []byte HTTPResponse *http.Response @@ -20705,6 +26864,14 @@ func (r SignEvmTransactionResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SignEvmTransactionResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type SignEvmTypedDataResponse struct { Body []byte HTTPResponse *http.Response @@ -20738,6 +26905,14 @@ func (r SignEvmTypedDataResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SignEvmTypedDataResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type GetEvmEip7702DelegationOperationByIdResponse struct { Body []byte HTTPResponse *http.Response @@ -20765,6 +26940,14 @@ func (r GetEvmEip7702DelegationOperationByIdResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetEvmEip7702DelegationOperationByIdResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type RequestEvmFaucetResponse struct { Body []byte HTTPResponse *http.Response @@ -20797,6 +26980,14 @@ func (r RequestEvmFaucetResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r RequestEvmFaucetResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ListEvmSmartAccountsResponse struct { Body []byte HTTPResponse *http.Response @@ -20829,6 +27020,14 @@ func (r ListEvmSmartAccountsResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListEvmSmartAccountsResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type CreateEvmSmartAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -20856,6 +27055,14 @@ func (r CreateEvmSmartAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r CreateEvmSmartAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type GetEvmSmartAccountByNameResponse struct { Body []byte HTTPResponse *http.Response @@ -20883,6 +27090,14 @@ func (r GetEvmSmartAccountByNameResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetEvmSmartAccountByNameResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type GetEvmSmartAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -20910,6 +27125,14 @@ func (r GetEvmSmartAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetEvmSmartAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type UpdateEvmSmartAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -20939,6 +27162,14 @@ func (r UpdateEvmSmartAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r UpdateEvmSmartAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type CreateSpendPermissionResponse struct { Body []byte HTTPResponse *http.Response @@ -20966,6 +27197,14 @@ func (r CreateSpendPermissionResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r CreateSpendPermissionResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ListSpendPermissionsResponse struct { Body []byte HTTPResponse *http.Response @@ -20999,6 +27238,14 @@ func (r ListSpendPermissionsResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListSpendPermissionsResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type RevokeSpendPermissionResponse struct { Body []byte HTTPResponse *http.Response @@ -21026,6 +27273,14 @@ func (r RevokeSpendPermissionResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r RevokeSpendPermissionResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type PrepareUserOperationResponse struct { Body []byte HTTPResponse *http.Response @@ -21054,6 +27309,14 @@ func (r PrepareUserOperationResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r PrepareUserOperationResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type PrepareAndSendUserOperationResponse struct { Body []byte HTTPResponse *http.Response @@ -21085,6 +27348,14 @@ func (r PrepareAndSendUserOperationResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r PrepareAndSendUserOperationResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type GetUserOperationResponse struct { Body []byte HTTPResponse *http.Response @@ -21112,6 +27383,14 @@ func (r GetUserOperationResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetUserOperationResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type SendUserOperationResponse struct { Body []byte HTTPResponse *http.Response @@ -21142,6 +27421,14 @@ func (r SendUserOperationResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SendUserOperationResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type CreateEvmSwapQuoteResponse struct { Body []byte HTTPResponse *http.Response @@ -21169,6 +27456,14 @@ func (r CreateEvmSwapQuoteResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r CreateEvmSwapQuoteResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type GetEvmSwapPriceResponse struct { Body []byte HTTPResponse *http.Response @@ -21196,6 +27491,14 @@ func (r GetEvmSwapPriceResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetEvmSwapPriceResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ListEvmTokenBalancesResponse struct { Body []byte HTTPResponse *http.Response @@ -21229,6 +27532,14 @@ func (r ListEvmTokenBalancesResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListEvmTokenBalancesResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type GetOnrampUserLimitsResponse struct { Body []byte HTTPResponse *http.Response @@ -21258,6 +27569,14 @@ func (r GetOnrampUserLimitsResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetOnrampUserLimitsResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type RequestLimitsUpgradeResponse struct { Body []byte HTTPResponse *http.Response @@ -21278,22 +27597,106 @@ func (r RequestLimitsUpgradeResponse) Status() string { // StatusCode returns HTTPResponse.StatusCode func (r RequestLimitsUpgradeResponse) StatusCode() int { if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r RequestLimitsUpgradeResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type CreateOnrampOrderResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *struct { + // Order An Onramp order. + Order OnrampOrder `json:"order"` + + // PaymentLink A payment link to pay for an order. + // + // Please refer to the [Onramp docs](https://docs.cdp.coinbase.com/onramp-&-offramp/onramp-apis/onramp-overview) for details on how to integrate with the different payment link types. + PaymentLink *OnrampPaymentLink `json:"paymentLink,omitempty"` + } + JSON400 *Error + JSON401 *UnauthorizedError + JSON429 *RateLimitExceeded + JSON500 *InternalServerError +} + +// Status returns HTTPResponse.Status +func (r CreateOnrampOrderResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateOnrampOrderResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r CreateOnrampOrderResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type GetOnrampOrderByIdResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *struct { + // Order An Onramp order. + Order OnrampOrder `json:"order"` + } + JSON401 *UnauthorizedError + JSON404 *Error + JSON429 *RateLimitExceeded +} + +// Status returns HTTPResponse.Status +func (r GetOnrampOrderByIdResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetOnrampOrderByIdResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetOnrampOrderByIdResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") } - return 0 + return "" } -type CreateOnrampOrderResponse struct { +type CreateOnrampSessionResponse struct { Body []byte HTTPResponse *http.Response JSON201 *struct { - // Order An Onramp order. - Order OnrampOrder `json:"order"` + // Quote Quote information with pricing details for the crypto purchase. + Quote *OnrampQuote `json:"quote,omitempty"` - // PaymentLink A payment link to pay for an order. - // - // Please refer to the [Onramp docs](https://docs.cdp.coinbase.com/onramp-&-offramp/onramp-apis/onramp-overview) for details on how to integrate with the different payment link types. - PaymentLink *OnrampPaymentLink `json:"paymentLink,omitempty"` + // Session An onramp session containing a ready-to-use onramp URL. + Session OnrampSession `json:"session"` } JSON400 *Error JSON401 *UnauthorizedError @@ -21302,7 +27705,7 @@ type CreateOnrampOrderResponse struct { } // Status returns HTTPResponse.Status -func (r CreateOnrampOrderResponse) Status() string { +func (r CreateOnrampSessionResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -21310,27 +27713,38 @@ func (r CreateOnrampOrderResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r CreateOnrampOrderResponse) StatusCode() int { +func (r CreateOnrampSessionResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } return 0 } -type GetOnrampOrderByIdResponse struct { +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r CreateOnrampSessionResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type ListPaymentMethodsResponse struct { Body []byte HTTPResponse *http.Response JSON200 *struct { - // Order An Onramp order. - Order OnrampOrder `json:"order"` + // NextPageToken The token for the next page of items, if any. + NextPageToken *string `json:"nextPageToken,omitempty"` + + // PaymentMethods The list of payment methods. + PaymentMethods []PaymentMethodsPaymentMethod `json:"paymentMethods"` } + JSON400 *Error JSON401 *UnauthorizedError - JSON404 *Error - JSON429 *RateLimitExceeded + JSON500 *InternalServerError } // Status returns HTTPResponse.Status -func (r GetOnrampOrderByIdResponse) Status() string { +func (r ListPaymentMethodsResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -21338,31 +27752,33 @@ func (r GetOnrampOrderByIdResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r GetOnrampOrderByIdResponse) StatusCode() int { +func (r ListPaymentMethodsResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } return 0 } -type CreateOnrampSessionResponse struct { +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListPaymentMethodsResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type GetPaymentMethodResponse struct { Body []byte HTTPResponse *http.Response - JSON201 *struct { - // Quote Quote information with pricing details for the crypto purchase. - Quote *OnrampQuote `json:"quote,omitempty"` - - // Session An onramp session containing a ready-to-use onramp URL. - Session OnrampSession `json:"session"` - } - JSON400 *Error - JSON401 *UnauthorizedError - JSON429 *RateLimitExceeded - JSON500 *InternalServerError + JSON200 *PaymentMethodsPaymentMethod + JSON400 *Error + JSON401 *UnauthorizedError + JSON404 *Error + JSON500 *InternalServerError } // Status returns HTTPResponse.Status -func (r CreateOnrampSessionResponse) Status() string { +func (r GetPaymentMethodResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -21370,13 +27786,21 @@ func (r CreateOnrampSessionResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r CreateOnrampSessionResponse) StatusCode() int { +func (r GetPaymentMethodResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetPaymentMethodResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ListPoliciesResponse struct { Body []byte HTTPResponse *http.Response @@ -21408,6 +27832,14 @@ func (r ListPoliciesResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListPoliciesResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type CreatePolicyResponse struct { Body []byte HTTPResponse *http.Response @@ -21436,6 +27868,14 @@ func (r CreatePolicyResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r CreatePolicyResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type DeletePolicyResponse struct { Body []byte HTTPResponse *http.Response @@ -21464,6 +27904,14 @@ func (r DeletePolicyResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r DeletePolicyResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type GetPolicyByIdResponse struct { Body []byte HTTPResponse *http.Response @@ -21490,6 +27938,14 @@ func (r GetPolicyByIdResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetPolicyByIdResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type UpdatePolicyResponse struct { Body []byte HTTPResponse *http.Response @@ -21519,6 +27975,14 @@ func (r UpdatePolicyResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r UpdatePolicyResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ListSolanaAccountsResponse struct { Body []byte HTTPResponse *http.Response @@ -21550,6 +28014,14 @@ func (r ListSolanaAccountsResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListSolanaAccountsResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type CreateSolanaAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -21580,6 +28052,14 @@ func (r CreateSolanaAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r CreateSolanaAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type GetSolanaAccountByNameResponse struct { Body []byte HTTPResponse *http.Response @@ -21607,6 +28087,14 @@ func (r GetSolanaAccountByNameResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetSolanaAccountByNameResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ExportSolanaAccountByNameResponse struct { Body []byte HTTPResponse *http.Response @@ -21640,6 +28128,14 @@ func (r ExportSolanaAccountByNameResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ExportSolanaAccountByNameResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ImportSolanaAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -21670,6 +28166,14 @@ func (r ImportSolanaAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ImportSolanaAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type SendSolanaTransactionResponse struct { Body []byte HTTPResponse *http.Response @@ -21704,6 +28208,14 @@ func (r SendSolanaTransactionResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SendSolanaTransactionResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type GetSolanaAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -21731,6 +28243,14 @@ func (r GetSolanaAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetSolanaAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type UpdateSolanaAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -21760,6 +28280,14 @@ func (r UpdateSolanaAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r UpdateSolanaAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ExportSolanaAccountResponse struct { Body []byte HTTPResponse *http.Response @@ -21793,6 +28321,14 @@ func (r ExportSolanaAccountResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ExportSolanaAccountResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type SignSolanaMessageResponse struct { Body []byte HTTPResponse *http.Response @@ -21827,6 +28363,14 @@ func (r SignSolanaMessageResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SignSolanaMessageResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type SignSolanaTransactionResponse struct { Body []byte HTTPResponse *http.Response @@ -21862,6 +28406,14 @@ func (r SignSolanaTransactionResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SignSolanaTransactionResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type RequestSolanaFaucetResponse struct { Body []byte HTTPResponse *http.Response @@ -21893,6 +28445,14 @@ func (r RequestSolanaFaucetResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r RequestSolanaFaucetResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ListSolanaTokenBalancesResponse struct { Body []byte HTTPResponse *http.Response @@ -21911,7 +28471,178 @@ type ListSolanaTokenBalancesResponse struct { } // Status returns HTTPResponse.Status -func (r ListSolanaTokenBalancesResponse) Status() string { +func (r ListSolanaTokenBalancesResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListSolanaTokenBalancesResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListSolanaTokenBalancesResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type ListTransfersResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *struct { + // NextPageToken The token for the next page of items, if any. + NextPageToken *string `json:"nextPageToken,omitempty"` + + // Transfers The list of transfers. + Transfers []Transfer `json:"transfers"` + } + JSON400 *Error +} + +// Status returns HTTPResponse.Status +func (r ListTransfersResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListTransfersResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListTransfersResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type CreateTransferResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Transfer + JSON400 *Error + JSON422 *IdempotencyError +} + +// Status returns HTTPResponse.Status +func (r CreateTransferResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateTransferResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r CreateTransferResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type GetTransferByIdResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Transfer + JSON404 *Error +} + +// Status returns HTTPResponse.Status +func (r GetTransferByIdResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetTransferByIdResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetTransferByIdResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type ExecuteFundTransferResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Transfer + JSON400 *Error + JSON401 *Error + JSON404 *Error + JSON422 *IdempotencyError + JSON429 *Error + JSON500 *InternalServerError + JSON502 *BadGatewayError + JSON503 *ServiceUnavailableError +} + +// Status returns HTTPResponse.Status +func (r ExecuteFundTransferResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ExecuteFundTransferResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ExecuteFundTransferResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type SubmitDepositTravelRuleResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DepositTravelRuleResponse + JSON400 *Error + JSON404 *Error + JSON422 *IdempotencyError +} + +// Status returns HTTPResponse.Status +func (r SubmitDepositTravelRuleResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -21919,13 +28650,21 @@ func (r ListSolanaTokenBalancesResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r ListSolanaTokenBalancesResponse) StatusCode() int { +func (r SubmitDepositTravelRuleResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SubmitDepositTravelRuleResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type PostX402DiscoveryMcpResponse struct { Body []byte HTTPResponse *http.Response @@ -21950,6 +28689,14 @@ func (r PostX402DiscoveryMcpResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r PostX402DiscoveryMcpResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ListX402DiscoveryMerchantResponse struct { Body []byte HTTPResponse *http.Response @@ -21977,6 +28724,14 @@ func (r ListX402DiscoveryMerchantResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListX402DiscoveryMerchantResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ListX402DiscoveryResourcesResponse struct { Body []byte HTTPResponse *http.Response @@ -22003,6 +28758,14 @@ func (r ListX402DiscoveryResourcesResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListX402DiscoveryResourcesResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type SearchX402ResourcesResponse struct { Body []byte HTTPResponse *http.Response @@ -22029,6 +28792,14 @@ func (r SearchX402ResourcesResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SearchX402ResourcesResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type SettleX402PaymentResponse struct { Body []byte HTTPResponse *http.Response @@ -22056,6 +28827,14 @@ func (r SettleX402PaymentResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SettleX402PaymentResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type SupportedX402PaymentKindsResponse struct { Body []byte HTTPResponse *http.Response @@ -22081,6 +28860,14 @@ func (r SupportedX402PaymentKindsResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SupportedX402PaymentKindsResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type VerifyX402PaymentResponse struct { Body []byte HTTPResponse *http.Response @@ -22107,6 +28894,67 @@ func (r VerifyX402PaymentResponse) StatusCode() int { return 0 } +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r VerifyX402PaymentResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +// ListFoundationAccountsWithResponse request returning *ListFoundationAccountsResponse +func (c *ClientWithResponses) ListFoundationAccountsWithResponse(ctx context.Context, params *ListFoundationAccountsParams, reqEditors ...RequestEditorFn) (*ListFoundationAccountsResponse, error) { + rsp, err := c.ListFoundationAccounts(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListFoundationAccountsResponse(rsp) +} + +// CreateFoundationAccountWithBodyWithResponse request with arbitrary body returning *CreateFoundationAccountResponse +func (c *ClientWithResponses) CreateFoundationAccountWithBodyWithResponse(ctx context.Context, params *CreateFoundationAccountParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateFoundationAccountResponse, error) { + rsp, err := c.CreateFoundationAccountWithBody(ctx, params, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateFoundationAccountResponse(rsp) +} + +func (c *ClientWithResponses) CreateFoundationAccountWithResponse(ctx context.Context, params *CreateFoundationAccountParams, body CreateFoundationAccountJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateFoundationAccountResponse, error) { + rsp, err := c.CreateFoundationAccount(ctx, params, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateFoundationAccountResponse(rsp) +} + +// GetFoundationAccountByIdWithResponse request returning *GetFoundationAccountByIdResponse +func (c *ClientWithResponses) GetFoundationAccountByIdWithResponse(ctx context.Context, accountId AccountId, reqEditors ...RequestEditorFn) (*GetFoundationAccountByIdResponse, error) { + rsp, err := c.GetFoundationAccountById(ctx, accountId, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetFoundationAccountByIdResponse(rsp) +} + +// ListBalancesWithResponse request returning *ListBalancesResponse +func (c *ClientWithResponses) ListBalancesWithResponse(ctx context.Context, accountId AccountId, params *ListBalancesParams, reqEditors ...RequestEditorFn) (*ListBalancesResponse, error) { + rsp, err := c.ListBalances(ctx, accountId, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListBalancesResponse(rsp) +} + +// GetBalanceByAssetWithResponse request returning *GetBalanceByAssetResponse +func (c *ClientWithResponses) GetBalanceByAssetWithResponse(ctx context.Context, accountId AccountId, asset Asset, reqEditors ...RequestEditorFn) (*GetBalanceByAssetResponse, error) { + rsp, err := c.GetBalanceByAsset(ctx, accountId, asset, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetBalanceByAssetResponse(rsp) +} + // ListDataTokenBalancesWithResponse request returning *ListDataTokenBalancesResponse func (c *ClientWithResponses) ListDataTokenBalancesWithResponse(ctx context.Context, network ListEvmTokenBalancesNetwork, address string, params *ListDataTokenBalancesParams, reqEditors ...RequestEditorFn) (*ListDataTokenBalancesResponse, error) { rsp, err := c.ListDataTokenBalances(ctx, network, address, params, reqEditors...) @@ -22230,6 +29078,41 @@ func (c *ClientWithResponses) ListWebhookSubscriptionEventsWithResponse(ctx cont return ParseListWebhookSubscriptionEventsResponse(rsp) } +// ListDepositDestinationsWithResponse request returning *ListDepositDestinationsResponse +func (c *ClientWithResponses) ListDepositDestinationsWithResponse(ctx context.Context, params *ListDepositDestinationsParams, reqEditors ...RequestEditorFn) (*ListDepositDestinationsResponse, error) { + rsp, err := c.ListDepositDestinations(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListDepositDestinationsResponse(rsp) +} + +// CreateDepositDestinationWithBodyWithResponse request with arbitrary body returning *CreateDepositDestinationResponse +func (c *ClientWithResponses) CreateDepositDestinationWithBodyWithResponse(ctx context.Context, params *CreateDepositDestinationParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateDepositDestinationResponse, error) { + rsp, err := c.CreateDepositDestinationWithBody(ctx, params, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateDepositDestinationResponse(rsp) +} + +func (c *ClientWithResponses) CreateDepositDestinationWithResponse(ctx context.Context, params *CreateDepositDestinationParams, body CreateDepositDestinationJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateDepositDestinationResponse, error) { + rsp, err := c.CreateDepositDestination(ctx, params, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateDepositDestinationResponse(rsp) +} + +// GetDepositDestinationByIdWithResponse request returning *GetDepositDestinationByIdResponse +func (c *ClientWithResponses) GetDepositDestinationByIdWithResponse(ctx context.Context, depositDestinationId DepositDestinationId, reqEditors ...RequestEditorFn) (*GetDepositDestinationByIdResponse, error) { + rsp, err := c.GetDepositDestinationById(ctx, depositDestinationId, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetDepositDestinationByIdResponse(rsp) +} + // RevokeDelegationForEndUserAccountWithBodyWithResponse request with arbitrary body returning *RevokeDelegationForEndUserAccountResponse func (c *ClientWithResponses) RevokeDelegationForEndUserAccountWithBodyWithResponse(ctx context.Context, userId string, address BlockchainAddress, params *RevokeDelegationForEndUserAccountParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*RevokeDelegationForEndUserAccountResponse, error) { rsp, err := c.RevokeDelegationForEndUserAccountWithBody(ctx, userId, address, params, contentType, body, reqEditors...) @@ -23131,6 +30014,24 @@ func (c *ClientWithResponses) CreateOnrampSessionWithResponse(ctx context.Contex return ParseCreateOnrampSessionResponse(rsp) } +// ListPaymentMethodsWithResponse request returning *ListPaymentMethodsResponse +func (c *ClientWithResponses) ListPaymentMethodsWithResponse(ctx context.Context, params *ListPaymentMethodsParams, reqEditors ...RequestEditorFn) (*ListPaymentMethodsResponse, error) { + rsp, err := c.ListPaymentMethods(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListPaymentMethodsResponse(rsp) +} + +// GetPaymentMethodWithResponse request returning *GetPaymentMethodResponse +func (c *ClientWithResponses) GetPaymentMethodWithResponse(ctx context.Context, paymentMethodId PaymentMethodId, reqEditors ...RequestEditorFn) (*GetPaymentMethodResponse, error) { + rsp, err := c.GetPaymentMethod(ctx, paymentMethodId, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetPaymentMethodResponse(rsp) +} + // ListPoliciesWithResponse request returning *ListPoliciesResponse func (c *ClientWithResponses) ListPoliciesWithResponse(ctx context.Context, params *ListPoliciesParams, reqEditors ...RequestEditorFn) (*ListPoliciesResponse, error) { rsp, err := c.ListPolicies(ctx, params, reqEditors...) @@ -23224,248 +30125,563 @@ func (c *ClientWithResponses) GetSolanaAccountByNameWithResponse(ctx context.Con if err != nil { return nil, err } - return ParseGetSolanaAccountByNameResponse(rsp) + return ParseGetSolanaAccountByNameResponse(rsp) +} + +// ExportSolanaAccountByNameWithBodyWithResponse request with arbitrary body returning *ExportSolanaAccountByNameResponse +func (c *ClientWithResponses) ExportSolanaAccountByNameWithBodyWithResponse(ctx context.Context, name string, params *ExportSolanaAccountByNameParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ExportSolanaAccountByNameResponse, error) { + rsp, err := c.ExportSolanaAccountByNameWithBody(ctx, name, params, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseExportSolanaAccountByNameResponse(rsp) +} + +func (c *ClientWithResponses) ExportSolanaAccountByNameWithResponse(ctx context.Context, name string, params *ExportSolanaAccountByNameParams, body ExportSolanaAccountByNameJSONRequestBody, reqEditors ...RequestEditorFn) (*ExportSolanaAccountByNameResponse, error) { + rsp, err := c.ExportSolanaAccountByName(ctx, name, params, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseExportSolanaAccountByNameResponse(rsp) +} + +// ImportSolanaAccountWithBodyWithResponse request with arbitrary body returning *ImportSolanaAccountResponse +func (c *ClientWithResponses) ImportSolanaAccountWithBodyWithResponse(ctx context.Context, params *ImportSolanaAccountParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ImportSolanaAccountResponse, error) { + rsp, err := c.ImportSolanaAccountWithBody(ctx, params, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseImportSolanaAccountResponse(rsp) +} + +func (c *ClientWithResponses) ImportSolanaAccountWithResponse(ctx context.Context, params *ImportSolanaAccountParams, body ImportSolanaAccountJSONRequestBody, reqEditors ...RequestEditorFn) (*ImportSolanaAccountResponse, error) { + rsp, err := c.ImportSolanaAccount(ctx, params, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseImportSolanaAccountResponse(rsp) +} + +// SendSolanaTransactionWithBodyWithResponse request with arbitrary body returning *SendSolanaTransactionResponse +func (c *ClientWithResponses) SendSolanaTransactionWithBodyWithResponse(ctx context.Context, params *SendSolanaTransactionParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*SendSolanaTransactionResponse, error) { + rsp, err := c.SendSolanaTransactionWithBody(ctx, params, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseSendSolanaTransactionResponse(rsp) +} + +func (c *ClientWithResponses) SendSolanaTransactionWithResponse(ctx context.Context, params *SendSolanaTransactionParams, body SendSolanaTransactionJSONRequestBody, reqEditors ...RequestEditorFn) (*SendSolanaTransactionResponse, error) { + rsp, err := c.SendSolanaTransaction(ctx, params, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseSendSolanaTransactionResponse(rsp) +} + +// GetSolanaAccountWithResponse request returning *GetSolanaAccountResponse +func (c *ClientWithResponses) GetSolanaAccountWithResponse(ctx context.Context, address string, reqEditors ...RequestEditorFn) (*GetSolanaAccountResponse, error) { + rsp, err := c.GetSolanaAccount(ctx, address, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetSolanaAccountResponse(rsp) +} + +// UpdateSolanaAccountWithBodyWithResponse request with arbitrary body returning *UpdateSolanaAccountResponse +func (c *ClientWithResponses) UpdateSolanaAccountWithBodyWithResponse(ctx context.Context, address string, params *UpdateSolanaAccountParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateSolanaAccountResponse, error) { + rsp, err := c.UpdateSolanaAccountWithBody(ctx, address, params, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateSolanaAccountResponse(rsp) +} + +func (c *ClientWithResponses) UpdateSolanaAccountWithResponse(ctx context.Context, address string, params *UpdateSolanaAccountParams, body UpdateSolanaAccountJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateSolanaAccountResponse, error) { + rsp, err := c.UpdateSolanaAccount(ctx, address, params, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateSolanaAccountResponse(rsp) +} + +// ExportSolanaAccountWithBodyWithResponse request with arbitrary body returning *ExportSolanaAccountResponse +func (c *ClientWithResponses) ExportSolanaAccountWithBodyWithResponse(ctx context.Context, address string, params *ExportSolanaAccountParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ExportSolanaAccountResponse, error) { + rsp, err := c.ExportSolanaAccountWithBody(ctx, address, params, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseExportSolanaAccountResponse(rsp) +} + +func (c *ClientWithResponses) ExportSolanaAccountWithResponse(ctx context.Context, address string, params *ExportSolanaAccountParams, body ExportSolanaAccountJSONRequestBody, reqEditors ...RequestEditorFn) (*ExportSolanaAccountResponse, error) { + rsp, err := c.ExportSolanaAccount(ctx, address, params, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseExportSolanaAccountResponse(rsp) +} + +// SignSolanaMessageWithBodyWithResponse request with arbitrary body returning *SignSolanaMessageResponse +func (c *ClientWithResponses) SignSolanaMessageWithBodyWithResponse(ctx context.Context, address string, params *SignSolanaMessageParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*SignSolanaMessageResponse, error) { + rsp, err := c.SignSolanaMessageWithBody(ctx, address, params, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseSignSolanaMessageResponse(rsp) +} + +func (c *ClientWithResponses) SignSolanaMessageWithResponse(ctx context.Context, address string, params *SignSolanaMessageParams, body SignSolanaMessageJSONRequestBody, reqEditors ...RequestEditorFn) (*SignSolanaMessageResponse, error) { + rsp, err := c.SignSolanaMessage(ctx, address, params, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseSignSolanaMessageResponse(rsp) +} + +// SignSolanaTransactionWithBodyWithResponse request with arbitrary body returning *SignSolanaTransactionResponse +func (c *ClientWithResponses) SignSolanaTransactionWithBodyWithResponse(ctx context.Context, address string, params *SignSolanaTransactionParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*SignSolanaTransactionResponse, error) { + rsp, err := c.SignSolanaTransactionWithBody(ctx, address, params, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseSignSolanaTransactionResponse(rsp) +} + +func (c *ClientWithResponses) SignSolanaTransactionWithResponse(ctx context.Context, address string, params *SignSolanaTransactionParams, body SignSolanaTransactionJSONRequestBody, reqEditors ...RequestEditorFn) (*SignSolanaTransactionResponse, error) { + rsp, err := c.SignSolanaTransaction(ctx, address, params, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseSignSolanaTransactionResponse(rsp) +} + +// RequestSolanaFaucetWithBodyWithResponse request with arbitrary body returning *RequestSolanaFaucetResponse +func (c *ClientWithResponses) RequestSolanaFaucetWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*RequestSolanaFaucetResponse, error) { + rsp, err := c.RequestSolanaFaucetWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseRequestSolanaFaucetResponse(rsp) +} + +func (c *ClientWithResponses) RequestSolanaFaucetWithResponse(ctx context.Context, body RequestSolanaFaucetJSONRequestBody, reqEditors ...RequestEditorFn) (*RequestSolanaFaucetResponse, error) { + rsp, err := c.RequestSolanaFaucet(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseRequestSolanaFaucetResponse(rsp) +} + +// ListSolanaTokenBalancesWithResponse request returning *ListSolanaTokenBalancesResponse +func (c *ClientWithResponses) ListSolanaTokenBalancesWithResponse(ctx context.Context, network ListSolanaTokenBalancesNetwork, address string, params *ListSolanaTokenBalancesParams, reqEditors ...RequestEditorFn) (*ListSolanaTokenBalancesResponse, error) { + rsp, err := c.ListSolanaTokenBalances(ctx, network, address, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListSolanaTokenBalancesResponse(rsp) +} + +// ListTransfersWithResponse request returning *ListTransfersResponse +func (c *ClientWithResponses) ListTransfersWithResponse(ctx context.Context, params *ListTransfersParams, reqEditors ...RequestEditorFn) (*ListTransfersResponse, error) { + rsp, err := c.ListTransfers(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListTransfersResponse(rsp) } -// ExportSolanaAccountByNameWithBodyWithResponse request with arbitrary body returning *ExportSolanaAccountByNameResponse -func (c *ClientWithResponses) ExportSolanaAccountByNameWithBodyWithResponse(ctx context.Context, name string, params *ExportSolanaAccountByNameParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ExportSolanaAccountByNameResponse, error) { - rsp, err := c.ExportSolanaAccountByNameWithBody(ctx, name, params, contentType, body, reqEditors...) +// CreateTransferWithBodyWithResponse request with arbitrary body returning *CreateTransferResponse +func (c *ClientWithResponses) CreateTransferWithBodyWithResponse(ctx context.Context, params *CreateTransferParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateTransferResponse, error) { + rsp, err := c.CreateTransferWithBody(ctx, params, contentType, body, reqEditors...) if err != nil { return nil, err } - return ParseExportSolanaAccountByNameResponse(rsp) + return ParseCreateTransferResponse(rsp) } -func (c *ClientWithResponses) ExportSolanaAccountByNameWithResponse(ctx context.Context, name string, params *ExportSolanaAccountByNameParams, body ExportSolanaAccountByNameJSONRequestBody, reqEditors ...RequestEditorFn) (*ExportSolanaAccountByNameResponse, error) { - rsp, err := c.ExportSolanaAccountByName(ctx, name, params, body, reqEditors...) +func (c *ClientWithResponses) CreateTransferWithResponse(ctx context.Context, params *CreateTransferParams, body CreateTransferJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateTransferResponse, error) { + rsp, err := c.CreateTransfer(ctx, params, body, reqEditors...) if err != nil { return nil, err } - return ParseExportSolanaAccountByNameResponse(rsp) + return ParseCreateTransferResponse(rsp) } -// ImportSolanaAccountWithBodyWithResponse request with arbitrary body returning *ImportSolanaAccountResponse -func (c *ClientWithResponses) ImportSolanaAccountWithBodyWithResponse(ctx context.Context, params *ImportSolanaAccountParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ImportSolanaAccountResponse, error) { - rsp, err := c.ImportSolanaAccountWithBody(ctx, params, contentType, body, reqEditors...) +// GetTransferByIdWithResponse request returning *GetTransferByIdResponse +func (c *ClientWithResponses) GetTransferByIdWithResponse(ctx context.Context, transferId string, reqEditors ...RequestEditorFn) (*GetTransferByIdResponse, error) { + rsp, err := c.GetTransferById(ctx, transferId, reqEditors...) if err != nil { return nil, err } - return ParseImportSolanaAccountResponse(rsp) + return ParseGetTransferByIdResponse(rsp) } -func (c *ClientWithResponses) ImportSolanaAccountWithResponse(ctx context.Context, params *ImportSolanaAccountParams, body ImportSolanaAccountJSONRequestBody, reqEditors ...RequestEditorFn) (*ImportSolanaAccountResponse, error) { - rsp, err := c.ImportSolanaAccount(ctx, params, body, reqEditors...) +// ExecuteFundTransferWithResponse request returning *ExecuteFundTransferResponse +func (c *ClientWithResponses) ExecuteFundTransferWithResponse(ctx context.Context, transferId string, params *ExecuteFundTransferParams, reqEditors ...RequestEditorFn) (*ExecuteFundTransferResponse, error) { + rsp, err := c.ExecuteFundTransfer(ctx, transferId, params, reqEditors...) if err != nil { return nil, err } - return ParseImportSolanaAccountResponse(rsp) + return ParseExecuteFundTransferResponse(rsp) } -// SendSolanaTransactionWithBodyWithResponse request with arbitrary body returning *SendSolanaTransactionResponse -func (c *ClientWithResponses) SendSolanaTransactionWithBodyWithResponse(ctx context.Context, params *SendSolanaTransactionParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*SendSolanaTransactionResponse, error) { - rsp, err := c.SendSolanaTransactionWithBody(ctx, params, contentType, body, reqEditors...) +// SubmitDepositTravelRuleWithBodyWithResponse request with arbitrary body returning *SubmitDepositTravelRuleResponse +func (c *ClientWithResponses) SubmitDepositTravelRuleWithBodyWithResponse(ctx context.Context, transferId string, params *SubmitDepositTravelRuleParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*SubmitDepositTravelRuleResponse, error) { + rsp, err := c.SubmitDepositTravelRuleWithBody(ctx, transferId, params, contentType, body, reqEditors...) if err != nil { return nil, err } - return ParseSendSolanaTransactionResponse(rsp) + return ParseSubmitDepositTravelRuleResponse(rsp) } -func (c *ClientWithResponses) SendSolanaTransactionWithResponse(ctx context.Context, params *SendSolanaTransactionParams, body SendSolanaTransactionJSONRequestBody, reqEditors ...RequestEditorFn) (*SendSolanaTransactionResponse, error) { - rsp, err := c.SendSolanaTransaction(ctx, params, body, reqEditors...) +func (c *ClientWithResponses) SubmitDepositTravelRuleWithResponse(ctx context.Context, transferId string, params *SubmitDepositTravelRuleParams, body SubmitDepositTravelRuleJSONRequestBody, reqEditors ...RequestEditorFn) (*SubmitDepositTravelRuleResponse, error) { + rsp, err := c.SubmitDepositTravelRule(ctx, transferId, params, body, reqEditors...) if err != nil { return nil, err } - return ParseSendSolanaTransactionResponse(rsp) + return ParseSubmitDepositTravelRuleResponse(rsp) } -// GetSolanaAccountWithResponse request returning *GetSolanaAccountResponse -func (c *ClientWithResponses) GetSolanaAccountWithResponse(ctx context.Context, address string, reqEditors ...RequestEditorFn) (*GetSolanaAccountResponse, error) { - rsp, err := c.GetSolanaAccount(ctx, address, reqEditors...) +// PostX402DiscoveryMcpWithBodyWithResponse request with arbitrary body returning *PostX402DiscoveryMcpResponse +func (c *ClientWithResponses) PostX402DiscoveryMcpWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostX402DiscoveryMcpResponse, error) { + rsp, err := c.PostX402DiscoveryMcpWithBody(ctx, contentType, body, reqEditors...) if err != nil { return nil, err } - return ParseGetSolanaAccountResponse(rsp) + return ParsePostX402DiscoveryMcpResponse(rsp) } -// UpdateSolanaAccountWithBodyWithResponse request with arbitrary body returning *UpdateSolanaAccountResponse -func (c *ClientWithResponses) UpdateSolanaAccountWithBodyWithResponse(ctx context.Context, address string, params *UpdateSolanaAccountParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateSolanaAccountResponse, error) { - rsp, err := c.UpdateSolanaAccountWithBody(ctx, address, params, contentType, body, reqEditors...) +func (c *ClientWithResponses) PostX402DiscoveryMcpWithResponse(ctx context.Context, body PostX402DiscoveryMcpJSONRequestBody, reqEditors ...RequestEditorFn) (*PostX402DiscoveryMcpResponse, error) { + rsp, err := c.PostX402DiscoveryMcp(ctx, body, reqEditors...) if err != nil { return nil, err } - return ParseUpdateSolanaAccountResponse(rsp) + return ParsePostX402DiscoveryMcpResponse(rsp) } -func (c *ClientWithResponses) UpdateSolanaAccountWithResponse(ctx context.Context, address string, params *UpdateSolanaAccountParams, body UpdateSolanaAccountJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateSolanaAccountResponse, error) { - rsp, err := c.UpdateSolanaAccount(ctx, address, params, body, reqEditors...) +// ListX402DiscoveryMerchantWithResponse request returning *ListX402DiscoveryMerchantResponse +func (c *ClientWithResponses) ListX402DiscoveryMerchantWithResponse(ctx context.Context, params *ListX402DiscoveryMerchantParams, reqEditors ...RequestEditorFn) (*ListX402DiscoveryMerchantResponse, error) { + rsp, err := c.ListX402DiscoveryMerchant(ctx, params, reqEditors...) if err != nil { return nil, err } - return ParseUpdateSolanaAccountResponse(rsp) + return ParseListX402DiscoveryMerchantResponse(rsp) } -// ExportSolanaAccountWithBodyWithResponse request with arbitrary body returning *ExportSolanaAccountResponse -func (c *ClientWithResponses) ExportSolanaAccountWithBodyWithResponse(ctx context.Context, address string, params *ExportSolanaAccountParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ExportSolanaAccountResponse, error) { - rsp, err := c.ExportSolanaAccountWithBody(ctx, address, params, contentType, body, reqEditors...) +// ListX402DiscoveryResourcesWithResponse request returning *ListX402DiscoveryResourcesResponse +func (c *ClientWithResponses) ListX402DiscoveryResourcesWithResponse(ctx context.Context, params *ListX402DiscoveryResourcesParams, reqEditors ...RequestEditorFn) (*ListX402DiscoveryResourcesResponse, error) { + rsp, err := c.ListX402DiscoveryResources(ctx, params, reqEditors...) if err != nil { return nil, err } - return ParseExportSolanaAccountResponse(rsp) + return ParseListX402DiscoveryResourcesResponse(rsp) } -func (c *ClientWithResponses) ExportSolanaAccountWithResponse(ctx context.Context, address string, params *ExportSolanaAccountParams, body ExportSolanaAccountJSONRequestBody, reqEditors ...RequestEditorFn) (*ExportSolanaAccountResponse, error) { - rsp, err := c.ExportSolanaAccount(ctx, address, params, body, reqEditors...) +// SearchX402ResourcesWithResponse request returning *SearchX402ResourcesResponse +func (c *ClientWithResponses) SearchX402ResourcesWithResponse(ctx context.Context, params *SearchX402ResourcesParams, reqEditors ...RequestEditorFn) (*SearchX402ResourcesResponse, error) { + rsp, err := c.SearchX402Resources(ctx, params, reqEditors...) if err != nil { return nil, err } - return ParseExportSolanaAccountResponse(rsp) + return ParseSearchX402ResourcesResponse(rsp) } -// SignSolanaMessageWithBodyWithResponse request with arbitrary body returning *SignSolanaMessageResponse -func (c *ClientWithResponses) SignSolanaMessageWithBodyWithResponse(ctx context.Context, address string, params *SignSolanaMessageParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*SignSolanaMessageResponse, error) { - rsp, err := c.SignSolanaMessageWithBody(ctx, address, params, contentType, body, reqEditors...) +// SettleX402PaymentWithBodyWithResponse request with arbitrary body returning *SettleX402PaymentResponse +func (c *ClientWithResponses) SettleX402PaymentWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*SettleX402PaymentResponse, error) { + rsp, err := c.SettleX402PaymentWithBody(ctx, contentType, body, reqEditors...) if err != nil { return nil, err } - return ParseSignSolanaMessageResponse(rsp) + return ParseSettleX402PaymentResponse(rsp) } -func (c *ClientWithResponses) SignSolanaMessageWithResponse(ctx context.Context, address string, params *SignSolanaMessageParams, body SignSolanaMessageJSONRequestBody, reqEditors ...RequestEditorFn) (*SignSolanaMessageResponse, error) { - rsp, err := c.SignSolanaMessage(ctx, address, params, body, reqEditors...) +func (c *ClientWithResponses) SettleX402PaymentWithResponse(ctx context.Context, body SettleX402PaymentJSONRequestBody, reqEditors ...RequestEditorFn) (*SettleX402PaymentResponse, error) { + rsp, err := c.SettleX402Payment(ctx, body, reqEditors...) if err != nil { return nil, err } - return ParseSignSolanaMessageResponse(rsp) + return ParseSettleX402PaymentResponse(rsp) } -// SignSolanaTransactionWithBodyWithResponse request with arbitrary body returning *SignSolanaTransactionResponse -func (c *ClientWithResponses) SignSolanaTransactionWithBodyWithResponse(ctx context.Context, address string, params *SignSolanaTransactionParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*SignSolanaTransactionResponse, error) { - rsp, err := c.SignSolanaTransactionWithBody(ctx, address, params, contentType, body, reqEditors...) +// SupportedX402PaymentKindsWithResponse request returning *SupportedX402PaymentKindsResponse +func (c *ClientWithResponses) SupportedX402PaymentKindsWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*SupportedX402PaymentKindsResponse, error) { + rsp, err := c.SupportedX402PaymentKinds(ctx, reqEditors...) if err != nil { return nil, err } - return ParseSignSolanaTransactionResponse(rsp) + return ParseSupportedX402PaymentKindsResponse(rsp) } -func (c *ClientWithResponses) SignSolanaTransactionWithResponse(ctx context.Context, address string, params *SignSolanaTransactionParams, body SignSolanaTransactionJSONRequestBody, reqEditors ...RequestEditorFn) (*SignSolanaTransactionResponse, error) { - rsp, err := c.SignSolanaTransaction(ctx, address, params, body, reqEditors...) +// VerifyX402PaymentWithBodyWithResponse request with arbitrary body returning *VerifyX402PaymentResponse +func (c *ClientWithResponses) VerifyX402PaymentWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*VerifyX402PaymentResponse, error) { + rsp, err := c.VerifyX402PaymentWithBody(ctx, contentType, body, reqEditors...) if err != nil { return nil, err } - return ParseSignSolanaTransactionResponse(rsp) + return ParseVerifyX402PaymentResponse(rsp) } -// RequestSolanaFaucetWithBodyWithResponse request with arbitrary body returning *RequestSolanaFaucetResponse -func (c *ClientWithResponses) RequestSolanaFaucetWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*RequestSolanaFaucetResponse, error) { - rsp, err := c.RequestSolanaFaucetWithBody(ctx, contentType, body, reqEditors...) +func (c *ClientWithResponses) VerifyX402PaymentWithResponse(ctx context.Context, body VerifyX402PaymentJSONRequestBody, reqEditors ...RequestEditorFn) (*VerifyX402PaymentResponse, error) { + rsp, err := c.VerifyX402Payment(ctx, body, reqEditors...) if err != nil { return nil, err } - return ParseRequestSolanaFaucetResponse(rsp) + return ParseVerifyX402PaymentResponse(rsp) } -func (c *ClientWithResponses) RequestSolanaFaucetWithResponse(ctx context.Context, body RequestSolanaFaucetJSONRequestBody, reqEditors ...RequestEditorFn) (*RequestSolanaFaucetResponse, error) { - rsp, err := c.RequestSolanaFaucet(ctx, body, reqEditors...) +// ParseListFoundationAccountsResponse parses an HTTP response from a ListFoundationAccountsWithResponse call +func ParseListFoundationAccountsResponse(rsp *http.Response) (*ListFoundationAccountsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - return ParseRequestSolanaFaucetResponse(rsp) + + response := &ListFoundationAccountsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest struct { + // Accounts The list of accounts. + Accounts []Account `json:"accounts"` + + // NextPageToken The token for the next page of items, if any. + NextPageToken *string `json:"nextPageToken,omitempty"` + } + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + } + + return response, nil } -// ListSolanaTokenBalancesWithResponse request returning *ListSolanaTokenBalancesResponse -func (c *ClientWithResponses) ListSolanaTokenBalancesWithResponse(ctx context.Context, network ListSolanaTokenBalancesNetwork, address string, params *ListSolanaTokenBalancesParams, reqEditors ...RequestEditorFn) (*ListSolanaTokenBalancesResponse, error) { - rsp, err := c.ListSolanaTokenBalances(ctx, network, address, params, reqEditors...) +// ParseCreateFoundationAccountResponse parses an HTTP response from a CreateFoundationAccountWithResponse call +func ParseCreateFoundationAccountResponse(rsp *http.Response) (*CreateFoundationAccountResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - return ParseListSolanaTokenBalancesResponse(rsp) + + response := &CreateFoundationAccountResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Account + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 422: + var dest IdempotencyError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON422 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest EndpointUnavailableError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON503 = &dest + + } + + return response, nil } -// PostX402DiscoveryMcpWithBodyWithResponse request with arbitrary body returning *PostX402DiscoveryMcpResponse -func (c *ClientWithResponses) PostX402DiscoveryMcpWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostX402DiscoveryMcpResponse, error) { - rsp, err := c.PostX402DiscoveryMcpWithBody(ctx, contentType, body, reqEditors...) +// ParseGetFoundationAccountByIdResponse parses an HTTP response from a GetFoundationAccountByIdWithResponse call +func ParseGetFoundationAccountByIdResponse(rsp *http.Response) (*GetFoundationAccountByIdResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - return ParsePostX402DiscoveryMcpResponse(rsp) + + response := &GetFoundationAccountByIdResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Account + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil } -func (c *ClientWithResponses) PostX402DiscoveryMcpWithResponse(ctx context.Context, body PostX402DiscoveryMcpJSONRequestBody, reqEditors ...RequestEditorFn) (*PostX402DiscoveryMcpResponse, error) { - rsp, err := c.PostX402DiscoveryMcp(ctx, body, reqEditors...) +// ParseListBalancesResponse parses an HTTP response from a ListBalancesWithResponse call +func ParseListBalancesResponse(rsp *http.Response) (*ListBalancesResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - return ParsePostX402DiscoveryMcpResponse(rsp) -} -// ListX402DiscoveryMerchantWithResponse request returning *ListX402DiscoveryMerchantResponse -func (c *ClientWithResponses) ListX402DiscoveryMerchantWithResponse(ctx context.Context, params *ListX402DiscoveryMerchantParams, reqEditors ...RequestEditorFn) (*ListX402DiscoveryMerchantResponse, error) { - rsp, err := c.ListX402DiscoveryMerchant(ctx, params, reqEditors...) - if err != nil { - return nil, err + response := &ListBalancesResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest struct { + // Balances The list of balances. + Balances []Balance `json:"balances"` + + // NextPageToken The token for the next page of items, if any. + NextPageToken *string `json:"nextPageToken,omitempty"` + } + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest EndpointUnavailableError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON503 = &dest + } - return ParseListX402DiscoveryMerchantResponse(rsp) -} -// ListX402DiscoveryResourcesWithResponse request returning *ListX402DiscoveryResourcesResponse -func (c *ClientWithResponses) ListX402DiscoveryResourcesWithResponse(ctx context.Context, params *ListX402DiscoveryResourcesParams, reqEditors ...RequestEditorFn) (*ListX402DiscoveryResourcesResponse, error) { - rsp, err := c.ListX402DiscoveryResources(ctx, params, reqEditors...) - if err != nil { - return nil, err - } - return ParseListX402DiscoveryResourcesResponse(rsp) + return response, nil } -// SearchX402ResourcesWithResponse request returning *SearchX402ResourcesResponse -func (c *ClientWithResponses) SearchX402ResourcesWithResponse(ctx context.Context, params *SearchX402ResourcesParams, reqEditors ...RequestEditorFn) (*SearchX402ResourcesResponse, error) { - rsp, err := c.SearchX402Resources(ctx, params, reqEditors...) +// ParseGetBalanceByAssetResponse parses an HTTP response from a GetBalanceByAssetWithResponse call +func ParseGetBalanceByAssetResponse(rsp *http.Response) (*GetBalanceByAssetResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - return ParseSearchX402ResourcesResponse(rsp) -} -// SettleX402PaymentWithBodyWithResponse request with arbitrary body returning *SettleX402PaymentResponse -func (c *ClientWithResponses) SettleX402PaymentWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*SettleX402PaymentResponse, error) { - rsp, err := c.SettleX402PaymentWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err + response := &GetBalanceByAssetResponse{ + Body: bodyBytes, + HTTPResponse: rsp, } - return ParseSettleX402PaymentResponse(rsp) -} -func (c *ClientWithResponses) SettleX402PaymentWithResponse(ctx context.Context, body SettleX402PaymentJSONRequestBody, reqEditors ...RequestEditorFn) (*SettleX402PaymentResponse, error) { - rsp, err := c.SettleX402Payment(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseSettleX402PaymentResponse(rsp) -} + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Balance + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest -// SupportedX402PaymentKindsWithResponse request returning *SupportedX402PaymentKindsResponse -func (c *ClientWithResponses) SupportedX402PaymentKindsWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*SupportedX402PaymentKindsResponse, error) { - rsp, err := c.SupportedX402PaymentKinds(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseSupportedX402PaymentKindsResponse(rsp) -} + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest -// VerifyX402PaymentWithBodyWithResponse request with arbitrary body returning *VerifyX402PaymentResponse -func (c *ClientWithResponses) VerifyX402PaymentWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*VerifyX402PaymentResponse, error) { - rsp, err := c.VerifyX402PaymentWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseVerifyX402PaymentResponse(rsp) -} + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest EndpointUnavailableError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON503 = &dest -func (c *ClientWithResponses) VerifyX402PaymentWithResponse(ctx context.Context, body VerifyX402PaymentJSONRequestBody, reqEditors ...RequestEditorFn) (*VerifyX402PaymentResponse, error) { - rsp, err := c.VerifyX402Payment(ctx, body, reqEditors...) - if err != nil { - return nil, err } - return ParseVerifyX402PaymentResponse(rsp) + + return response, nil } // ParseListDataTokenBalancesResponse parses an HTTP response from a ListDataTokenBalancesWithResponse call @@ -23827,18 +31043,173 @@ func ParseCreateWebhookSubscriptionResponse(rsp *http.Response) (*CreateWebhookS return nil, err } - response := &CreateWebhookSubscriptionResponse{ + response := &CreateWebhookSubscriptionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest WebhookSubscriptionResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON429 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + } + + return response, nil +} + +// ParseDeleteWebhookSubscriptionResponse parses an HTTP response from a DeleteWebhookSubscriptionWithResponse call +func ParseDeleteWebhookSubscriptionResponse(rsp *http.Response) (*DeleteWebhookSubscriptionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteWebhookSubscriptionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON429 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + } + + return response, nil +} + +// ParseGetWebhookSubscriptionResponse parses an HTTP response from a GetWebhookSubscriptionWithResponse call +func ParseGetWebhookSubscriptionResponse(rsp *http.Response) (*GetWebhookSubscriptionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetWebhookSubscriptionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest WebhookSubscriptionResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON429 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + } + + return response, nil +} + +// ParseUpdateWebhookSubscriptionResponse parses an HTTP response from a UpdateWebhookSubscriptionWithResponse call +func ParseUpdateWebhookSubscriptionResponse(rsp *http.Response) (*UpdateWebhookSubscriptionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &UpdateWebhookSubscriptionResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: var dest WebhookSubscriptionResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON201 = &dest + response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest Error @@ -23854,6 +31225,13 @@ func ParseCreateWebhookSubscriptionResponse(rsp *http.Response) (*CreateWebhookS } response.JSON401 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -23873,20 +31251,34 @@ func ParseCreateWebhookSubscriptionResponse(rsp *http.Response) (*CreateWebhookS return response, nil } -// ParseDeleteWebhookSubscriptionResponse parses an HTTP response from a DeleteWebhookSubscriptionWithResponse call -func ParseDeleteWebhookSubscriptionResponse(rsp *http.Response) (*DeleteWebhookSubscriptionResponse, error) { +// ParseListWebhookSubscriptionEventsResponse parses an HTTP response from a ListWebhookSubscriptionEventsWithResponse call +func ParseListWebhookSubscriptionEventsResponse(rsp *http.Response) (*ListWebhookSubscriptionEventsResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &DeleteWebhookSubscriptionResponse{ + response := &ListWebhookSubscriptionEventsResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest WebhookEventListResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: var dest UnauthorizedError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -23920,50 +31312,49 @@ func ParseDeleteWebhookSubscriptionResponse(rsp *http.Response) (*DeleteWebhookS return response, nil } -// ParseGetWebhookSubscriptionResponse parses an HTTP response from a GetWebhookSubscriptionWithResponse call -func ParseGetWebhookSubscriptionResponse(rsp *http.Response) (*GetWebhookSubscriptionResponse, error) { +// ParseListDepositDestinationsResponse parses an HTTP response from a ListDepositDestinationsWithResponse call +func ParseListDepositDestinationsResponse(rsp *http.Response) (*ListDepositDestinationsResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetWebhookSubscriptionResponse{ + response := &ListDepositDestinationsResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest WebhookSubscriptionResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest + var dest struct { + // DepositDestinations The list of deposit destinations. + DepositDestinations []DepositDestination `json:"depositDestinations"` - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: - var dest UnauthorizedError + // NextPageToken The token for the next page of items, if any. + NextPageToken *string `json:"nextPageToken,omitempty"` + } if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON401 = &dest + response.JSON200 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON404 = &dest + response.JSON400 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON429 = &dest + response.JSON401 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: - var dest InternalServerError + var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -23974,26 +31365,26 @@ func ParseGetWebhookSubscriptionResponse(rsp *http.Response) (*GetWebhookSubscri return response, nil } -// ParseUpdateWebhookSubscriptionResponse parses an HTTP response from a UpdateWebhookSubscriptionWithResponse call -func ParseUpdateWebhookSubscriptionResponse(rsp *http.Response) (*UpdateWebhookSubscriptionResponse, error) { +// ParseCreateDepositDestinationResponse parses an HTTP response from a CreateDepositDestinationWithResponse call +func ParseCreateDepositDestinationResponse(rsp *http.Response) (*CreateDepositDestinationResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &UpdateWebhookSubscriptionResponse{ + response := &CreateDepositDestinationResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest WebhookSubscriptionResponse + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest DepositDestination if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON200 = &dest + response.JSON201 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest Error @@ -24003,7 +31394,7 @@ func ParseUpdateWebhookSubscriptionResponse(rsp *http.Response) (*UpdateWebhookS response.JSON400 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: - var dest UnauthorizedError + var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -24016,41 +31407,48 @@ func ParseUpdateWebhookSubscriptionResponse(rsp *http.Response) (*UpdateWebhookS } response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: - var dest Error + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 422: + var dest IdempotencyError if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON429 = &dest + response.JSON422 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: - var dest InternalServerError + var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } response.JSON500 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest EndpointUnavailableError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON503 = &dest + } return response, nil } -// ParseListWebhookSubscriptionEventsResponse parses an HTTP response from a ListWebhookSubscriptionEventsWithResponse call -func ParseListWebhookSubscriptionEventsResponse(rsp *http.Response) (*ListWebhookSubscriptionEventsResponse, error) { +// ParseGetDepositDestinationByIdResponse parses an HTTP response from a GetDepositDestinationByIdWithResponse call +func ParseGetDepositDestinationByIdResponse(rsp *http.Response) (*GetDepositDestinationByIdResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ListWebhookSubscriptionEventsResponse{ + response := &GetDepositDestinationByIdResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest WebhookEventListResponse + var dest DepositDestination if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -24064,7 +31462,7 @@ func ParseListWebhookSubscriptionEventsResponse(rsp *http.Response) (*ListWebhoo response.JSON400 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: - var dest UnauthorizedError + var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -24077,15 +31475,8 @@ func ParseListWebhookSubscriptionEventsResponse(rsp *http.Response) (*ListWebhoo } response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: - var dest Error - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON429 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: - var dest InternalServerError + var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -24476,6 +31867,13 @@ func ParseCreateEvmEip7702DelegationWithEndUserAccountResponse(rsp *http.Respons } response.JSON402 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest DelegationForbiddenError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -24576,7 +31974,7 @@ func ParseSendEvmTransactionWithEndUserAccountResponse(rsp *http.Response) (*Sen response.JSON402 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: - var dest Error + var dest DelegationForbiddenError if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -24667,6 +32065,13 @@ func ParseSignEvmMessageWithEndUserAccountResponse(rsp *http.Response) (*SignEvm } response.JSON402 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest DelegationForbiddenError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -24760,7 +32165,7 @@ func ParseSignEvmTransactionWithEndUserAccountResponse(rsp *http.Response) (*Sig response.JSON402 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: - var dest Error + var dest DelegationForbiddenError if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -24858,6 +32263,13 @@ func ParseSignEvmTypedDataWithEndUserAccountResponse(rsp *http.Response) (*SignE } response.JSON402 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest DelegationForbiddenError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -24941,7 +32353,7 @@ func ParseSendUserOperationWithEndUserAccountResponse(rsp *http.Response) (*Send response.JSON402 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: - var dest Error + var dest DelegationForbiddenError if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -25004,10 +32416,10 @@ func ParseSendEvmAssetWithEndUserAccountResponse(rsp *http.Response) (*SendEvmAs case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: var dest struct { // TransactionHash The hash of the transaction, as a 0x-prefixed hex string. Populated for EOA accounts. Null for Smart Accounts (use userOpHash instead). - TransactionHash *string `json:"transactionHash"` + TransactionHash *string `json:"transactionHash,omitempty"` // UserOpHash The hash of the user operation, as a 0x-prefixed hex string. Populated for Smart Accounts. Null for EOA accounts (use transactionHash instead). - UserOpHash *string `json:"userOpHash"` + UserOpHash *string `json:"userOpHash,omitempty"` } if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err @@ -25035,6 +32447,13 @@ func ParseSendEvmAssetWithEndUserAccountResponse(rsp *http.Response) (*SendEvmAs } response.JSON402 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest DelegationForbiddenError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -25121,7 +32540,7 @@ func ParseSendSolanaTransactionWithEndUserAccountResponse(rsp *http.Response) (* response.JSON402 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: - var dest Error + var dest DelegationForbiddenError if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -25212,6 +32631,13 @@ func ParseSignSolanaMessageWithEndUserAccountResponse(rsp *http.Response) (*Sign } response.JSON402 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest DelegationForbiddenError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -25305,7 +32731,7 @@ func ParseSignSolanaTransactionWithEndUserAccountResponse(rsp *http.Response) (* response.JSON402 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: - var dest Error + var dest DelegationForbiddenError if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -25403,6 +32829,13 @@ func ParseSendSolanaAssetWithEndUserAccountResponse(rsp *http.Response) (*SendSo } response.JSON402 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest DelegationForbiddenError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -28498,7 +35931,127 @@ func ParseGetOnrampOrderByIdResponse(rsp *http.Response) (*GetOnrampOrderByIdRes if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON200 = &dest + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: + var dest RateLimitExceeded + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON429 = &dest + + } + + return response, nil +} + +// ParseCreateOnrampSessionResponse parses an HTTP response from a CreateOnrampSessionWithResponse call +func ParseCreateOnrampSessionResponse(rsp *http.Response) (*CreateOnrampSessionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateOnrampSessionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest struct { + // Quote Quote information with pricing details for the crypto purchase. + Quote *OnrampQuote `json:"quote,omitempty"` + + // Session An onramp session containing a ready-to-use onramp URL. + Session OnrampSession `json:"session"` + } + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: + var dest RateLimitExceeded + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON429 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + } + + return response, nil +} + +// ParseListPaymentMethodsResponse parses an HTTP response from a ListPaymentMethodsWithResponse call +func ParseListPaymentMethodsResponse(rsp *http.Response) (*ListPaymentMethodsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListPaymentMethodsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest struct { + // NextPageToken The token for the next page of items, if any. + NextPageToken *string `json:"nextPageToken,omitempty"` + + // PaymentMethods The list of payment methods. + PaymentMethods []PaymentMethodsPaymentMethod `json:"paymentMethods"` + } + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: var dest UnauthorizedError @@ -28507,51 +36060,38 @@ func ParseGetOnrampOrderByIdResponse(rsp *http.Response) (*GetOnrampOrderByIdRes } response.JSON401 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: - var dest Error - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON404 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: - var dest RateLimitExceeded + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerError if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON429 = &dest + response.JSON500 = &dest } return response, nil } -// ParseCreateOnrampSessionResponse parses an HTTP response from a CreateOnrampSessionWithResponse call -func ParseCreateOnrampSessionResponse(rsp *http.Response) (*CreateOnrampSessionResponse, error) { +// ParseGetPaymentMethodResponse parses an HTTP response from a GetPaymentMethodWithResponse call +func ParseGetPaymentMethodResponse(rsp *http.Response) (*GetPaymentMethodResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &CreateOnrampSessionResponse{ + response := &GetPaymentMethodResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: - var dest struct { - // Quote Quote information with pricing details for the crypto purchase. - Quote *OnrampQuote `json:"quote,omitempty"` - - // Session An onramp session containing a ready-to-use onramp URL. - Session OnrampSession `json:"session"` - } + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest PaymentMethodsPaymentMethod if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON201 = &dest + response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest Error @@ -28567,12 +36107,12 @@ func ParseCreateOnrampSessionResponse(rsp *http.Response) (*CreateOnrampSessionR } response.JSON401 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: - var dest RateLimitExceeded + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON429 = &dest + response.JSON404 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalServerError @@ -29909,6 +37449,247 @@ func ParseListSolanaTokenBalancesResponse(rsp *http.Response) (*ListSolanaTokenB return response, nil } +// ParseListTransfersResponse parses an HTTP response from a ListTransfersWithResponse call +func ParseListTransfersResponse(rsp *http.Response) (*ListTransfersResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListTransfersResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest struct { + // NextPageToken The token for the next page of items, if any. + NextPageToken *string `json:"nextPageToken,omitempty"` + + // Transfers The list of transfers. + Transfers []Transfer `json:"transfers"` + } + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + } + + return response, nil +} + +// ParseCreateTransferResponse parses an HTTP response from a CreateTransferWithResponse call +func ParseCreateTransferResponse(rsp *http.Response) (*CreateTransferResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateTransferResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Transfer + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 422: + var dest IdempotencyError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON422 = &dest + + } + + return response, nil +} + +// ParseGetTransferByIdResponse parses an HTTP response from a GetTransferByIdWithResponse call +func ParseGetTransferByIdResponse(rsp *http.Response) (*GetTransferByIdResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetTransferByIdResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Transfer + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseExecuteFundTransferResponse parses an HTTP response from a ExecuteFundTransferWithResponse call +func ParseExecuteFundTransferResponse(rsp *http.Response) (*ExecuteFundTransferResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ExecuteFundTransferResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Transfer + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 422: + var dest IdempotencyError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON422 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON429 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 502: + var dest BadGatewayError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON502 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON503 = &dest + + } + + return response, nil +} + +// ParseSubmitDepositTravelRuleResponse parses an HTTP response from a SubmitDepositTravelRuleWithResponse call +func ParseSubmitDepositTravelRuleResponse(rsp *http.Response) (*SubmitDepositTravelRuleResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &SubmitDepositTravelRuleResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest DepositTravelRuleResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 422: + var dest IdempotencyError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON422 = &dest + + } + + return response, nil +} + // ParsePostX402DiscoveryMcpResponse parses an HTTP response from a PostX402DiscoveryMcpWithResponse call func ParsePostX402DiscoveryMcpResponse(rsp *http.Response) (*PostX402DiscoveryMcpResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) diff --git a/java/scripts/fix-generated-code.sh b/java/scripts/fix-generated-code.sh index b2fb5a5ff..204b0b2ed 100755 --- a/java/scripts/fix-generated-code.sh +++ b/java/scripts/fix-generated-code.sh @@ -33,6 +33,7 @@ TYPES=( "CreateEndUserEvmSwapCriteria" "SendEndUserEvmAssetCriteria" "SendEndUserSolAssetCriteria" + "TransferFees" ) for TYPE in "${TYPES[@]}"; do diff --git a/java/src/main/java/com/coinbase/cdp/openapi/api/AccountsApi.java b/java/src/main/java/com/coinbase/cdp/openapi/api/AccountsApi.java new file mode 100644 index 000000000..a63522978 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/api/AccountsApi.java @@ -0,0 +1,566 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.coinbase.cdp.openapi.api; + +import com.coinbase.cdp.openapi.ApiClient; +import com.coinbase.cdp.openapi.ApiException; +import com.coinbase.cdp.openapi.ApiResponse; +import com.coinbase.cdp.openapi.Pair; + +import com.coinbase.cdp.openapi.model.Account; +import com.coinbase.cdp.openapi.model.AccountType; +import com.coinbase.cdp.openapi.model.Balance; +import com.coinbase.cdp.openapi.model.CreateAccountRequest; +import com.coinbase.cdp.openapi.model.Error; +import com.coinbase.cdp.openapi.model.ListBalances200Response; +import com.coinbase.cdp.openapi.model.ListFoundationAccounts200Response; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.InputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.net.http.HttpRequest; +import java.nio.channels.Channels; +import java.nio.channels.Pipe; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; + +import java.util.ArrayList; +import java.util.StringJoiner; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class AccountsApi { + private final HttpClient memberVarHttpClient; + private final ObjectMapper memberVarObjectMapper; + private final String memberVarBaseUri; + private final Consumer memberVarInterceptor; + private final Duration memberVarReadTimeout; + private final Consumer> memberVarResponseInterceptor; + private final Consumer> memberVarAsyncResponseInterceptor; + + public AccountsApi() { + this(new ApiClient()); + } + + public AccountsApi(ApiClient apiClient) { + memberVarHttpClient = apiClient.getHttpClient(); + memberVarObjectMapper = apiClient.getObjectMapper(); + memberVarBaseUri = apiClient.getBaseUri(); + memberVarInterceptor = apiClient.getRequestInterceptor(); + memberVarReadTimeout = apiClient.getReadTimeout(); + memberVarResponseInterceptor = apiClient.getResponseInterceptor(); + memberVarAsyncResponseInterceptor = apiClient.getAsyncResponseInterceptor(); + } + + protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + String message = formatExceptionMessage(operationId, response.statusCode(), body); + return new ApiException(response.statusCode(), message, response.headers(), body); + } + + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; + } + return operationId + " call failed with: " + statusCode + " - " + body; + } + + /** + * Create account + * Create an account for your Entity. Support for creating Customer-owned accounts is in development. + * @param createAccountRequest (required) + * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) + * @return Account + * @throws ApiException if fails to make API call + */ + public Account createFoundationAccount(CreateAccountRequest createAccountRequest, String xIdempotencyKey) throws ApiException { + ApiResponse localVarResponse = createFoundationAccountWithHttpInfo(createAccountRequest, xIdempotencyKey); + return localVarResponse.getData(); + } + + /** + * Create account + * Create an account for your Entity. Support for creating Customer-owned accounts is in development. + * @param createAccountRequest (required) + * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) + * @return ApiResponse<Account> + * @throws ApiException if fails to make API call + */ + public ApiResponse createFoundationAccountWithHttpInfo(CreateAccountRequest createAccountRequest, String xIdempotencyKey) throws ApiException { + HttpRequest.Builder localVarRequestBuilder = createFoundationAccountRequestBuilder(createAccountRequest, xIdempotencyKey); + try { + HttpResponse localVarResponse = memberVarHttpClient.send( + localVarRequestBuilder.build(), + HttpResponse.BodyHandlers.ofInputStream()); + if (memberVarResponseInterceptor != null) { + memberVarResponseInterceptor.accept(localVarResponse); + } + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("createFoundationAccount", localVarResponse); + } + if (localVarResponse.body() == null) { + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + null + ); + } + + String responseBody = new String(localVarResponse.body().readAllBytes()); + localVarResponse.body().close(); + + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + responseBody.isBlank()? null: memberVarObjectMapper.readValue(responseBody, new TypeReference() {}) + ); + } finally { + } + } catch (IOException e) { + throw new ApiException(e); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ApiException(e); + } + } + + private HttpRequest.Builder createFoundationAccountRequestBuilder(CreateAccountRequest createAccountRequest, String xIdempotencyKey) throws ApiException { + // verify the required parameter 'createAccountRequest' is set + if (createAccountRequest == null) { + throw new ApiException(400, "Missing the required parameter 'createAccountRequest' when calling createFoundationAccount"); + } + + HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); + + String localVarPath = "/v2/accounts"; + + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); + + if (xIdempotencyKey != null) { + localVarRequestBuilder.header("X-Idempotency-Key", xIdempotencyKey.toString()); + } + localVarRequestBuilder.header("Content-Type", "application/json"); + localVarRequestBuilder.header("Accept", "application/json"); + + try { + byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(createAccountRequest); + localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); + } catch (IOException e) { + throw new ApiException(e); + } + if (memberVarReadTimeout != null) { + localVarRequestBuilder.timeout(memberVarReadTimeout); + } + if (memberVarInterceptor != null) { + memberVarInterceptor.accept(localVarRequestBuilder); + } + return localVarRequestBuilder; + } + + /** + * Get balance for account + * Get the balance for an account by asset. + * @param accountId The unique identifier of the account. (required) + * @param asset The symbol of the asset. (required) + * @return Balance + * @throws ApiException if fails to make API call + */ + public Balance getBalanceByAsset(String accountId, String asset) throws ApiException { + ApiResponse localVarResponse = getBalanceByAssetWithHttpInfo(accountId, asset); + return localVarResponse.getData(); + } + + /** + * Get balance for account + * Get the balance for an account by asset. + * @param accountId The unique identifier of the account. (required) + * @param asset The symbol of the asset. (required) + * @return ApiResponse<Balance> + * @throws ApiException if fails to make API call + */ + public ApiResponse getBalanceByAssetWithHttpInfo(String accountId, String asset) throws ApiException { + HttpRequest.Builder localVarRequestBuilder = getBalanceByAssetRequestBuilder(accountId, asset); + try { + HttpResponse localVarResponse = memberVarHttpClient.send( + localVarRequestBuilder.build(), + HttpResponse.BodyHandlers.ofInputStream()); + if (memberVarResponseInterceptor != null) { + memberVarResponseInterceptor.accept(localVarResponse); + } + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("getBalanceByAsset", localVarResponse); + } + if (localVarResponse.body() == null) { + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + null + ); + } + + String responseBody = new String(localVarResponse.body().readAllBytes()); + localVarResponse.body().close(); + + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + responseBody.isBlank()? null: memberVarObjectMapper.readValue(responseBody, new TypeReference() {}) + ); + } finally { + } + } catch (IOException e) { + throw new ApiException(e); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ApiException(e); + } + } + + private HttpRequest.Builder getBalanceByAssetRequestBuilder(String accountId, String asset) throws ApiException { + // verify the required parameter 'accountId' is set + if (accountId == null) { + throw new ApiException(400, "Missing the required parameter 'accountId' when calling getBalanceByAsset"); + } + // verify the required parameter 'asset' is set + if (asset == null) { + throw new ApiException(400, "Missing the required parameter 'asset' when calling getBalanceByAsset"); + } + + HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); + + String localVarPath = "/v2/accounts/{accountId}/balances/{asset}" + .replace("{accountId}", ApiClient.urlEncode(accountId.toString())) + .replace("{asset}", ApiClient.urlEncode(asset.toString())); + + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); + + localVarRequestBuilder.header("Accept", "application/json"); + + localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); + if (memberVarReadTimeout != null) { + localVarRequestBuilder.timeout(memberVarReadTimeout); + } + if (memberVarInterceptor != null) { + memberVarInterceptor.accept(localVarRequestBuilder); + } + return localVarRequestBuilder; + } + + /** + * Get account + * Get an account by its ID. + * @param accountId The ID of the account to retrieve. (required) + * @return Account + * @throws ApiException if fails to make API call + */ + public Account getFoundationAccountById(String accountId) throws ApiException { + ApiResponse localVarResponse = getFoundationAccountByIdWithHttpInfo(accountId); + return localVarResponse.getData(); + } + + /** + * Get account + * Get an account by its ID. + * @param accountId The ID of the account to retrieve. (required) + * @return ApiResponse<Account> + * @throws ApiException if fails to make API call + */ + public ApiResponse getFoundationAccountByIdWithHttpInfo(String accountId) throws ApiException { + HttpRequest.Builder localVarRequestBuilder = getFoundationAccountByIdRequestBuilder(accountId); + try { + HttpResponse localVarResponse = memberVarHttpClient.send( + localVarRequestBuilder.build(), + HttpResponse.BodyHandlers.ofInputStream()); + if (memberVarResponseInterceptor != null) { + memberVarResponseInterceptor.accept(localVarResponse); + } + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("getFoundationAccountById", localVarResponse); + } + if (localVarResponse.body() == null) { + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + null + ); + } + + String responseBody = new String(localVarResponse.body().readAllBytes()); + localVarResponse.body().close(); + + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + responseBody.isBlank()? null: memberVarObjectMapper.readValue(responseBody, new TypeReference() {}) + ); + } finally { + } + } catch (IOException e) { + throw new ApiException(e); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ApiException(e); + } + } + + private HttpRequest.Builder getFoundationAccountByIdRequestBuilder(String accountId) throws ApiException { + // verify the required parameter 'accountId' is set + if (accountId == null) { + throw new ApiException(400, "Missing the required parameter 'accountId' when calling getFoundationAccountById"); + } + + HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); + + String localVarPath = "/v2/accounts/{accountId}" + .replace("{accountId}", ApiClient.urlEncode(accountId.toString())); + + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); + + localVarRequestBuilder.header("Accept", "application/json"); + + localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); + if (memberVarReadTimeout != null) { + localVarRequestBuilder.timeout(memberVarReadTimeout); + } + if (memberVarInterceptor != null) { + memberVarInterceptor.accept(localVarRequestBuilder); + } + return localVarRequestBuilder; + } + + /** + * List balances for account + * List the balances for an account. Results are sorted by native-fiat equivalent balance in descending order. + * @param accountId The unique identifier of the account. (required) + * @param pageSize The number of resources to return per page. (optional, default to 20) + * @param pageToken The token for the next page of resources, if any. (optional) + * @return ListBalances200Response + * @throws ApiException if fails to make API call + */ + public ListBalances200Response listBalances(String accountId, Integer pageSize, String pageToken) throws ApiException { + ApiResponse localVarResponse = listBalancesWithHttpInfo(accountId, pageSize, pageToken); + return localVarResponse.getData(); + } + + /** + * List balances for account + * List the balances for an account. Results are sorted by native-fiat equivalent balance in descending order. + * @param accountId The unique identifier of the account. (required) + * @param pageSize The number of resources to return per page. (optional, default to 20) + * @param pageToken The token for the next page of resources, if any. (optional) + * @return ApiResponse<ListBalances200Response> + * @throws ApiException if fails to make API call + */ + public ApiResponse listBalancesWithHttpInfo(String accountId, Integer pageSize, String pageToken) throws ApiException { + HttpRequest.Builder localVarRequestBuilder = listBalancesRequestBuilder(accountId, pageSize, pageToken); + try { + HttpResponse localVarResponse = memberVarHttpClient.send( + localVarRequestBuilder.build(), + HttpResponse.BodyHandlers.ofInputStream()); + if (memberVarResponseInterceptor != null) { + memberVarResponseInterceptor.accept(localVarResponse); + } + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("listBalances", localVarResponse); + } + if (localVarResponse.body() == null) { + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + null + ); + } + + String responseBody = new String(localVarResponse.body().readAllBytes()); + localVarResponse.body().close(); + + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + responseBody.isBlank()? null: memberVarObjectMapper.readValue(responseBody, new TypeReference() {}) + ); + } finally { + } + } catch (IOException e) { + throw new ApiException(e); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ApiException(e); + } + } + + private HttpRequest.Builder listBalancesRequestBuilder(String accountId, Integer pageSize, String pageToken) throws ApiException { + // verify the required parameter 'accountId' is set + if (accountId == null) { + throw new ApiException(400, "Missing the required parameter 'accountId' when calling listBalances"); + } + + HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); + + String localVarPath = "/v2/accounts/{accountId}/balances" + .replace("{accountId}", ApiClient.urlEncode(accountId.toString())); + + List localVarQueryParams = new ArrayList<>(); + StringJoiner localVarQueryStringJoiner = new StringJoiner("&"); + String localVarQueryParameterBaseName; + localVarQueryParameterBaseName = "pageSize"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("pageSize", pageSize)); + localVarQueryParameterBaseName = "pageToken"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("pageToken", pageToken)); + + if (!localVarQueryParams.isEmpty() || localVarQueryStringJoiner.length() != 0) { + StringJoiner queryJoiner = new StringJoiner("&"); + localVarQueryParams.forEach(p -> queryJoiner.add(p.getName() + '=' + p.getValue())); + if (localVarQueryStringJoiner.length() != 0) { + queryJoiner.add(localVarQueryStringJoiner.toString()); + } + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath + '?' + queryJoiner.toString())); + } else { + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); + } + + localVarRequestBuilder.header("Accept", "application/json"); + + localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); + if (memberVarReadTimeout != null) { + localVarRequestBuilder.timeout(memberVarReadTimeout); + } + if (memberVarInterceptor != null) { + memberVarInterceptor.accept(localVarRequestBuilder); + } + return localVarRequestBuilder; + } + + /** + * List accounts + * List all accounts. The API will return all accounts that the API Key has Permissions to access. You can filter the results by using query parameters, which will be treated as a single conjunction (i.e. AND). Results are sorted by creation date in descending order (newest first). + * @param pageSize The number of resources to return per page. (optional, default to 20) + * @param pageToken The token for the next page of resources, if any. (optional) + * @param type Filter accounts by account type. When omitted, accounts of any type are returned. Combined with `owner` using AND. (optional) + * @return ListFoundationAccounts200Response + * @throws ApiException if fails to make API call + */ + public ListFoundationAccounts200Response listFoundationAccounts(Integer pageSize, String pageToken, AccountType type) throws ApiException { + ApiResponse localVarResponse = listFoundationAccountsWithHttpInfo(pageSize, pageToken, type); + return localVarResponse.getData(); + } + + /** + * List accounts + * List all accounts. The API will return all accounts that the API Key has Permissions to access. You can filter the results by using query parameters, which will be treated as a single conjunction (i.e. AND). Results are sorted by creation date in descending order (newest first). + * @param pageSize The number of resources to return per page. (optional, default to 20) + * @param pageToken The token for the next page of resources, if any. (optional) + * @param type Filter accounts by account type. When omitted, accounts of any type are returned. Combined with `owner` using AND. (optional) + * @return ApiResponse<ListFoundationAccounts200Response> + * @throws ApiException if fails to make API call + */ + public ApiResponse listFoundationAccountsWithHttpInfo(Integer pageSize, String pageToken, AccountType type) throws ApiException { + HttpRequest.Builder localVarRequestBuilder = listFoundationAccountsRequestBuilder(pageSize, pageToken, type); + try { + HttpResponse localVarResponse = memberVarHttpClient.send( + localVarRequestBuilder.build(), + HttpResponse.BodyHandlers.ofInputStream()); + if (memberVarResponseInterceptor != null) { + memberVarResponseInterceptor.accept(localVarResponse); + } + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("listFoundationAccounts", localVarResponse); + } + if (localVarResponse.body() == null) { + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + null + ); + } + + String responseBody = new String(localVarResponse.body().readAllBytes()); + localVarResponse.body().close(); + + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + responseBody.isBlank()? null: memberVarObjectMapper.readValue(responseBody, new TypeReference() {}) + ); + } finally { + } + } catch (IOException e) { + throw new ApiException(e); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ApiException(e); + } + } + + private HttpRequest.Builder listFoundationAccountsRequestBuilder(Integer pageSize, String pageToken, AccountType type) throws ApiException { + + HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); + + String localVarPath = "/v2/accounts"; + + List localVarQueryParams = new ArrayList<>(); + StringJoiner localVarQueryStringJoiner = new StringJoiner("&"); + String localVarQueryParameterBaseName; + localVarQueryParameterBaseName = "pageSize"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("pageSize", pageSize)); + localVarQueryParameterBaseName = "pageToken"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("pageToken", pageToken)); + localVarQueryParameterBaseName = "type"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("type", type)); + + if (!localVarQueryParams.isEmpty() || localVarQueryStringJoiner.length() != 0) { + StringJoiner queryJoiner = new StringJoiner("&"); + localVarQueryParams.forEach(p -> queryJoiner.add(p.getName() + '=' + p.getValue())); + if (localVarQueryStringJoiner.length() != 0) { + queryJoiner.add(localVarQueryStringJoiner.toString()); + } + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath + '?' + queryJoiner.toString())); + } else { + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); + } + + localVarRequestBuilder.header("Accept", "application/json"); + + localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); + if (memberVarReadTimeout != null) { + localVarRequestBuilder.timeout(memberVarReadTimeout); + } + if (memberVarInterceptor != null) { + memberVarInterceptor.accept(localVarRequestBuilder); + } + return localVarRequestBuilder; + } + +} diff --git a/java/src/main/java/com/coinbase/cdp/openapi/api/DepositDestinationsApi.java b/java/src/main/java/com/coinbase/cdp/openapi/api/DepositDestinationsApi.java new file mode 100644 index 000000000..c67458caa --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/api/DepositDestinationsApi.java @@ -0,0 +1,379 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.coinbase.cdp.openapi.api; + +import com.coinbase.cdp.openapi.ApiClient; +import com.coinbase.cdp.openapi.ApiException; +import com.coinbase.cdp.openapi.ApiResponse; +import com.coinbase.cdp.openapi.Pair; + +import com.coinbase.cdp.openapi.model.CreateDepositDestinationRequest; +import com.coinbase.cdp.openapi.model.DepositDestination; +import com.coinbase.cdp.openapi.model.Error; +import com.coinbase.cdp.openapi.model.ListDepositDestinations200Response; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.InputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.net.http.HttpRequest; +import java.nio.channels.Channels; +import java.nio.channels.Pipe; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; + +import java.util.ArrayList; +import java.util.StringJoiner; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class DepositDestinationsApi { + private final HttpClient memberVarHttpClient; + private final ObjectMapper memberVarObjectMapper; + private final String memberVarBaseUri; + private final Consumer memberVarInterceptor; + private final Duration memberVarReadTimeout; + private final Consumer> memberVarResponseInterceptor; + private final Consumer> memberVarAsyncResponseInterceptor; + + public DepositDestinationsApi() { + this(new ApiClient()); + } + + public DepositDestinationsApi(ApiClient apiClient) { + memberVarHttpClient = apiClient.getHttpClient(); + memberVarObjectMapper = apiClient.getObjectMapper(); + memberVarBaseUri = apiClient.getBaseUri(); + memberVarInterceptor = apiClient.getRequestInterceptor(); + memberVarReadTimeout = apiClient.getReadTimeout(); + memberVarResponseInterceptor = apiClient.getResponseInterceptor(); + memberVarAsyncResponseInterceptor = apiClient.getAsyncResponseInterceptor(); + } + + protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + String message = formatExceptionMessage(operationId, response.statusCode(), body); + return new ApiException(response.statusCode(), message, response.headers(), body); + } + + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; + } + return operationId + " call failed with: " + statusCode + " - " + body; + } + + /** + * Create deposit destination + * Create a new deposit destination for an account. A deposit destination is a cryptocurrency address that can be used to receive funds. The address will be generated for the specified network. + * @param createDepositDestinationRequest (required) + * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) + * @return DepositDestination + * @throws ApiException if fails to make API call + */ + public DepositDestination createDepositDestination(CreateDepositDestinationRequest createDepositDestinationRequest, String xIdempotencyKey) throws ApiException { + ApiResponse localVarResponse = createDepositDestinationWithHttpInfo(createDepositDestinationRequest, xIdempotencyKey); + return localVarResponse.getData(); + } + + /** + * Create deposit destination + * Create a new deposit destination for an account. A deposit destination is a cryptocurrency address that can be used to receive funds. The address will be generated for the specified network. + * @param createDepositDestinationRequest (required) + * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) + * @return ApiResponse<DepositDestination> + * @throws ApiException if fails to make API call + */ + public ApiResponse createDepositDestinationWithHttpInfo(CreateDepositDestinationRequest createDepositDestinationRequest, String xIdempotencyKey) throws ApiException { + HttpRequest.Builder localVarRequestBuilder = createDepositDestinationRequestBuilder(createDepositDestinationRequest, xIdempotencyKey); + try { + HttpResponse localVarResponse = memberVarHttpClient.send( + localVarRequestBuilder.build(), + HttpResponse.BodyHandlers.ofInputStream()); + if (memberVarResponseInterceptor != null) { + memberVarResponseInterceptor.accept(localVarResponse); + } + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("createDepositDestination", localVarResponse); + } + if (localVarResponse.body() == null) { + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + null + ); + } + + String responseBody = new String(localVarResponse.body().readAllBytes()); + localVarResponse.body().close(); + + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + responseBody.isBlank()? null: memberVarObjectMapper.readValue(responseBody, new TypeReference() {}) + ); + } finally { + } + } catch (IOException e) { + throw new ApiException(e); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ApiException(e); + } + } + + private HttpRequest.Builder createDepositDestinationRequestBuilder(CreateDepositDestinationRequest createDepositDestinationRequest, String xIdempotencyKey) throws ApiException { + // verify the required parameter 'createDepositDestinationRequest' is set + if (createDepositDestinationRequest == null) { + throw new ApiException(400, "Missing the required parameter 'createDepositDestinationRequest' when calling createDepositDestination"); + } + + HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); + + String localVarPath = "/v2/deposit-destinations"; + + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); + + if (xIdempotencyKey != null) { + localVarRequestBuilder.header("X-Idempotency-Key", xIdempotencyKey.toString()); + } + localVarRequestBuilder.header("Content-Type", "application/json"); + localVarRequestBuilder.header("Accept", "application/json"); + + try { + byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(createDepositDestinationRequest); + localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); + } catch (IOException e) { + throw new ApiException(e); + } + if (memberVarReadTimeout != null) { + localVarRequestBuilder.timeout(memberVarReadTimeout); + } + if (memberVarInterceptor != null) { + memberVarInterceptor.accept(localVarRequestBuilder); + } + return localVarRequestBuilder; + } + + /** + * Get deposit destination + * Get a specific deposit destination by its ID. + * @param depositDestinationId The ID of the deposit address to retrieve. (required) + * @return DepositDestination + * @throws ApiException if fails to make API call + */ + public DepositDestination getDepositDestinationById(String depositDestinationId) throws ApiException { + ApiResponse localVarResponse = getDepositDestinationByIdWithHttpInfo(depositDestinationId); + return localVarResponse.getData(); + } + + /** + * Get deposit destination + * Get a specific deposit destination by its ID. + * @param depositDestinationId The ID of the deposit address to retrieve. (required) + * @return ApiResponse<DepositDestination> + * @throws ApiException if fails to make API call + */ + public ApiResponse getDepositDestinationByIdWithHttpInfo(String depositDestinationId) throws ApiException { + HttpRequest.Builder localVarRequestBuilder = getDepositDestinationByIdRequestBuilder(depositDestinationId); + try { + HttpResponse localVarResponse = memberVarHttpClient.send( + localVarRequestBuilder.build(), + HttpResponse.BodyHandlers.ofInputStream()); + if (memberVarResponseInterceptor != null) { + memberVarResponseInterceptor.accept(localVarResponse); + } + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("getDepositDestinationById", localVarResponse); + } + if (localVarResponse.body() == null) { + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + null + ); + } + + String responseBody = new String(localVarResponse.body().readAllBytes()); + localVarResponse.body().close(); + + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + responseBody.isBlank()? null: memberVarObjectMapper.readValue(responseBody, new TypeReference() {}) + ); + } finally { + } + } catch (IOException e) { + throw new ApiException(e); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ApiException(e); + } + } + + private HttpRequest.Builder getDepositDestinationByIdRequestBuilder(String depositDestinationId) throws ApiException { + // verify the required parameter 'depositDestinationId' is set + if (depositDestinationId == null) { + throw new ApiException(400, "Missing the required parameter 'depositDestinationId' when calling getDepositDestinationById"); + } + + HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); + + String localVarPath = "/v2/deposit-destinations/{depositDestinationId}" + .replace("{depositDestinationId}", ApiClient.urlEncode(depositDestinationId.toString())); + + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); + + localVarRequestBuilder.header("Accept", "application/json"); + + localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); + if (memberVarReadTimeout != null) { + localVarRequestBuilder.timeout(memberVarReadTimeout); + } + if (memberVarInterceptor != null) { + memberVarInterceptor.accept(localVarRequestBuilder); + } + return localVarRequestBuilder; + } + + /** + * List deposit destinations + * List deposit destinations. You can optionally filter the results by type, account ID, network, or cryptocurrency address. Results are sorted by creation date in descending order (newest first). + * @param accountId Filter deposit destinations by account ID. (optional) + * @param address Filter deposit destinations by the cryptocurrency address. (optional) + * @param type Filter deposit destinations by type. (optional) + * @param network Filter deposit destinations by network. (optional) + * @param pageSize The number of resources to return per page. (optional, default to 20) + * @param pageToken The token for the next page of resources, if any. (optional) + * @return ListDepositDestinations200Response + * @throws ApiException if fails to make API call + */ + public ListDepositDestinations200Response listDepositDestinations(String accountId, String address, String type, String network, Integer pageSize, String pageToken) throws ApiException { + ApiResponse localVarResponse = listDepositDestinationsWithHttpInfo(accountId, address, type, network, pageSize, pageToken); + return localVarResponse.getData(); + } + + /** + * List deposit destinations + * List deposit destinations. You can optionally filter the results by type, account ID, network, or cryptocurrency address. Results are sorted by creation date in descending order (newest first). + * @param accountId Filter deposit destinations by account ID. (optional) + * @param address Filter deposit destinations by the cryptocurrency address. (optional) + * @param type Filter deposit destinations by type. (optional) + * @param network Filter deposit destinations by network. (optional) + * @param pageSize The number of resources to return per page. (optional, default to 20) + * @param pageToken The token for the next page of resources, if any. (optional) + * @return ApiResponse<ListDepositDestinations200Response> + * @throws ApiException if fails to make API call + */ + public ApiResponse listDepositDestinationsWithHttpInfo(String accountId, String address, String type, String network, Integer pageSize, String pageToken) throws ApiException { + HttpRequest.Builder localVarRequestBuilder = listDepositDestinationsRequestBuilder(accountId, address, type, network, pageSize, pageToken); + try { + HttpResponse localVarResponse = memberVarHttpClient.send( + localVarRequestBuilder.build(), + HttpResponse.BodyHandlers.ofInputStream()); + if (memberVarResponseInterceptor != null) { + memberVarResponseInterceptor.accept(localVarResponse); + } + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("listDepositDestinations", localVarResponse); + } + if (localVarResponse.body() == null) { + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + null + ); + } + + String responseBody = new String(localVarResponse.body().readAllBytes()); + localVarResponse.body().close(); + + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + responseBody.isBlank()? null: memberVarObjectMapper.readValue(responseBody, new TypeReference() {}) + ); + } finally { + } + } catch (IOException e) { + throw new ApiException(e); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ApiException(e); + } + } + + private HttpRequest.Builder listDepositDestinationsRequestBuilder(String accountId, String address, String type, String network, Integer pageSize, String pageToken) throws ApiException { + + HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); + + String localVarPath = "/v2/deposit-destinations"; + + List localVarQueryParams = new ArrayList<>(); + StringJoiner localVarQueryStringJoiner = new StringJoiner("&"); + String localVarQueryParameterBaseName; + localVarQueryParameterBaseName = "accountId"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("accountId", accountId)); + localVarQueryParameterBaseName = "address"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("address", address)); + localVarQueryParameterBaseName = "type"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("type", type)); + localVarQueryParameterBaseName = "network"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("network", network)); + localVarQueryParameterBaseName = "pageSize"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("pageSize", pageSize)); + localVarQueryParameterBaseName = "pageToken"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("pageToken", pageToken)); + + if (!localVarQueryParams.isEmpty() || localVarQueryStringJoiner.length() != 0) { + StringJoiner queryJoiner = new StringJoiner("&"); + localVarQueryParams.forEach(p -> queryJoiner.add(p.getName() + '=' + p.getValue())); + if (localVarQueryStringJoiner.length() != 0) { + queryJoiner.add(localVarQueryStringJoiner.toString()); + } + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath + '?' + queryJoiner.toString())); + } else { + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); + } + + localVarRequestBuilder.header("Accept", "application/json"); + + localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); + if (memberVarReadTimeout != null) { + localVarRequestBuilder.timeout(memberVarReadTimeout); + } + if (memberVarInterceptor != null) { + memberVarInterceptor.accept(localVarRequestBuilder); + } + return localVarRequestBuilder; + } + +} diff --git a/java/src/main/java/com/coinbase/cdp/openapi/api/EmbeddedWalletsApi.java b/java/src/main/java/com/coinbase/cdp/openapi/api/EmbeddedWalletsApi.java index eea644f5f..bc52711e8 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/api/EmbeddedWalletsApi.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/api/EmbeddedWalletsApi.java @@ -106,7 +106,7 @@ private String formatExceptionMessage(String operationId, int statusCode, String } /** - * Create account-scoped delegation for an end user account + * Create account-scoped delegation for end user * Creates an account-scoped delegation that allows a developer to sign on behalf of an end user for a single blockchain account (identified by its address) for the specified duration. The end user must be authenticated to authorize this delegation. Multiple account-scoped delegations may exist concurrently for a single end user (one per canonical account address). Account-scoped and user-scoped delegations cannot coexist for the same user. When the address corresponds to an EVM Smart Account, the delegation is scoped to the Smart Account's owner EOA rather than the Smart Account address itself. This means `/address/{smartAccountAddress}/delegation` and `/address/{ownerEoaAddress}/delegation` resolve to the same delegation, and the 409 `account_scoped_delegation_active` error may be returned when creating via either address if one already exists for the canonical owner. * @param userId The ID of the end user. (required) * @param address The blockchain address of the end user account to scope this delegation to. Format varies by network (e.g., 0x-prefixed for EVM, base58 for Solana). For EVM addresses, matching is case-insensitive. (required) @@ -123,7 +123,7 @@ public GetDelegationForEndUser200Response createDelegationForEndUserAccount(Stri } /** - * Create account-scoped delegation for an end user account + * Create account-scoped delegation for end user * Creates an account-scoped delegation that allows a developer to sign on behalf of an end user for a single blockchain account (identified by its address) for the specified duration. The end user must be authenticated to authorize this delegation. Multiple account-scoped delegations may exist concurrently for a single end user (one per canonical account address). Account-scoped and user-scoped delegations cannot coexist for the same user. When the address corresponds to an EVM Smart Account, the delegation is scoped to the Smart Account's owner EOA rather than the Smart Account address itself. This means `/address/{smartAccountAddress}/delegation` and `/address/{ownerEoaAddress}/delegation` resolve to the same delegation, and the 409 `account_scoped_delegation_active` error may be returned when creating via either address if one already exists for the canonical owner. * @param userId The ID of the end user. (required) * @param address The blockchain address of the end user account to scope this delegation to. Format varies by network (e.g., 0x-prefixed for EVM, base58 for Solana). For EVM addresses, matching is case-insensitive. (required) @@ -465,7 +465,7 @@ private HttpRequest.Builder getDelegationForEndUserRequestBuilder(String userId, } /** - * Get account-scoped delegation for an end user account + * Get account-scoped delegation for end user * Returns the active account-scoped delegation for the specified end user account, if one exists. Useful for showing delegation status in a UI. When the address corresponds to an EVM Smart Account, this returns the delegation for the Smart Account's owner EOA. * @param userId The ID of the end user. (required) * @param address The blockchain address of the end user account to query. For EVM addresses, matching is case-insensitive. (required) @@ -479,7 +479,7 @@ public GetDelegationForEndUser200Response getDelegationForEndUserAccount(String } /** - * Get account-scoped delegation for an end user account + * Get account-scoped delegation for end user * Returns the active account-scoped delegation for the specified end user account, if one exists. Useful for showing delegation status in a UI. When the address corresponds to an EVM Smart Account, this returns the delegation for the Smart Account's owner EOA. * @param userId The ID of the end user. (required) * @param address The blockchain address of the end user account to query. For EVM addresses, matching is case-insensitive. (required) @@ -693,7 +693,7 @@ private HttpRequest.Builder revokeDelegationForEndUserRequestBuilder(String user } /** - * Revoke account-scoped delegation for an end user account + * Revoke account-scoped delegation for end user * Revokes the active account-scoped delegation for the specified end user account. Other account-scoped delegations for the same user are unaffected. This operation can be performed by the end user themselves or by a developer using their API key. When the address corresponds to an EVM Smart Account, this revokes the delegation for the Smart Account's owner EOA. * @param userId The ID of the end user. (required) * @param address The blockchain address of the end user account whose delegation should be revoked. For EVM addresses, matching is case-insensitive. (required) @@ -709,7 +709,7 @@ public void revokeDelegationForEndUserAccount(String userId, String address, Rev } /** - * Revoke account-scoped delegation for an end user account + * Revoke account-scoped delegation for end user * Revokes the active account-scoped delegation for the specified end user account. Other account-scoped delegations for the same user are unaffected. This operation can be performed by the end user themselves or by a developer using their API key. When the address corresponds to an EVM Smart Account, this revokes the delegation for the Smart Account's owner EOA. * @param userId The ID of the end user. (required) * @param address The blockchain address of the end user account whose delegation should be revoked. For EVM addresses, matching is case-insensitive. (required) @@ -958,7 +958,7 @@ private HttpRequest.Builder sendEvmAssetWithEndUserAccountRequestBuilder(String } /** - * Send a transaction with end user EVM account + * Send transaction via end user EVM account * Signs a transaction with the given end user EVM account and sends it to the indicated supported network. This API handles nonce management and gas estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). **Transaction fields and API behavior** - `to` *(Required)*: The address of the contract or account to send the transaction to. - `chainId` *(Ignored)*: The value of the `chainId` field in the transaction is ignored. The transaction will be sent to the network indicated by the `network` field in the request body. - `nonce` *(Optional)*: The nonce to use for the transaction. If not provided, the API will assign a nonce to the transaction based on the current state of the account. - `maxPriorityFeePerGas` *(Optional)*: The maximum priority fee per gas to use for the transaction. If not provided, the API will estimate a value based on current network conditions. - `maxFeePerGas` *(Optional)*: The maximum fee per gas to use for the transaction. If not provided, the API will estimate a value based on current network conditions. - `gasLimit` *(Optional)*: The gas limit to use for the transaction. If not provided, the API will estimate a value based on the `to` and `data` fields of the transaction. - `value` *(Optional)*: The amount of ETH, in wei, to send with the transaction. - `data` *(Optional)*: The data to send with the transaction; only used for contract calls. - `accessList` *(Optional)*: The access list to use for the transaction. * @param userId The ID of the end user. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -975,7 +975,7 @@ public SendEvmTransactionWithEndUserAccount200Response sendEvmTransactionWithEnd } /** - * Send a transaction with end user EVM account + * Send transaction via end user EVM account * Signs a transaction with the given end user EVM account and sends it to the indicated supported network. This API handles nonce management and gas estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). **Transaction fields and API behavior** - `to` *(Required)*: The address of the contract or account to send the transaction to. - `chainId` *(Ignored)*: The value of the `chainId` field in the transaction is ignored. The transaction will be sent to the network indicated by the `network` field in the request body. - `nonce` *(Optional)*: The nonce to use for the transaction. If not provided, the API will assign a nonce to the transaction based on the current state of the account. - `maxPriorityFeePerGas` *(Optional)*: The maximum priority fee per gas to use for the transaction. If not provided, the API will estimate a value based on current network conditions. - `maxFeePerGas` *(Optional)*: The maximum fee per gas to use for the transaction. If not provided, the API will estimate a value based on current network conditions. - `gasLimit` *(Optional)*: The gas limit to use for the transaction. If not provided, the API will estimate a value based on the `to` and `data` fields of the transaction. - `value` *(Optional)*: The amount of ETH, in wei, to send with the transaction. - `data` *(Optional)*: The data to send with the transaction; only used for contract calls. - `accessList` *(Optional)*: The access list to use for the transaction. * @param userId The ID of the end user. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -1220,7 +1220,7 @@ private HttpRequest.Builder sendSolanaAssetWithEndUserAccountRequestBuilder(Stri } /** - * Send a transaction with end user Solana account + * Send transaction via end user Solana account * Signs a transaction with the given end user Solana account and sends it to the indicated supported network. The API handles recent blockhash management and fee estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. The unsigned transaction should be serialized into a byte array and then encoded as base64. **Transaction types** The following transaction types are supported: * [Legacy transactions](https://solana.com/developers/guides/advanced/versions#current-transaction-versions) * [Versioned transactions](https://solana.com/developers/guides/advanced/versions) **Instruction Batching** To batch multiple operations, include multiple instructions within a single transaction. All instructions within a transaction are executed atomically - if any instruction fails, the entire transaction fails and is rolled back. **Network Support** The following Solana networks are supported: * `solana` - Solana Mainnet * `solana-devnet` - Solana Devnet The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. * @param userId The ID of the end user. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -1237,7 +1237,7 @@ public SendSolanaTransactionWithEndUserAccount200Response sendSolanaTransactionW } /** - * Send a transaction with end user Solana account + * Send transaction via end user Solana account * Signs a transaction with the given end user Solana account and sends it to the indicated supported network. The API handles recent blockhash management and fee estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. The unsigned transaction should be serialized into a byte array and then encoded as base64. **Transaction types** The following transaction types are supported: * [Legacy transactions](https://solana.com/developers/guides/advanced/versions#current-transaction-versions) * [Versioned transactions](https://solana.com/developers/guides/advanced/versions) **Instruction Batching** To batch multiple operations, include multiple instructions within a single transaction. All instructions within a transaction are executed atomically - if any instruction fails, the entire transaction fails and is rolled back. **Network Support** The following Solana networks are supported: * `solana` - Solana Mainnet * `solana-devnet` - Solana Devnet The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. * @param userId The ID of the end user. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -1344,7 +1344,7 @@ private HttpRequest.Builder sendSolanaTransactionWithEndUserAccountRequestBuilde } /** - * Send a user operation for end user Smart Account + * Send user operation for end user Smart Account * Prepares, signs, and sends a user operation for an end user's Smart Account. * @param userId The ID of the end user. (required) * @param address The address of the EVM Smart Account to execute the user operation from. (required) @@ -1362,7 +1362,7 @@ public EvmUserOperation sendUserOperationWithEndUserAccount(String userId, Strin } /** - * Send a user operation for end user Smart Account + * Send user operation for end user Smart Account * Prepares, signs, and sends a user operation for an end user's Smart Account. * @param userId The ID of the end user. (required) * @param address The address of the EVM Smart Account to execute the user operation from. (required) @@ -1475,7 +1475,7 @@ private HttpRequest.Builder sendUserOperationWithEndUserAccountRequestBuilder(St } /** - * Sign an EIP-191 message with end user EVM account + * Sign EIP-191 message via end user EVM account * Signs an [EIP-191](https://eips.ethereum.org/EIPS/eip-191) message with the given end user EVM account. Per the specification, the message in the request body is prepended with `0x19 <0x45 (E)> <thereum Signed Message:\\n\" + len(message)>` before being signed. * @param userId The ID of the end user. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -1492,7 +1492,7 @@ public SignEvmMessageWithEndUserAccount200Response signEvmMessageWithEndUserAcco } /** - * Sign an EIP-191 message with end user EVM account + * Sign EIP-191 message via end user EVM account * Signs an [EIP-191](https://eips.ethereum.org/EIPS/eip-191) message with the given end user EVM account. Per the specification, the message in the request body is prepended with `0x19 <0x45 (E)> <thereum Signed Message:\\n\" + len(message)>` before being signed. * @param userId The ID of the end user. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -1599,7 +1599,7 @@ private HttpRequest.Builder signEvmMessageWithEndUserAccountRequestBuilder(Strin } /** - * Sign a transaction with end user EVM account + * Sign transaction via end user EVM account * Signs a transaction with the given end user EVM account. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. * @param userId The ID of the end user. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -1616,7 +1616,7 @@ public SignEvmTransactionWithEndUserAccount200Response signEvmTransactionWithEnd } /** - * Sign a transaction with end user EVM account + * Sign transaction via end user EVM account * Signs a transaction with the given end user EVM account. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. * @param userId The ID of the end user. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -1723,7 +1723,7 @@ private HttpRequest.Builder signEvmTransactionWithEndUserAccountRequestBuilder(S } /** - * Sign EIP-712 typed data with end user EVM account + * Sign EIP-712 typed data via end user EVM account * Signs [EIP-712](https://eips.ethereum.org/EIPS/eip-712) typed data with the given end user EVM account. * @param userId The ID of the end user. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -1740,7 +1740,7 @@ public SignEvmTypedDataWithEndUserAccount200Response signEvmTypedDataWithEndUser } /** - * Sign EIP-712 typed data with end user EVM account + * Sign EIP-712 typed data via end user EVM account * Signs [EIP-712](https://eips.ethereum.org/EIPS/eip-712) typed data with the given end user EVM account. * @param userId The ID of the end user. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -1847,7 +1847,7 @@ private HttpRequest.Builder signEvmTypedDataWithEndUserAccountRequestBuilder(Str } /** - * Sign a Base64 encoded message + * Sign Base64-encoded message * Signs an arbitrary Base64 encoded message with the given Solana account. **WARNING:** Never sign a message that you didn't generate as it may put your funds at risk. * @param userId The ID of the end user. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -1864,7 +1864,7 @@ public SignSolanaMessageWithEndUserAccount200Response signSolanaMessageWithEndUs } /** - * Sign a Base64 encoded message + * Sign Base64-encoded message * Signs an arbitrary Base64 encoded message with the given Solana account. **WARNING:** Never sign a message that you didn't generate as it may put your funds at risk. * @param userId The ID of the end user. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -1971,7 +1971,7 @@ private HttpRequest.Builder signSolanaMessageWithEndUserAccountRequestBuilder(St } /** - * Sign a transaction with end user Solana account + * Sign transaction via end user Solana account * Signs a transaction with the given end user Solana account. The unsigned transaction should be serialized into a byte array and then encoded as base64. **Transaction types** The following transaction types are supported: * [Legacy transactions](https://solana-labs.github.io/solana-web3.js/classes/Transaction.html) * [Versioned transactions](https://solana-labs.github.io/solana-web3.js/classes/VersionedTransaction.html) The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. * @param userId The ID of the end user. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -1988,7 +1988,7 @@ public SignSolanaTransactionWithEndUserAccount200Response signSolanaTransactionW } /** - * Sign a transaction with end user Solana account + * Sign transaction via end user Solana account * Signs a transaction with the given end user Solana account. The unsigned transaction should be serialized into a byte array and then encoded as base64. **Transaction types** The following transaction types are supported: * [Legacy transactions](https://solana-labs.github.io/solana-web3.js/classes/Transaction.html) * [Versioned transactions](https://solana-labs.github.io/solana-web3.js/classes/VersionedTransaction.html) The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. * @param userId The ID of the end user. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) diff --git a/java/src/main/java/com/coinbase/cdp/openapi/api/EndUserAccountsApi.java b/java/src/main/java/com/coinbase/cdp/openapi/api/EndUserAccountsApi.java index 198c27cb5..5540b9ddb 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/api/EndUserAccountsApi.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/api/EndUserAccountsApi.java @@ -93,7 +93,7 @@ private String formatExceptionMessage(String operationId, int statusCode, String } /** - * Add an EVM account to an end user + * Add EVM account to end user * Adds a new EVM EOA account to an existing end user. End users can have up to 10 EVM accounts. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. * @param userId The ID of the end user to add the account to. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -108,7 +108,7 @@ public AddEndUserEvmAccount201Response addEndUserEvmAccount(String userId, Strin } /** - * Add an EVM account to an end user + * Add EVM account to end user * Adds a new EVM EOA account to an existing end user. End users can have up to 10 EVM accounts. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. * @param userId The ID of the end user to add the account to. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -195,7 +195,7 @@ private HttpRequest.Builder addEndUserEvmAccountRequestBuilder(String userId, St } /** - * Add an EVM smart account to an end user + * Add EVM smart account to end user * Creates an EVM smart account for an existing end user. The backend will create a new EVM EOA account to serve as the owner of the smart account. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. * @param userId The ID of the end user to add the smart account to. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -210,7 +210,7 @@ public AddEndUserEvmSmartAccount201Response addEndUserEvmSmartAccount(String use } /** - * Add an EVM smart account to an end user + * Add EVM smart account to end user * Creates an EVM smart account for an existing end user. The backend will create a new EVM EOA account to serve as the owner of the smart account. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. * @param userId The ID of the end user to add the smart account to. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -297,7 +297,7 @@ private HttpRequest.Builder addEndUserEvmSmartAccountRequestBuilder(String userI } /** - * Add a Solana account to an end user + * Add Solana account to end user * Adds a new Solana account to an existing end user. End users can have up to 10 Solana accounts. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. * @param userId The ID of the end user to add the account to. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -312,7 +312,7 @@ public AddEndUserSolanaAccount201Response addEndUserSolanaAccount(String userId, } /** - * Add a Solana account to an end user + * Add Solana account to end user * Adds a new Solana account to an existing end user. End users can have up to 10 Solana accounts. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. * @param userId The ID of the end user to add the account to. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -399,7 +399,7 @@ private HttpRequest.Builder addEndUserSolanaAccountRequestBuilder(String userId, } /** - * Create an end user + * Create end user * Creates an end user. An end user is an entity that can own CDP EVM accounts, EVM smart accounts, and/or Solana accounts. 1 or more authentication methods must be associated with an end user. By default, no accounts are created unless the optional `evmAccount` and/or `solanaAccount` fields are provided. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -413,7 +413,7 @@ public EndUser createEndUser(String xWalletAuth, String xIdempotencyKey, CreateE } /** - * Create an end user + * Create end user * Creates an end user. An end user is an entity that can own CDP EVM accounts, EVM smart accounts, and/or Solana accounts. 1 or more authentication methods must be associated with an end user. By default, no accounts are created unless the optional `evmAccount` and/or `solanaAccount` fields are provided. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -494,7 +494,7 @@ private HttpRequest.Builder createEndUserRequestBuilder(String xWalletAuth, Stri } /** - * Get an end user + * Get end user * Gets an end user by ID. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. * @param userId The ID of the end user to get. (required) * @return EndUser @@ -506,7 +506,7 @@ public EndUser getEndUser(String userId) throws ApiException { } /** - * Get an end user + * Get end user * Gets an end user by ID. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. * @param userId The ID of the end user to get. (required) * @return ApiResponse<EndUser> @@ -578,7 +578,7 @@ private HttpRequest.Builder getEndUserRequestBuilder(String userId) throws ApiEx } /** - * Import a private key for an end user + * Import end user private key * Imports an existing private key for an end user into the developer's CDP Project. The private key must be encrypted using the CDP SDK's encryption scheme before being sent to this endpoint. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. This endpoint allows developers to import existing keys for their end users, supporting both EVM and Solana key types. The end user must have at least one authentication method configured. * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -592,7 +592,7 @@ public EndUser importEndUser(String xWalletAuth, String xIdempotencyKey, ImportE } /** - * Import a private key for an end user + * Import end user private key * Imports an existing private key for an end user into the developer's CDP Project. The private key must be encrypted using the CDP SDK's encryption scheme before being sent to this endpoint. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. This endpoint allows developers to import existing keys for their end users, supporting both EVM and Solana key types. The end user must have at least one authentication method configured. * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) diff --git a/java/src/main/java/com/coinbase/cdp/openapi/api/EvmAccountsApi.java b/java/src/main/java/com/coinbase/cdp/openapi/api/EvmAccountsApi.java index 9801534b7..fb421a628 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/api/EvmAccountsApi.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/api/EvmAccountsApi.java @@ -103,7 +103,7 @@ private String formatExceptionMessage(String operationId, int statusCode, String } /** - * Create an EVM account + * Create EVM account * Creates a new EVM account. * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -117,7 +117,7 @@ public EvmAccount createEvmAccount(String xWalletAuth, String xIdempotencyKey, C } /** - * Create an EVM account + * Create EVM account * Creates a new EVM account. * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -304,7 +304,7 @@ private HttpRequest.Builder createEvmEip7702DelegationRequestBuilder(String addr } /** - * Export an EVM account + * Export EVM account * Export an existing EVM account's private key. It is important to store the private key in a secure place after it's exported. * @param address The 0x-prefixed address of the EVM account. The address does not need to be checksummed. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -319,7 +319,7 @@ public ExportEvmAccount200Response exportEvmAccount(String address, String xWall } /** - * Export an EVM account + * Export EVM account * Export an existing EVM account's private key. It is important to store the private key in a secure place after it's exported. * @param address The 0x-prefixed address of the EVM account. The address does not need to be checksummed. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -406,7 +406,7 @@ private HttpRequest.Builder exportEvmAccountRequestBuilder(String address, Strin } /** - * Export an EVM account by name + * Export EVM account by name * Export an existing EVM account's private key by its name. It is important to store the private key in a secure place after it's exported. * @param name The name of the EVM account. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -421,7 +421,7 @@ public ExportEvmAccount200Response exportEvmAccountByName(String name, String xW } /** - * Export an EVM account by name + * Export EVM account by name * Export an existing EVM account's private key by its name. It is important to store the private key in a secure place after it's exported. * @param name The name of the EVM account. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -508,7 +508,7 @@ private HttpRequest.Builder exportEvmAccountByNameRequestBuilder(String name, St } /** - * Get an EVM account by address + * Get EVM account by address * Gets an EVM account by its address. * @param address The 0x-prefixed address of the EVM account. The address does not need to be checksummed. (required) * @return EvmAccount @@ -520,7 +520,7 @@ public EvmAccount getEvmAccount(String address) throws ApiException { } /** - * Get an EVM account by address + * Get EVM account by address * Gets an EVM account by its address. * @param address The 0x-prefixed address of the EVM account. The address does not need to be checksummed. (required) * @return ApiResponse<EvmAccount> @@ -592,7 +592,7 @@ private HttpRequest.Builder getEvmAccountRequestBuilder(String address) throws A } /** - * Get an EVM account by name + * Get EVM account by name * Gets an EVM account by its name. * @param name The name of the EVM account. (required) * @return EvmAccount @@ -604,7 +604,7 @@ public EvmAccount getEvmAccountByName(String name) throws ApiException { } /** - * Get an EVM account by name + * Get EVM account by name * Gets an EVM account by its name. * @param name The name of the EVM account. (required) * @return ApiResponse<EvmAccount> @@ -676,7 +676,7 @@ private HttpRequest.Builder getEvmAccountByNameRequestBuilder(String name) throw } /** - * Get EIP-7702 delegation operation for an operationID + * Get EIP-7702 delegation operation by ID * Returns the EIP-7702 delegation operation. Use the delegationOperationId returned by the Create EIP-7702 delegation endpoint to poll for operation completion. * @param delegationOperationId The unique identifier for the delegation operation. (required) * @return EvmEip7702DelegationOperation @@ -688,7 +688,7 @@ public EvmEip7702DelegationOperation getEvmEip7702DelegationOperationById(UUID d } /** - * Get EIP-7702 delegation operation for an operationID + * Get EIP-7702 delegation operation by ID * Returns the EIP-7702 delegation operation. Use the delegationOperationId returned by the Create EIP-7702 delegation endpoint to poll for operation completion. * @param delegationOperationId The unique identifier for the delegation operation. (required) * @return ApiResponse<EvmEip7702DelegationOperation> @@ -760,7 +760,7 @@ private HttpRequest.Builder getEvmEip7702DelegationOperationByIdRequestBuilder(U } /** - * Import an EVM account + * Import EVM account * Import an existing EVM account into the developer's CDP Project. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -774,7 +774,7 @@ public EvmAccount importEvmAccount(String xWalletAuth, String xIdempotencyKey, I } /** - * Import an EVM account + * Import EVM account * Import an existing EVM account into the developer's CDP Project. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -953,7 +953,7 @@ private HttpRequest.Builder listEvmAccountsRequestBuilder(Integer pageSize, Stri } /** - * Send a transaction + * Send transaction * Signs a transaction with the given EVM account and sends it to the indicated supported network. This API handles nonce management and gas estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). **Transaction fields and API behavior** - `to` *(Required)*: The address of the contract or account to send the transaction to. - `chainId` *(Ignored)*: The value of the `chainId` field in the transaction is ignored. The transaction will be sent to the network indicated by the `network` field in the request body. - `nonce` *(Optional)*: The nonce to use for the transaction. If not provided, the API will assign a nonce to the transaction based on the current state of the account. - `maxPriorityFeePerGas` *(Optional)*: The maximum priority fee per gas to use for the transaction. If not provided, the API will estimate a value based on current network conditions. - `maxFeePerGas` *(Optional)*: The maximum fee per gas to use for the transaction. If not provided, the API will estimate a value based on current network conditions. - `gasLimit` *(Optional)*: The gas limit to use for the transaction. If not provided, the API will estimate a value based on the `to` and `data` fields of the transaction. - `value` *(Optional)*: The amount of ETH, in wei, to send with the transaction. - `data` *(Optional)*: The data to send with the transaction; only used for contract calls. - `accessList` *(Optional)*: The access list to use for the transaction. * @param address The 0x-prefixed address of the Ethereum account. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -968,7 +968,7 @@ public SendEvmTransactionWithEndUserAccount200Response sendEvmTransaction(String } /** - * Send a transaction + * Send transaction * Signs a transaction with the given EVM account and sends it to the indicated supported network. This API handles nonce management and gas estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). **Transaction fields and API behavior** - `to` *(Required)*: The address of the contract or account to send the transaction to. - `chainId` *(Ignored)*: The value of the `chainId` field in the transaction is ignored. The transaction will be sent to the network indicated by the `network` field in the request body. - `nonce` *(Optional)*: The nonce to use for the transaction. If not provided, the API will assign a nonce to the transaction based on the current state of the account. - `maxPriorityFeePerGas` *(Optional)*: The maximum priority fee per gas to use for the transaction. If not provided, the API will estimate a value based on current network conditions. - `maxFeePerGas` *(Optional)*: The maximum fee per gas to use for the transaction. If not provided, the API will estimate a value based on current network conditions. - `gasLimit` *(Optional)*: The gas limit to use for the transaction. If not provided, the API will estimate a value based on the `to` and `data` fields of the transaction. - `value` *(Optional)*: The amount of ETH, in wei, to send with the transaction. - `data` *(Optional)*: The data to send with the transaction; only used for contract calls. - `accessList` *(Optional)*: The access list to use for the transaction. * @param address The 0x-prefixed address of the Ethereum account. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -1055,7 +1055,7 @@ private HttpRequest.Builder sendEvmTransactionRequestBuilder(String address, Str } /** - * Sign a hash + * Sign hash * Signs an arbitrary 32 byte hash with the given EVM account. * @param address The 0x-prefixed address of the EVM account. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -1070,7 +1070,7 @@ public SignEvmHash200Response signEvmHash(String address, String xWalletAuth, St } /** - * Sign a hash + * Sign hash * Signs an arbitrary 32 byte hash with the given EVM account. * @param address The 0x-prefixed address of the EVM account. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -1157,7 +1157,7 @@ private HttpRequest.Builder signEvmHashRequestBuilder(String address, String xWa } /** - * Sign an EIP-191 message + * Sign EIP-191 message * Signs an [EIP-191](https://eips.ethereum.org/EIPS/eip-191) message with the given EVM account. Per the specification, the message in the request body is prepended with `0x19 <0x45 (E)> <thereum Signed Message:\\n\" + len(message)>` before being signed. * @param address The 0x-prefixed address of the EVM account. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -1172,7 +1172,7 @@ public SignEvmMessageWithEndUserAccount200Response signEvmMessage(String address } /** - * Sign an EIP-191 message + * Sign EIP-191 message * Signs an [EIP-191](https://eips.ethereum.org/EIPS/eip-191) message with the given EVM account. Per the specification, the message in the request body is prepended with `0x19 <0x45 (E)> <thereum Signed Message:\\n\" + len(message)>` before being signed. * @param address The 0x-prefixed address of the EVM account. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -1259,7 +1259,7 @@ private HttpRequest.Builder signEvmMessageRequestBuilder(String address, String } /** - * Sign a transaction + * Sign transaction * Signs a transaction with the given EVM account. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. * @param address The 0x-prefixed address of the EVM account. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -1274,7 +1274,7 @@ public SignEvmTransactionWithEndUserAccount200Response signEvmTransaction(String } /** - * Sign a transaction + * Sign transaction * Signs a transaction with the given EVM account. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. * @param address The 0x-prefixed address of the EVM account. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -1463,7 +1463,7 @@ private HttpRequest.Builder signEvmTypedDataRequestBuilder(String address, Strin } /** - * Update an EVM account + * Update EVM account * Updates an existing EVM account. Use this to update the account's name or account-level policy. * @param address The 0x-prefixed address of the EVM account. The address does not need to be checksummed. (required) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -1477,7 +1477,7 @@ public EvmAccount updateEvmAccount(String address, String xIdempotencyKey, Updat } /** - * Update an EVM account + * Update EVM account * Updates an existing EVM account. Use this to update the account's name or account-level policy. * @param address The 0x-prefixed address of the EVM account. The address does not need to be checksummed. (required) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) diff --git a/java/src/main/java/com/coinbase/cdp/openapi/api/EvmSmartAccountsApi.java b/java/src/main/java/com/coinbase/cdp/openapi/api/EvmSmartAccountsApi.java index 17ca850cd..44a8ae3d4 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/api/EvmSmartAccountsApi.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/api/EvmSmartAccountsApi.java @@ -93,7 +93,7 @@ private String formatExceptionMessage(String operationId, int statusCode, String } /** - * Create a Smart Account + * Create Smart Account * Creates a new Smart Account. * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) * @param createEvmSmartAccountRequest (optional) @@ -106,7 +106,7 @@ public EvmSmartAccount createEvmSmartAccount(String xIdempotencyKey, CreateEvmSm } /** - * Create a Smart Account + * Create Smart Account * Creates a new Smart Account. * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) * @param createEvmSmartAccountRequest (optional) @@ -183,7 +183,7 @@ private HttpRequest.Builder createEvmSmartAccountRequestBuilder(String xIdempote } /** - * Create a spend permission + * Create spend permission * Creates a spend permission for the given smart account address. * @param address The address of the Smart Account to create the spend permission for. (required) * @param createSpendPermissionRequest (required) @@ -198,7 +198,7 @@ public EvmUserOperation createSpendPermission(String address, CreateSpendPermiss } /** - * Create a spend permission + * Create spend permission * Creates a spend permission for the given smart account address. * @param address The address of the Smart Account to create the spend permission for. (required) * @param createSpendPermissionRequest (required) @@ -289,7 +289,7 @@ private HttpRequest.Builder createSpendPermissionRequestBuilder(String address, } /** - * Get a Smart Account by address + * Get Smart Account by address * Gets a Smart Account by its address. * @param address The 0x-prefixed address of the Smart Account. (required) * @return EvmSmartAccount @@ -301,7 +301,7 @@ public EvmSmartAccount getEvmSmartAccount(String address) throws ApiException { } /** - * Get a Smart Account by address + * Get Smart Account by address * Gets a Smart Account by its address. * @param address The 0x-prefixed address of the Smart Account. (required) * @return ApiResponse<EvmSmartAccount> @@ -373,7 +373,7 @@ private HttpRequest.Builder getEvmSmartAccountRequestBuilder(String address) thr } /** - * Get a Smart Account by name + * Get Smart Account by name * Gets a Smart Account by its name. * @param name The name of the Smart Account. (required) * @return EvmSmartAccount @@ -385,7 +385,7 @@ public EvmSmartAccount getEvmSmartAccountByName(String name) throws ApiException } /** - * Get a Smart Account by name + * Get Smart Account by name * Gets a Smart Account by its name. * @param name The name of the Smart Account. (required) * @return ApiResponse<EvmSmartAccount> @@ -457,7 +457,7 @@ private HttpRequest.Builder getEvmSmartAccountByNameRequestBuilder(String name) } /** - * Get a user operation + * Get user operation * Gets a user operation by its hash. * @param address The address of the Smart Account the user operation belongs to. (required) * @param userOpHash The hash of the user operation to fetch. (required) @@ -470,7 +470,7 @@ public EvmUserOperation getUserOperation(String address, String userOpHash) thro } /** - * Get a user operation + * Get user operation * Gets a user operation by its hash. * @param address The address of the Smart Account the user operation belongs to. (required) * @param userOpHash The hash of the user operation to fetch. (required) @@ -751,7 +751,7 @@ private HttpRequest.Builder listSpendPermissionsRequestBuilder(String address, I } /** - * Prepare and send a user operation for EVM Smart Account + * Prepare and send user operation * Prepares, signs, and sends a user operation for an EVM Smart Account. This API can be used only if the owner on Smart Account is a CDP EVM Account. * @param address The address of the EVM Smart Account to execute the user operation from. (required) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -766,7 +766,7 @@ public EvmUserOperation prepareAndSendUserOperation(String address, String xIdem } /** - * Prepare and send a user operation for EVM Smart Account + * Prepare and send user operation * Prepares, signs, and sends a user operation for an EVM Smart Account. This API can be used only if the owner on Smart Account is a CDP EVM Account. * @param address The address of the EVM Smart Account to execute the user operation from. (required) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -853,7 +853,7 @@ private HttpRequest.Builder prepareAndSendUserOperationRequestBuilder(String add } /** - * Prepare a user operation + * Prepare user operation * Prepares a new user operation on a Smart Account for a specific network. * @param address The address of the Smart Account to create the user operation on. (required) * @param prepareUserOperationRequest (optional) @@ -866,7 +866,7 @@ public EvmUserOperation prepareUserOperation(String address, PrepareUserOperatio } /** - * Prepare a user operation + * Prepare user operation * Prepares a new user operation on a Smart Account for a specific network. * @param address The address of the Smart Account to create the user operation on. (required) * @param prepareUserOperationRequest (optional) @@ -945,7 +945,7 @@ private HttpRequest.Builder prepareUserOperationRequestBuilder(String address, P } /** - * Revoke a spend permission + * Revoke spend permission * Revokes an existing spend permission. * @param address The address of the Smart account this spend permission is valid for. (required) * @param revokeSpendPermissionRequest (required) @@ -960,7 +960,7 @@ public EvmUserOperation revokeSpendPermission(String address, RevokeSpendPermiss } /** - * Revoke a spend permission + * Revoke spend permission * Revokes an existing spend permission. * @param address The address of the Smart account this spend permission is valid for. (required) * @param revokeSpendPermissionRequest (required) @@ -1051,7 +1051,7 @@ private HttpRequest.Builder revokeSpendPermissionRequestBuilder(String address, } /** - * Send a user operation + * Send user operation * Sends a user operation with a signature. The payload to sign must be the `userOpHash` field of the user operation. This hash should be signed directly (not using `personal_sign` or EIP-191 message hashing). The signature must be 65 bytes in length, consisting of: - 32 bytes for the `r` value - 32 bytes for the `s` value - 1 byte for the `v` value (must be 27 or 28) If using the CDP Paymaster, the user operation must be signed and sent within 2 minutes of being prepared. * @param address The address of the Smart Account to send the user operation from. (required) * @param userOpHash The hash of the user operation to send. (required) @@ -1065,7 +1065,7 @@ public EvmUserOperation sendUserOperation(String address, String userOpHash, Sen } /** - * Send a user operation + * Send user operation * Sends a user operation with a signature. The payload to sign must be the `userOpHash` field of the user operation. This hash should be signed directly (not using `personal_sign` or EIP-191 message hashing). The signature must be 65 bytes in length, consisting of: - 32 bytes for the `r` value - 32 bytes for the `s` value - 1 byte for the `v` value (must be 27 or 28) If using the CDP Paymaster, the user operation must be signed and sent within 2 minutes of being prepared. * @param address The address of the Smart Account to send the user operation from. (required) * @param userOpHash The hash of the user operation to send. (required) @@ -1150,7 +1150,7 @@ private HttpRequest.Builder sendUserOperationRequestBuilder(String address, Stri } /** - * Update an EVM Smart Account + * Update EVM Smart Account * Updates an existing EVM smart account. Use this to update the smart account's name. * @param address The 0x-prefixed address of the EVM smart account. The address does not need to be checksummed. (required) * @param updateEvmSmartAccountRequest (optional) @@ -1163,7 +1163,7 @@ public EvmSmartAccount updateEvmSmartAccount(String address, UpdateEvmSmartAccou } /** - * Update an EVM Smart Account + * Update EVM Smart Account * Updates an existing EVM smart account. Use this to update the smart account's name. * @param address The 0x-prefixed address of the EVM smart account. The address does not need to be checksummed. (required) * @param updateEvmSmartAccountRequest (optional) diff --git a/java/src/main/java/com/coinbase/cdp/openapi/api/EvmSwapsApi.java b/java/src/main/java/com/coinbase/cdp/openapi/api/EvmSwapsApi.java index 19c2afbe3..88418fcc3 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/api/EvmSwapsApi.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/api/EvmSwapsApi.java @@ -86,7 +86,7 @@ private String formatExceptionMessage(String operationId, int statusCode, String } /** - * Create a swap quote + * Create swap quote * Create a swap quote, which includes the payload to sign as well as the transaction data needed to execute the swap. The developer is responsible for signing the payload and submitting the transaction to the network in order to execute the swap. * @param createEvmSwapQuoteRequest (required) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -99,7 +99,7 @@ public CreateSwapQuoteResponseWrapper createEvmSwapQuote(CreateEvmSwapQuoteReque } /** - * Create a swap quote + * Create swap quote * Create a swap quote, which includes the payload to sign as well as the transaction data needed to execute the swap. The developer is responsible for signing the payload and submitting the transaction to the network in order to execute the swap. * @param createEvmSwapQuoteRequest (required) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -180,7 +180,7 @@ private HttpRequest.Builder createEvmSwapQuoteRequestBuilder(CreateEvmSwapQuoteR } /** - * Get a price estimate for a swap + * Get swap price estimate * Get a price estimate for a swap between two tokens on an EVM network. * @param network (required) * @param toToken (required) @@ -199,7 +199,7 @@ public GetSwapPriceResponseWrapper getEvmSwapPrice(EvmSwapsNetwork network, Stri } /** - * Get a price estimate for a swap + * Get swap price estimate * Get a price estimate for a swap between two tokens on an EVM network. * @param network (required) * @param toToken (required) diff --git a/java/src/main/java/com/coinbase/cdp/openapi/api/PaymentMethodsApi.java b/java/src/main/java/com/coinbase/cdp/openapi/api/PaymentMethodsApi.java new file mode 100644 index 000000000..28365a5ba --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/api/PaymentMethodsApi.java @@ -0,0 +1,268 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.coinbase.cdp.openapi.api; + +import com.coinbase.cdp.openapi.ApiClient; +import com.coinbase.cdp.openapi.ApiException; +import com.coinbase.cdp.openapi.ApiResponse; +import com.coinbase.cdp.openapi.Pair; + +import com.coinbase.cdp.openapi.model.Error; +import com.coinbase.cdp.openapi.model.ListPaymentMethods200Response; +import com.coinbase.cdp.openapi.model.PaymentMethodsPaymentMethod; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.InputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.net.http.HttpRequest; +import java.nio.channels.Channels; +import java.nio.channels.Pipe; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; + +import java.util.ArrayList; +import java.util.StringJoiner; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class PaymentMethodsApi { + private final HttpClient memberVarHttpClient; + private final ObjectMapper memberVarObjectMapper; + private final String memberVarBaseUri; + private final Consumer memberVarInterceptor; + private final Duration memberVarReadTimeout; + private final Consumer> memberVarResponseInterceptor; + private final Consumer> memberVarAsyncResponseInterceptor; + + public PaymentMethodsApi() { + this(new ApiClient()); + } + + public PaymentMethodsApi(ApiClient apiClient) { + memberVarHttpClient = apiClient.getHttpClient(); + memberVarObjectMapper = apiClient.getObjectMapper(); + memberVarBaseUri = apiClient.getBaseUri(); + memberVarInterceptor = apiClient.getRequestInterceptor(); + memberVarReadTimeout = apiClient.getReadTimeout(); + memberVarResponseInterceptor = apiClient.getResponseInterceptor(); + memberVarAsyncResponseInterceptor = apiClient.getAsyncResponseInterceptor(); + } + + protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + String message = formatExceptionMessage(operationId, response.statusCode(), body); + return new ApiException(response.statusCode(), message, response.headers(), body); + } + + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; + } + return operationId + " call failed with: " + statusCode + " - " + body; + } + + /** + * Get payment method + * Get details of a specific payment method by its ID. Returns 404 if the payment method is not found or not owned by the requesting entity. + * @param paymentMethodId The unique identifier of the payment method. (required) + * @return PaymentMethodsPaymentMethod + * @throws ApiException if fails to make API call + */ + public PaymentMethodsPaymentMethod getPaymentMethod(String paymentMethodId) throws ApiException { + ApiResponse localVarResponse = getPaymentMethodWithHttpInfo(paymentMethodId); + return localVarResponse.getData(); + } + + /** + * Get payment method + * Get details of a specific payment method by its ID. Returns 404 if the payment method is not found or not owned by the requesting entity. + * @param paymentMethodId The unique identifier of the payment method. (required) + * @return ApiResponse<PaymentMethodsPaymentMethod> + * @throws ApiException if fails to make API call + */ + public ApiResponse getPaymentMethodWithHttpInfo(String paymentMethodId) throws ApiException { + HttpRequest.Builder localVarRequestBuilder = getPaymentMethodRequestBuilder(paymentMethodId); + try { + HttpResponse localVarResponse = memberVarHttpClient.send( + localVarRequestBuilder.build(), + HttpResponse.BodyHandlers.ofInputStream()); + if (memberVarResponseInterceptor != null) { + memberVarResponseInterceptor.accept(localVarResponse); + } + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("getPaymentMethod", localVarResponse); + } + if (localVarResponse.body() == null) { + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + null + ); + } + + String responseBody = new String(localVarResponse.body().readAllBytes()); + localVarResponse.body().close(); + + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + responseBody.isBlank()? null: memberVarObjectMapper.readValue(responseBody, new TypeReference() {}) + ); + } finally { + } + } catch (IOException e) { + throw new ApiException(e); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ApiException(e); + } + } + + private HttpRequest.Builder getPaymentMethodRequestBuilder(String paymentMethodId) throws ApiException { + // verify the required parameter 'paymentMethodId' is set + if (paymentMethodId == null) { + throw new ApiException(400, "Missing the required parameter 'paymentMethodId' when calling getPaymentMethod"); + } + + HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); + + String localVarPath = "/v2/payment-methods/{paymentMethodId}" + .replace("{paymentMethodId}", ApiClient.urlEncode(paymentMethodId.toString())); + + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); + + localVarRequestBuilder.header("Accept", "application/json"); + + localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); + if (memberVarReadTimeout != null) { + localVarRequestBuilder.timeout(memberVarReadTimeout); + } + if (memberVarInterceptor != null) { + memberVarInterceptor.accept(localVarRequestBuilder); + } + return localVarRequestBuilder; + } + + /** + * List payment methods + * List payment methods linked to your entity. Payment methods represent external financial instruments that can be used as a target for transfers. The list will not include disabled or deleted payment methods. **Currently Supported Types:** - `fedwire`: Domestic USD wire transfers - `swift`: International wire transfers - `sepa`: SEPA EUR transfers **Note:** Payment methods are created and verified through your linked CDP entity. Currently, fetching payment methods is only supported for Prime investment vehicles linked to CDP. + * @param pageSize The number of resources to return per page. (optional, default to 20) + * @param pageToken The token for the next page of resources, if any. (optional) + * @return ListPaymentMethods200Response + * @throws ApiException if fails to make API call + */ + public ListPaymentMethods200Response listPaymentMethods(Integer pageSize, String pageToken) throws ApiException { + ApiResponse localVarResponse = listPaymentMethodsWithHttpInfo(pageSize, pageToken); + return localVarResponse.getData(); + } + + /** + * List payment methods + * List payment methods linked to your entity. Payment methods represent external financial instruments that can be used as a target for transfers. The list will not include disabled or deleted payment methods. **Currently Supported Types:** - `fedwire`: Domestic USD wire transfers - `swift`: International wire transfers - `sepa`: SEPA EUR transfers **Note:** Payment methods are created and verified through your linked CDP entity. Currently, fetching payment methods is only supported for Prime investment vehicles linked to CDP. + * @param pageSize The number of resources to return per page. (optional, default to 20) + * @param pageToken The token for the next page of resources, if any. (optional) + * @return ApiResponse<ListPaymentMethods200Response> + * @throws ApiException if fails to make API call + */ + public ApiResponse listPaymentMethodsWithHttpInfo(Integer pageSize, String pageToken) throws ApiException { + HttpRequest.Builder localVarRequestBuilder = listPaymentMethodsRequestBuilder(pageSize, pageToken); + try { + HttpResponse localVarResponse = memberVarHttpClient.send( + localVarRequestBuilder.build(), + HttpResponse.BodyHandlers.ofInputStream()); + if (memberVarResponseInterceptor != null) { + memberVarResponseInterceptor.accept(localVarResponse); + } + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("listPaymentMethods", localVarResponse); + } + if (localVarResponse.body() == null) { + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + null + ); + } + + String responseBody = new String(localVarResponse.body().readAllBytes()); + localVarResponse.body().close(); + + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + responseBody.isBlank()? null: memberVarObjectMapper.readValue(responseBody, new TypeReference() {}) + ); + } finally { + } + } catch (IOException e) { + throw new ApiException(e); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ApiException(e); + } + } + + private HttpRequest.Builder listPaymentMethodsRequestBuilder(Integer pageSize, String pageToken) throws ApiException { + + HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); + + String localVarPath = "/v2/payment-methods"; + + List localVarQueryParams = new ArrayList<>(); + StringJoiner localVarQueryStringJoiner = new StringJoiner("&"); + String localVarQueryParameterBaseName; + localVarQueryParameterBaseName = "pageSize"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("pageSize", pageSize)); + localVarQueryParameterBaseName = "pageToken"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("pageToken", pageToken)); + + if (!localVarQueryParams.isEmpty() || localVarQueryStringJoiner.length() != 0) { + StringJoiner queryJoiner = new StringJoiner("&"); + localVarQueryParams.forEach(p -> queryJoiner.add(p.getName() + '=' + p.getValue())); + if (localVarQueryStringJoiner.length() != 0) { + queryJoiner.add(localVarQueryStringJoiner.toString()); + } + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath + '?' + queryJoiner.toString())); + } else { + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); + } + + localVarRequestBuilder.header("Accept", "application/json"); + + localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); + if (memberVarReadTimeout != null) { + localVarRequestBuilder.timeout(memberVarReadTimeout); + } + if (memberVarInterceptor != null) { + memberVarInterceptor.accept(localVarRequestBuilder); + } + return localVarRequestBuilder; + } + +} diff --git a/java/src/main/java/com/coinbase/cdp/openapi/api/PolicyEngineApi.java b/java/src/main/java/com/coinbase/cdp/openapi/api/PolicyEngineApi.java index 4cc55e22f..cdba1a292 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/api/PolicyEngineApi.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/api/PolicyEngineApi.java @@ -86,7 +86,7 @@ private String formatExceptionMessage(String operationId, int statusCode, String } /** - * Create a policy + * Create policy * Create a policy that can be used to govern the behavior of accounts. * @param createPolicyRequest (required) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -99,7 +99,7 @@ public Policy createPolicy(CreatePolicyRequest createPolicyRequest, String xIdem } /** - * Create a policy + * Create policy * Create a policy that can be used to govern the behavior of accounts. * @param createPolicyRequest (required) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -180,7 +180,7 @@ private HttpRequest.Builder createPolicyRequestBuilder(CreatePolicyRequest creat } /** - * Delete a policy + * Delete policy * Delete a policy by its ID. This will have the effect of removing the policy from all accounts that are currently using it. * @param policyId The ID of the policy to delete. (required) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -191,7 +191,7 @@ public void deletePolicy(String policyId, String xIdempotencyKey) throws ApiExce } /** - * Delete a policy + * Delete policy * Delete a policy by its ID. This will have the effect of removing the policy from all accounts that are currently using it. * @param policyId The ID of the policy to delete. (required) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -261,7 +261,7 @@ private HttpRequest.Builder deletePolicyRequestBuilder(String policyId, String x } /** - * Get a policy by ID + * Get policy by ID * Get a policy by its ID. * @param policyId The ID of the policy to get. (required) * @return Policy @@ -273,7 +273,7 @@ public Policy getPolicyById(String policyId) throws ApiException { } /** - * Get a policy by ID + * Get policy by ID * Get a policy by its ID. * @param policyId The ID of the policy to get. (required) * @return ApiResponse<Policy> @@ -447,7 +447,7 @@ private HttpRequest.Builder listPoliciesRequestBuilder(Integer pageSize, String } /** - * Update a policy + * Update policy * Updates a policy by its ID. This will have the effect of applying the updated policy to all accounts that are currently using it. * @param policyId The ID of the policy to update. (required) * @param updatePolicyRequest (required) @@ -461,7 +461,7 @@ public Policy updatePolicy(String policyId, UpdatePolicyRequest updatePolicyRequ } /** - * Update a policy + * Update policy * Updates a policy by its ID. This will have the effect of applying the updated policy to all accounts that are currently using it. * @param policyId The ID of the policy to update. (required) * @param updatePolicyRequest (required) diff --git a/java/src/main/java/com/coinbase/cdp/openapi/api/SolanaAccountsApi.java b/java/src/main/java/com/coinbase/cdp/openapi/api/SolanaAccountsApi.java index 3ca7dbdd3..696bba547 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/api/SolanaAccountsApi.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/api/SolanaAccountsApi.java @@ -95,7 +95,7 @@ private String formatExceptionMessage(String operationId, int statusCode, String } /** - * Create a Solana account + * Create Solana account * Creates a new Solana account. * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -109,7 +109,7 @@ public SolanaAccount createSolanaAccount(String xWalletAuth, String xIdempotency } /** - * Create a Solana account + * Create Solana account * Creates a new Solana account. * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -190,7 +190,7 @@ private HttpRequest.Builder createSolanaAccountRequestBuilder(String xWalletAuth } /** - * Export an Solana account + * Export Solana account * Export an existing Solana account's private key. It is important to store the private key in a secure place after it's exported. * @param address The base58 encoded address of the Solana account. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -205,7 +205,7 @@ public ExportSolanaAccount200Response exportSolanaAccount(String address, String } /** - * Export an Solana account + * Export Solana account * Export an existing Solana account's private key. It is important to store the private key in a secure place after it's exported. * @param address The base58 encoded address of the Solana account. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -292,7 +292,7 @@ private HttpRequest.Builder exportSolanaAccountRequestBuilder(String address, St } /** - * Export a Solana account by name + * Export Solana account by name * Export an existing Solana account's private key by its name. It is important to store the private key in a secure place after it's exported. * @param name The name of the Solana account. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -307,7 +307,7 @@ public ExportSolanaAccount200Response exportSolanaAccountByName(String name, Str } /** - * Export a Solana account by name + * Export Solana account by name * Export an existing Solana account's private key by its name. It is important to store the private key in a secure place after it's exported. * @param name The name of the Solana account. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -394,7 +394,7 @@ private HttpRequest.Builder exportSolanaAccountByNameRequestBuilder(String name, } /** - * Get a Solana account by address + * Get Solana account by address * Gets a Solana account by its address. * @param address The base58 encoded address of the Solana account. (required) * @return SolanaAccount @@ -406,7 +406,7 @@ public SolanaAccount getSolanaAccount(String address) throws ApiException { } /** - * Get a Solana account by address + * Get Solana account by address * Gets a Solana account by its address. * @param address The base58 encoded address of the Solana account. (required) * @return ApiResponse<SolanaAccount> @@ -478,7 +478,7 @@ private HttpRequest.Builder getSolanaAccountRequestBuilder(String address) throw } /** - * Get a Solana account by name + * Get Solana account by name * Gets a Solana account by its name. * @param name The name of the Solana account. (required) * @return SolanaAccount @@ -490,7 +490,7 @@ public SolanaAccount getSolanaAccountByName(String name) throws ApiException { } /** - * Get a Solana account by name + * Get Solana account by name * Gets a Solana account by its name. * @param name The name of the Solana account. (required) * @return ApiResponse<SolanaAccount> @@ -562,7 +562,7 @@ private HttpRequest.Builder getSolanaAccountByNameRequestBuilder(String name) th } /** - * Import a Solana account + * Import Solana account * Import an existing Solana account into the developer's CDP Project. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -576,7 +576,7 @@ public SolanaAccount importSolanaAccount(String xWalletAuth, String xIdempotency } /** - * Import a Solana account + * Import Solana account * Import an existing Solana account into the developer's CDP Project. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -657,7 +657,7 @@ private HttpRequest.Builder importSolanaAccountRequestBuilder(String xWalletAuth } /** - * List Solana accounts or get account by name + * List Solana accounts * Lists the Solana accounts belonging to the developer. The response is paginated, and by default, returns 20 accounts per page. If a name is provided, the response will contain only the account with that name. * @param pageSize The number of resources to return per page. (optional, default to 20) * @param pageToken The token for the next page of resources, if any. (optional) @@ -670,7 +670,7 @@ public ListSolanaAccounts200Response listSolanaAccounts(Integer pageSize, String } /** - * List Solana accounts or get account by name + * List Solana accounts * Lists the Solana accounts belonging to the developer. The response is paginated, and by default, returns 20 accounts per page. If a name is provided, the response will contain only the account with that name. * @param pageSize The number of resources to return per page. (optional, default to 20) * @param pageToken The token for the next page of resources, if any. (optional) @@ -755,7 +755,7 @@ private HttpRequest.Builder listSolanaAccountsRequestBuilder(Integer pageSize, S } /** - * Send a Solana transaction + * Send Solana transaction * Signs and sends a single Solana transaction using multiple Solana accounts. The transaction may contain contain several instructions, each of which may require signatures from different account keys. The transaction should be serialized into a byte array and base64 encoded. The API handles recent blockhash management and fee estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. **Transaction types** The following transaction types are supported: * [Legacy transactions](https://solana.com/developers/guides/advanced/versions#current-transaction-versions) * [Versioned transactions](https://solana.com/developers/guides/advanced/versions) **Instruction Batching** To batch multiple operations, include multiple instructions within a single transaction. All instructions within a transaction are executed atomically - if any instruction fails, the entire transaction fails and is rolled back. **Network Support** The following Solana networks are supported: * `solana` - Solana Mainnet * `solana-devnet` - Solana Devnet The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -769,7 +769,7 @@ public SendSolanaTransactionWithEndUserAccount200Response sendSolanaTransaction( } /** - * Send a Solana transaction + * Send Solana transaction * Signs and sends a single Solana transaction using multiple Solana accounts. The transaction may contain contain several instructions, each of which may require signatures from different account keys. The transaction should be serialized into a byte array and base64 encoded. The API handles recent blockhash management and fee estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. **Transaction types** The following transaction types are supported: * [Legacy transactions](https://solana.com/developers/guides/advanced/versions#current-transaction-versions) * [Versioned transactions](https://solana.com/developers/guides/advanced/versions) **Instruction Batching** To batch multiple operations, include multiple instructions within a single transaction. All instructions within a transaction are executed atomically - if any instruction fails, the entire transaction fails and is rolled back. **Network Support** The following Solana networks are supported: * `solana` - Solana Mainnet * `solana-devnet` - Solana Devnet The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -850,7 +850,7 @@ private HttpRequest.Builder sendSolanaTransactionRequestBuilder(String xWalletAu } /** - * Sign a message + * Sign message * Signs an arbitrary message with the given Solana account. **WARNING:** Never sign a message that you didn't generate, as it can be an arbitrary transaction. For example, it might send all of your funds to an attacker. * @param address The base58 encoded address of the Solana account. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -865,7 +865,7 @@ public SignSolanaMessageWithEndUserAccount200Response signSolanaMessage(String a } /** - * Sign a message + * Sign message * Signs an arbitrary message with the given Solana account. **WARNING:** Never sign a message that you didn't generate, as it can be an arbitrary transaction. For example, it might send all of your funds to an attacker. * @param address The base58 encoded address of the Solana account. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -952,7 +952,7 @@ private HttpRequest.Builder signSolanaMessageRequestBuilder(String address, Stri } /** - * Sign a transaction + * Sign transaction * Signs a transaction with the given Solana account. The unsigned transaction should be serialized into a byte array and then encoded as base64. **Transaction types** The following transaction types are supported: * [Legacy transactions](https://solana-labs.github.io/solana-web3.js/classes/Transaction.html) * [Versioned transactions](https://solana-labs.github.io/solana-web3.js/classes/VersionedTransaction.html) The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. * @param address The base58 encoded address of the Solana account. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -967,7 +967,7 @@ public SignSolanaTransactionWithEndUserAccount200Response signSolanaTransaction( } /** - * Sign a transaction + * Sign transaction * Signs a transaction with the given Solana account. The unsigned transaction should be serialized into a byte array and then encoded as base64. **Transaction types** The following transaction types are supported: * [Legacy transactions](https://solana-labs.github.io/solana-web3.js/classes/Transaction.html) * [Versioned transactions](https://solana-labs.github.io/solana-web3.js/classes/VersionedTransaction.html) The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. * @param address The base58 encoded address of the Solana account. (required) * @param xWalletAuth A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) section of our Authentication docs for more details on how to generate your Wallet Token. (optional) @@ -1054,7 +1054,7 @@ private HttpRequest.Builder signSolanaTransactionRequestBuilder(String address, } /** - * Update a Solana account + * Update Solana account * Updates an existing Solana account. Use this to update the account's name or account-level policy. * @param address The base58 encoded address of the Solana account. (required) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) @@ -1068,7 +1068,7 @@ public SolanaAccount updateSolanaAccount(String address, String xIdempotencyKey, } /** - * Update a Solana account + * Update Solana account * Updates an existing Solana account. Use this to update the account's name or account-level policy. * @param address The base58 encoded address of the Solana account. (required) * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) diff --git a/java/src/main/java/com/coinbase/cdp/openapi/api/SqlApiApi.java b/java/src/main/java/com/coinbase/cdp/openapi/api/SqlApiApi.java index fab264319..470597626 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/api/SqlApiApi.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/api/SqlApiApi.java @@ -162,7 +162,7 @@ private HttpRequest.Builder getSQLGrammarRequestBuilder() throws ApiException { } /** - * Get schemas details + * Get schema details * Retrieve the schema information for the available tables in the SQL API's indexed data. This includes table names, column definitions, data types, and indexed fields. * @param database The name of the database to query. Defaults to \"base\" when not specified. (optional, default to base) * @param table Get the schema for a specific table. (optional) @@ -175,7 +175,7 @@ public OnchainDataSchemaResponse getSQLSchema(String database, String table) thr } /** - * Get schemas details + * Get schema details * Retrieve the schema information for the available tables in the SQL API's indexed data. This includes table names, column definitions, data types, and indexed fields. * @param database The name of the database to query. Defaults to \"base\" when not specified. (optional, default to base) * @param table Get the schema for a specific table. (optional) diff --git a/java/src/main/java/com/coinbase/cdp/openapi/api/TransfersApi.java b/java/src/main/java/com/coinbase/cdp/openapi/api/TransfersApi.java new file mode 100644 index 000000000..9cc965dd9 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/api/TransfersApi.java @@ -0,0 +1,605 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.coinbase.cdp.openapi.api; + +import com.coinbase.cdp.openapi.ApiClient; +import com.coinbase.cdp.openapi.ApiException; +import com.coinbase.cdp.openapi.ApiResponse; +import com.coinbase.cdp.openapi.Pair; + +import com.coinbase.cdp.openapi.model.DepositTravelRuleRequest; +import com.coinbase.cdp.openapi.model.DepositTravelRuleResponse; +import com.coinbase.cdp.openapi.model.Error; +import com.coinbase.cdp.openapi.model.ListTransfers200Response; +import java.time.OffsetDateTime; +import com.coinbase.cdp.openapi.model.Transfer; +import com.coinbase.cdp.openapi.model.TransferRequest; +import com.coinbase.cdp.openapi.model.TransferStatus; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.InputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.net.http.HttpRequest; +import java.nio.channels.Channels; +import java.nio.channels.Pipe; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; + +import java.util.ArrayList; +import java.util.StringJoiner; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class TransfersApi { + private final HttpClient memberVarHttpClient; + private final ObjectMapper memberVarObjectMapper; + private final String memberVarBaseUri; + private final Consumer memberVarInterceptor; + private final Duration memberVarReadTimeout; + private final Consumer> memberVarResponseInterceptor; + private final Consumer> memberVarAsyncResponseInterceptor; + + public TransfersApi() { + this(new ApiClient()); + } + + public TransfersApi(ApiClient apiClient) { + memberVarHttpClient = apiClient.getHttpClient(); + memberVarObjectMapper = apiClient.getObjectMapper(); + memberVarBaseUri = apiClient.getBaseUri(); + memberVarInterceptor = apiClient.getRequestInterceptor(); + memberVarReadTimeout = apiClient.getReadTimeout(); + memberVarResponseInterceptor = apiClient.getResponseInterceptor(); + memberVarAsyncResponseInterceptor = apiClient.getAsyncResponseInterceptor(); + } + + protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + String message = formatExceptionMessage(operationId, response.statusCode(), body); + return new ApiException(response.statusCode(), message, response.headers(), body); + } + + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; + } + return operationId + " call failed with: " + statusCode + " - " + body; + } + + /** + * Create transfer + * Create a new transfer to move funds from a source to a target. All transfers first transition to `quoted`. If `execute: false`, the transfer stays quoted until you call `/v2/transfers/{transferId}/execute`. If `execute: true`, quoted status emits momentarily before the transfer moves to `processing`, where execution proceeds. Subscribe to the transfers webhook to follow progress in real time instead of polling. + * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) + * @param transferRequest (optional) + * @return Transfer + * @throws ApiException if fails to make API call + */ + public Transfer createTransfer(String xIdempotencyKey, TransferRequest transferRequest) throws ApiException { + ApiResponse localVarResponse = createTransferWithHttpInfo(xIdempotencyKey, transferRequest); + return localVarResponse.getData(); + } + + /** + * Create transfer + * Create a new transfer to move funds from a source to a target. All transfers first transition to `quoted`. If `execute: false`, the transfer stays quoted until you call `/v2/transfers/{transferId}/execute`. If `execute: true`, quoted status emits momentarily before the transfer moves to `processing`, where execution proceeds. Subscribe to the transfers webhook to follow progress in real time instead of polling. + * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) + * @param transferRequest (optional) + * @return ApiResponse<Transfer> + * @throws ApiException if fails to make API call + */ + public ApiResponse createTransferWithHttpInfo(String xIdempotencyKey, TransferRequest transferRequest) throws ApiException { + HttpRequest.Builder localVarRequestBuilder = createTransferRequestBuilder(xIdempotencyKey, transferRequest); + try { + HttpResponse localVarResponse = memberVarHttpClient.send( + localVarRequestBuilder.build(), + HttpResponse.BodyHandlers.ofInputStream()); + if (memberVarResponseInterceptor != null) { + memberVarResponseInterceptor.accept(localVarResponse); + } + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("createTransfer", localVarResponse); + } + if (localVarResponse.body() == null) { + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + null + ); + } + + String responseBody = new String(localVarResponse.body().readAllBytes()); + localVarResponse.body().close(); + + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + responseBody.isBlank()? null: memberVarObjectMapper.readValue(responseBody, new TypeReference() {}) + ); + } finally { + } + } catch (IOException e) { + throw new ApiException(e); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ApiException(e); + } + } + + private HttpRequest.Builder createTransferRequestBuilder(String xIdempotencyKey, TransferRequest transferRequest) throws ApiException { + + HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); + + String localVarPath = "/v2/transfers"; + + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); + + if (xIdempotencyKey != null) { + localVarRequestBuilder.header("X-Idempotency-Key", xIdempotencyKey.toString()); + } + localVarRequestBuilder.header("Content-Type", "application/json"); + localVarRequestBuilder.header("Accept", "application/json"); + + try { + byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(transferRequest); + localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); + } catch (IOException e) { + throw new ApiException(e); + } + if (memberVarReadTimeout != null) { + localVarRequestBuilder.timeout(memberVarReadTimeout); + } + if (memberVarInterceptor != null) { + memberVarInterceptor.accept(localVarRequestBuilder); + } + return localVarRequestBuilder; + } + + /** + * Execute transfer + * Executes a transfer which was created using the Create a transfer endpoint. + * @param transferId The ID of the transfer. (required) + * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) + * @return Transfer + * @throws ApiException if fails to make API call + */ + public Transfer executeFundTransfer(String transferId, String xIdempotencyKey) throws ApiException { + ApiResponse localVarResponse = executeFundTransferWithHttpInfo(transferId, xIdempotencyKey); + return localVarResponse.getData(); + } + + /** + * Execute transfer + * Executes a transfer which was created using the Create a transfer endpoint. + * @param transferId The ID of the transfer. (required) + * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) + * @return ApiResponse<Transfer> + * @throws ApiException if fails to make API call + */ + public ApiResponse executeFundTransferWithHttpInfo(String transferId, String xIdempotencyKey) throws ApiException { + HttpRequest.Builder localVarRequestBuilder = executeFundTransferRequestBuilder(transferId, xIdempotencyKey); + try { + HttpResponse localVarResponse = memberVarHttpClient.send( + localVarRequestBuilder.build(), + HttpResponse.BodyHandlers.ofInputStream()); + if (memberVarResponseInterceptor != null) { + memberVarResponseInterceptor.accept(localVarResponse); + } + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("executeFundTransfer", localVarResponse); + } + if (localVarResponse.body() == null) { + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + null + ); + } + + String responseBody = new String(localVarResponse.body().readAllBytes()); + localVarResponse.body().close(); + + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + responseBody.isBlank()? null: memberVarObjectMapper.readValue(responseBody, new TypeReference() {}) + ); + } finally { + } + } catch (IOException e) { + throw new ApiException(e); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ApiException(e); + } + } + + private HttpRequest.Builder executeFundTransferRequestBuilder(String transferId, String xIdempotencyKey) throws ApiException { + // verify the required parameter 'transferId' is set + if (transferId == null) { + throw new ApiException(400, "Missing the required parameter 'transferId' when calling executeFundTransfer"); + } + + HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); + + String localVarPath = "/v2/transfers/{transferId}/execute" + .replace("{transferId}", ApiClient.urlEncode(transferId.toString())); + + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); + + if (xIdempotencyKey != null) { + localVarRequestBuilder.header("X-Idempotency-Key", xIdempotencyKey.toString()); + } + localVarRequestBuilder.header("Accept", "application/json"); + + localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.noBody()); + if (memberVarReadTimeout != null) { + localVarRequestBuilder.timeout(memberVarReadTimeout); + } + if (memberVarInterceptor != null) { + memberVarInterceptor.accept(localVarRequestBuilder); + } + return localVarRequestBuilder; + } + + /** + * Get transfer + * Get a transfer by its ID. + * @param transferId The unique identifier of the transfer. (required) + * @return Transfer + * @throws ApiException if fails to make API call + */ + public Transfer getTransferById(String transferId) throws ApiException { + ApiResponse localVarResponse = getTransferByIdWithHttpInfo(transferId); + return localVarResponse.getData(); + } + + /** + * Get transfer + * Get a transfer by its ID. + * @param transferId The unique identifier of the transfer. (required) + * @return ApiResponse<Transfer> + * @throws ApiException if fails to make API call + */ + public ApiResponse getTransferByIdWithHttpInfo(String transferId) throws ApiException { + HttpRequest.Builder localVarRequestBuilder = getTransferByIdRequestBuilder(transferId); + try { + HttpResponse localVarResponse = memberVarHttpClient.send( + localVarRequestBuilder.build(), + HttpResponse.BodyHandlers.ofInputStream()); + if (memberVarResponseInterceptor != null) { + memberVarResponseInterceptor.accept(localVarResponse); + } + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("getTransferById", localVarResponse); + } + if (localVarResponse.body() == null) { + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + null + ); + } + + String responseBody = new String(localVarResponse.body().readAllBytes()); + localVarResponse.body().close(); + + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + responseBody.isBlank()? null: memberVarObjectMapper.readValue(responseBody, new TypeReference() {}) + ); + } finally { + } + } catch (IOException e) { + throw new ApiException(e); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ApiException(e); + } + } + + private HttpRequest.Builder getTransferByIdRequestBuilder(String transferId) throws ApiException { + // verify the required parameter 'transferId' is set + if (transferId == null) { + throw new ApiException(400, "Missing the required parameter 'transferId' when calling getTransferById"); + } + + HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); + + String localVarPath = "/v2/transfers/{transferId}" + .replace("{transferId}", ApiClient.urlEncode(transferId.toString())); + + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); + + localVarRequestBuilder.header("Accept", "application/json"); + + localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); + if (memberVarReadTimeout != null) { + localVarRequestBuilder.timeout(memberVarReadTimeout); + } + if (memberVarInterceptor != null) { + memberVarInterceptor.accept(localVarRequestBuilder); + } + return localVarRequestBuilder; + } + + /** + * List transfers + * List transfers for your organization. Use this to view and monitor your transfer activity. **Status Filtering**: Filter by specific status to efficiently manage transfers: * `?status=processing` - Monitor active transfers. * `?status=quoted` - Find transfers awaiting execution. * `?status=failed` - Review failed transfers for troubleshooting. * `?status=completed` - Find completed transfers. **Account Filtering**: Filter by account ID to find transfers involving a specific account: * `?accountId=<ID>` - All transfers where the account is either source or target (OR semantics). * `?sourceAccountId=<ID>` - Only transfers where the account is the source (outbound). * `?targetAccountId=<ID>` - Only transfers where the account is the target (inbound). Providing `accountId` together with `sourceAccountId` or `targetAccountId` is a validation error and returns HTTP 400. **Date Range Filtering**: Filter by creation or last-updated time for reconciliation: * `?createdAfter=2026-01-01T00:00:00Z&createdBefore=2026-01-31T23:59:59Z` - Transfers created within a date range. * `?updatedAfter=2026-01-01T00:00:00Z` - Transfers updated since a given time. Useful for incremental sync. **Asset Filtering**: Filter by source or target asset symbol: * `?sourceAsset=usd` - Transfers funded from a USD account. * `?targetAsset=usdc` - Transfers delivering USDC to the target. **Other Filters**: * `?sourceAddress=0x...` - Transfers from a specific on-chain source address. * `?targetAddress=0x...` - Transfers to a specific on-chain destination address. * `?targetEmail=user@example.com` - Transfers to a specific email recipient. * `?transferId=transfer_...` - Look up a single transfer by ID; bypasses pagination. + * @param status Filter transfers by status. Useful for building dashboards, monitoring active transfers, or finding transfers needing action. (optional) + * @param accountId Filter transfers by account ID. Returns transfers where the specified account is either the source or target (OR semantics). Cannot be combined with `sourceAccountId` or `targetAccountId`. (optional) + * @param sourceAccountId Filter transfers by source account ID. Returns only transfers where the specified account is the source. Cannot be combined with `accountId`. (optional) + * @param targetAccountId Filter transfers by target account ID. Returns only transfers where the specified account is the target. Cannot be combined with `accountId`. (optional) + * @param createdAfter Filter transfers to those created at or after this datetime (inclusive). ISO 8601 format. (optional) + * @param createdBefore Filter transfers to those created at or before this datetime (inclusive). ISO 8601 format. (optional) + * @param updatedAfter Filter transfers to those updated at or after this datetime (inclusive). ISO 8601 format. Useful for incremental sync — poll for transfers that changed state since your last check. (optional) + * @param updatedBefore Filter transfers to those updated at or before this datetime (inclusive). ISO 8601 format. (optional) + * @param sourceAsset Filter transfers by source asset symbol (e.g., `usd`, `usdc`). (optional) + * @param targetAsset Filter transfers by target asset symbol (e.g., `usdc`, `eth`). (optional) + * @param sourceAddress Filter transfers by the on-chain address of the source. (optional) + * @param targetAddress Filter transfers by the on-chain destination address of the target. (optional) + * @param targetEmail Filter transfers by the email address of the target recipient. (optional) + * @param transferId Filter to a specific transfer by ID. When provided, returns only the matching transfer and bypasses pagination. (optional) + * @param pageSize The number of resources to return per page. (optional, default to 20) + * @param pageToken The token for the next page of resources, if any. (optional) + * @return ListTransfers200Response + * @throws ApiException if fails to make API call + */ + public ListTransfers200Response listTransfers(TransferStatus status, String accountId, String sourceAccountId, String targetAccountId, OffsetDateTime createdAfter, OffsetDateTime createdBefore, OffsetDateTime updatedAfter, OffsetDateTime updatedBefore, String sourceAsset, String targetAsset, String sourceAddress, String targetAddress, String targetEmail, String transferId, Integer pageSize, String pageToken) throws ApiException { + ApiResponse localVarResponse = listTransfersWithHttpInfo(status, accountId, sourceAccountId, targetAccountId, createdAfter, createdBefore, updatedAfter, updatedBefore, sourceAsset, targetAsset, sourceAddress, targetAddress, targetEmail, transferId, pageSize, pageToken); + return localVarResponse.getData(); + } + + /** + * List transfers + * List transfers for your organization. Use this to view and monitor your transfer activity. **Status Filtering**: Filter by specific status to efficiently manage transfers: * `?status=processing` - Monitor active transfers. * `?status=quoted` - Find transfers awaiting execution. * `?status=failed` - Review failed transfers for troubleshooting. * `?status=completed` - Find completed transfers. **Account Filtering**: Filter by account ID to find transfers involving a specific account: * `?accountId=<ID>` - All transfers where the account is either source or target (OR semantics). * `?sourceAccountId=<ID>` - Only transfers where the account is the source (outbound). * `?targetAccountId=<ID>` - Only transfers where the account is the target (inbound). Providing `accountId` together with `sourceAccountId` or `targetAccountId` is a validation error and returns HTTP 400. **Date Range Filtering**: Filter by creation or last-updated time for reconciliation: * `?createdAfter=2026-01-01T00:00:00Z&createdBefore=2026-01-31T23:59:59Z` - Transfers created within a date range. * `?updatedAfter=2026-01-01T00:00:00Z` - Transfers updated since a given time. Useful for incremental sync. **Asset Filtering**: Filter by source or target asset symbol: * `?sourceAsset=usd` - Transfers funded from a USD account. * `?targetAsset=usdc` - Transfers delivering USDC to the target. **Other Filters**: * `?sourceAddress=0x...` - Transfers from a specific on-chain source address. * `?targetAddress=0x...` - Transfers to a specific on-chain destination address. * `?targetEmail=user@example.com` - Transfers to a specific email recipient. * `?transferId=transfer_...` - Look up a single transfer by ID; bypasses pagination. + * @param status Filter transfers by status. Useful for building dashboards, monitoring active transfers, or finding transfers needing action. (optional) + * @param accountId Filter transfers by account ID. Returns transfers where the specified account is either the source or target (OR semantics). Cannot be combined with `sourceAccountId` or `targetAccountId`. (optional) + * @param sourceAccountId Filter transfers by source account ID. Returns only transfers where the specified account is the source. Cannot be combined with `accountId`. (optional) + * @param targetAccountId Filter transfers by target account ID. Returns only transfers where the specified account is the target. Cannot be combined with `accountId`. (optional) + * @param createdAfter Filter transfers to those created at or after this datetime (inclusive). ISO 8601 format. (optional) + * @param createdBefore Filter transfers to those created at or before this datetime (inclusive). ISO 8601 format. (optional) + * @param updatedAfter Filter transfers to those updated at or after this datetime (inclusive). ISO 8601 format. Useful for incremental sync — poll for transfers that changed state since your last check. (optional) + * @param updatedBefore Filter transfers to those updated at or before this datetime (inclusive). ISO 8601 format. (optional) + * @param sourceAsset Filter transfers by source asset symbol (e.g., `usd`, `usdc`). (optional) + * @param targetAsset Filter transfers by target asset symbol (e.g., `usdc`, `eth`). (optional) + * @param sourceAddress Filter transfers by the on-chain address of the source. (optional) + * @param targetAddress Filter transfers by the on-chain destination address of the target. (optional) + * @param targetEmail Filter transfers by the email address of the target recipient. (optional) + * @param transferId Filter to a specific transfer by ID. When provided, returns only the matching transfer and bypasses pagination. (optional) + * @param pageSize The number of resources to return per page. (optional, default to 20) + * @param pageToken The token for the next page of resources, if any. (optional) + * @return ApiResponse<ListTransfers200Response> + * @throws ApiException if fails to make API call + */ + public ApiResponse listTransfersWithHttpInfo(TransferStatus status, String accountId, String sourceAccountId, String targetAccountId, OffsetDateTime createdAfter, OffsetDateTime createdBefore, OffsetDateTime updatedAfter, OffsetDateTime updatedBefore, String sourceAsset, String targetAsset, String sourceAddress, String targetAddress, String targetEmail, String transferId, Integer pageSize, String pageToken) throws ApiException { + HttpRequest.Builder localVarRequestBuilder = listTransfersRequestBuilder(status, accountId, sourceAccountId, targetAccountId, createdAfter, createdBefore, updatedAfter, updatedBefore, sourceAsset, targetAsset, sourceAddress, targetAddress, targetEmail, transferId, pageSize, pageToken); + try { + HttpResponse localVarResponse = memberVarHttpClient.send( + localVarRequestBuilder.build(), + HttpResponse.BodyHandlers.ofInputStream()); + if (memberVarResponseInterceptor != null) { + memberVarResponseInterceptor.accept(localVarResponse); + } + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("listTransfers", localVarResponse); + } + if (localVarResponse.body() == null) { + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + null + ); + } + + String responseBody = new String(localVarResponse.body().readAllBytes()); + localVarResponse.body().close(); + + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + responseBody.isBlank()? null: memberVarObjectMapper.readValue(responseBody, new TypeReference() {}) + ); + } finally { + } + } catch (IOException e) { + throw new ApiException(e); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ApiException(e); + } + } + + private HttpRequest.Builder listTransfersRequestBuilder(TransferStatus status, String accountId, String sourceAccountId, String targetAccountId, OffsetDateTime createdAfter, OffsetDateTime createdBefore, OffsetDateTime updatedAfter, OffsetDateTime updatedBefore, String sourceAsset, String targetAsset, String sourceAddress, String targetAddress, String targetEmail, String transferId, Integer pageSize, String pageToken) throws ApiException { + + HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); + + String localVarPath = "/v2/transfers"; + + List localVarQueryParams = new ArrayList<>(); + StringJoiner localVarQueryStringJoiner = new StringJoiner("&"); + String localVarQueryParameterBaseName; + localVarQueryParameterBaseName = "status"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("status", status)); + localVarQueryParameterBaseName = "accountId"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("accountId", accountId)); + localVarQueryParameterBaseName = "sourceAccountId"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("sourceAccountId", sourceAccountId)); + localVarQueryParameterBaseName = "targetAccountId"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("targetAccountId", targetAccountId)); + localVarQueryParameterBaseName = "createdAfter"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("createdAfter", createdAfter)); + localVarQueryParameterBaseName = "createdBefore"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("createdBefore", createdBefore)); + localVarQueryParameterBaseName = "updatedAfter"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("updatedAfter", updatedAfter)); + localVarQueryParameterBaseName = "updatedBefore"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("updatedBefore", updatedBefore)); + localVarQueryParameterBaseName = "sourceAsset"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("sourceAsset", sourceAsset)); + localVarQueryParameterBaseName = "targetAsset"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("targetAsset", targetAsset)); + localVarQueryParameterBaseName = "sourceAddress"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("sourceAddress", sourceAddress)); + localVarQueryParameterBaseName = "targetAddress"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("targetAddress", targetAddress)); + localVarQueryParameterBaseName = "targetEmail"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("targetEmail", targetEmail)); + localVarQueryParameterBaseName = "transferId"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("transferId", transferId)); + localVarQueryParameterBaseName = "pageSize"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("pageSize", pageSize)); + localVarQueryParameterBaseName = "pageToken"; + localVarQueryParams.addAll(ApiClient.parameterToPairs("pageToken", pageToken)); + + if (!localVarQueryParams.isEmpty() || localVarQueryStringJoiner.length() != 0) { + StringJoiner queryJoiner = new StringJoiner("&"); + localVarQueryParams.forEach(p -> queryJoiner.add(p.getName() + '=' + p.getValue())); + if (localVarQueryStringJoiner.length() != 0) { + queryJoiner.add(localVarQueryStringJoiner.toString()); + } + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath + '?' + queryJoiner.toString())); + } else { + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); + } + + localVarRequestBuilder.header("Accept", "application/json"); + + localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); + if (memberVarReadTimeout != null) { + localVarRequestBuilder.timeout(memberVarReadTimeout); + } + if (memberVarInterceptor != null) { + memberVarInterceptor.accept(localVarRequestBuilder); + } + return localVarRequestBuilder; + } + + /** + * Submit deposit travel rule information + * Submit travel rule information for a deposit transfer held pending compliance review. Required fields vary by jurisdiction and may include originator name, address, date of birth, personal ID, and VASP information. If the submitted information satisfies all jurisdictional requirements, `status` will be `completed` and the transfer will proceed. Otherwise, `status` will be `incomplete` and `missingFields` will indicate which fields still need to be provided. + * @param transferId The unique identifier of the transfer. (required) + * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) + * @param depositTravelRuleRequest (optional) + * @return DepositTravelRuleResponse + * @throws ApiException if fails to make API call + */ + public DepositTravelRuleResponse submitDepositTravelRule(String transferId, String xIdempotencyKey, DepositTravelRuleRequest depositTravelRuleRequest) throws ApiException { + ApiResponse localVarResponse = submitDepositTravelRuleWithHttpInfo(transferId, xIdempotencyKey, depositTravelRuleRequest); + return localVarResponse.getData(); + } + + /** + * Submit deposit travel rule information + * Submit travel rule information for a deposit transfer held pending compliance review. Required fields vary by jurisdiction and may include originator name, address, date of birth, personal ID, and VASP information. If the submitted information satisfies all jurisdictional requirements, `status` will be `completed` and the transfer will proceed. Otherwise, `status` will be `incomplete` and `missingFields` will indicate which fields still need to be provided. + * @param transferId The unique identifier of the transfer. (required) + * @param xIdempotencyKey An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. (optional) + * @param depositTravelRuleRequest (optional) + * @return ApiResponse<DepositTravelRuleResponse> + * @throws ApiException if fails to make API call + */ + public ApiResponse submitDepositTravelRuleWithHttpInfo(String transferId, String xIdempotencyKey, DepositTravelRuleRequest depositTravelRuleRequest) throws ApiException { + HttpRequest.Builder localVarRequestBuilder = submitDepositTravelRuleRequestBuilder(transferId, xIdempotencyKey, depositTravelRuleRequest); + try { + HttpResponse localVarResponse = memberVarHttpClient.send( + localVarRequestBuilder.build(), + HttpResponse.BodyHandlers.ofInputStream()); + if (memberVarResponseInterceptor != null) { + memberVarResponseInterceptor.accept(localVarResponse); + } + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("submitDepositTravelRule", localVarResponse); + } + if (localVarResponse.body() == null) { + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + null + ); + } + + String responseBody = new String(localVarResponse.body().readAllBytes()); + localVarResponse.body().close(); + + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + responseBody.isBlank()? null: memberVarObjectMapper.readValue(responseBody, new TypeReference() {}) + ); + } finally { + } + } catch (IOException e) { + throw new ApiException(e); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ApiException(e); + } + } + + private HttpRequest.Builder submitDepositTravelRuleRequestBuilder(String transferId, String xIdempotencyKey, DepositTravelRuleRequest depositTravelRuleRequest) throws ApiException { + // verify the required parameter 'transferId' is set + if (transferId == null) { + throw new ApiException(400, "Missing the required parameter 'transferId' when calling submitDepositTravelRule"); + } + + HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); + + String localVarPath = "/v2/transfers/{transferId}/travel-rule" + .replace("{transferId}", ApiClient.urlEncode(transferId.toString())); + + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); + + if (xIdempotencyKey != null) { + localVarRequestBuilder.header("X-Idempotency-Key", xIdempotencyKey.toString()); + } + localVarRequestBuilder.header("Content-Type", "application/json"); + localVarRequestBuilder.header("Accept", "application/json"); + + try { + byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(depositTravelRuleRequest); + localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); + } catch (IOException e) { + throw new ApiException(e); + } + if (memberVarReadTimeout != null) { + localVarRequestBuilder.timeout(memberVarReadTimeout); + } + if (memberVarInterceptor != null) { + memberVarInterceptor.accept(localVarRequestBuilder); + } + return localVarRequestBuilder; + } + +} diff --git a/java/src/main/java/com/coinbase/cdp/openapi/api/WebhooksApi.java b/java/src/main/java/com/coinbase/cdp/openapi/api/WebhooksApi.java index 66b735d35..49f839dcf 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/api/WebhooksApi.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/api/WebhooksApi.java @@ -254,7 +254,7 @@ private HttpRequest.Builder deleteWebhookSubscriptionRequestBuilder(UUID subscri } /** - * Get webhook subscription details + * Get webhook subscription * Retrieve detailed information about a specific webhook subscription including configuration, status, creation timestamp, and webhook signature secret. ### Response Includes - Subscription configuration and filters - Target URL and custom headers - Webhook signature secret for verification - Creation timestamp and status * @param subscriptionId Unique identifier for the webhook subscription. (required) * @return WebhookSubscriptionResponse @@ -266,7 +266,7 @@ public WebhookSubscriptionResponse getWebhookSubscription(UUID subscriptionId) t } /** - * Get webhook subscription details + * Get webhook subscription * Retrieve detailed information about a specific webhook subscription including configuration, status, creation timestamp, and webhook signature secret. ### Response Includes - Subscription configuration and filters - Target URL and custom headers - Webhook signature secret for verification - Creation timestamp and status * @param subscriptionId Unique identifier for the webhook subscription. (required) * @return ApiResponse<WebhookSubscriptionResponse> diff --git a/java/src/main/java/com/coinbase/cdp/openapi/api/X402FacilitatorApi.java b/java/src/main/java/com/coinbase/cdp/openapi/api/X402FacilitatorApi.java index 0a621ff80..9aa1bbd46 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/api/X402FacilitatorApi.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/api/X402FacilitatorApi.java @@ -199,7 +199,7 @@ private HttpRequest.Builder listX402DiscoveryMerchantRequestBuilder(String payTo } /** - * List discovered x402 resources + * List x402 resources * Lists all active discovered x402 resources. This endpoint returns resources that have been discovered and cached by the x402 facilitator, including their payment requirements and metadata. The response is paginated, and by default, returns 100 items per page. * @param type Filter by protocol type (e.g., \"http\", \"mcp\"). Currently, the only supported protocol type is \"http\". (optional) * @param limit The number of discovered x402 resources to return per page. (optional, default to 100) @@ -213,7 +213,7 @@ public X402DiscoveryResourcesResponse listX402DiscoveryResources(String type, In } /** - * List discovered x402 resources + * List x402 resources * Lists all active discovered x402 resources. This endpoint returns resources that have been discovered and cached by the x402 facilitator, including their payment requirements and metadata. The response is paginated, and by default, returns 100 items per page. * @param type Filter by protocol type (e.g., \"http\", \"mcp\"). Currently, the only supported protocol type is \"http\". (optional) * @param limit The number of discovered x402 resources to return per page. (optional, default to 100) @@ -516,7 +516,7 @@ private HttpRequest.Builder searchX402ResourcesRequestBuilder(String query, Stri } /** - * Settle a payment + * Settle payment * Settle an x402 protocol payment with a specific scheme and network. * @param verifyX402PaymentRequest (required) * @return InlineObject1 @@ -528,7 +528,7 @@ public InlineObject1 settleX402Payment(VerifyX402PaymentRequest verifyX402Paymen } /** - * Settle a payment + * Settle payment * Settle an x402 protocol payment with a specific scheme and network. * @param verifyX402PaymentRequest (required) * @return ApiResponse<InlineObject1> @@ -682,7 +682,7 @@ private HttpRequest.Builder supportedX402PaymentKindsRequestBuilder() throws Api } /** - * Verify a payment + * Verify payment * Verify an x402 protocol payment with a specific scheme and network. * @param verifyX402PaymentRequest (required) * @return InlineObject @@ -694,7 +694,7 @@ public InlineObject verifyX402Payment(VerifyX402PaymentRequest verifyX402Payment } /** - * Verify a payment + * Verify payment * Verify an x402 protocol payment with a specific scheme and network. * @param verifyX402PaymentRequest (required) * @return ApiResponse<InlineObject> diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/Account.java b/java/src/main/java/com/coinbase/cdp/openapi/model/Account.java new file mode 100644 index 000000000..817219477 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/Account.java @@ -0,0 +1,412 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.AccountType; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * Account + */ +@JsonPropertyOrder({ + Account.JSON_PROPERTY_ACCOUNT_ID, + Account.JSON_PROPERTY_TYPE, + Account.JSON_PROPERTY_OWNER, + Account.JSON_PROPERTY_NAME, + Account.JSON_PROPERTY_CREATED_AT, + Account.JSON_PROPERTY_UPDATED_AT +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class Account { + public static final String JSON_PROPERTY_ACCOUNT_ID = "accountId"; + @jakarta.annotation.Nonnull + private String accountId; + + public static final String JSON_PROPERTY_TYPE = "type"; + @jakarta.annotation.Nonnull + private AccountType type; + + public static final String JSON_PROPERTY_OWNER = "owner"; + @jakarta.annotation.Nonnull + private String owner; + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nullable + private String name; + + public static final String JSON_PROPERTY_CREATED_AT = "createdAt"; + @jakarta.annotation.Nonnull + private OffsetDateTime createdAt; + + public static final String JSON_PROPERTY_UPDATED_AT = "updatedAt"; + @jakarta.annotation.Nonnull + private OffsetDateTime updatedAt; + + public Account() { + } + + public Account accountId(@jakarta.annotation.Nonnull String accountId) { + this.accountId = accountId; + return this; + } + + /** + * The ID of the Account, which is a UUID prefixed by the string `account_`. + * @return accountId + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ACCOUNT_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAccountId() { + return accountId; + } + + + @JsonProperty(JSON_PROPERTY_ACCOUNT_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAccountId(@jakarta.annotation.Nonnull String accountId) { + this.accountId = accountId; + } + + + public Account type(@jakarta.annotation.Nonnull AccountType type) { + this.type = type; + return this; + } + + /** + * Get type + * @return type + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_TYPE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public AccountType getType() { + return type; + } + + + @JsonProperty(JSON_PROPERTY_TYPE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setType(@jakarta.annotation.Nonnull AccountType type) { + this.type = type; + } + + + public Account owner(@jakarta.annotation.Nonnull String owner) { + this.owner = owner; + return this; + } + + /** + * The Owner ID of the Account. Owner IDs are UUIDs prefixed with the Owner Type as follows: * **Entity**: `entity_` - If the Owner is your Entity, e.g. `entity_af2937b0-9846-4fe7-bfe9-ccc22d935114`. Support for Customer-owned accounts (`customer_` prefix) is in development. + * @return owner + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_OWNER) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getOwner() { + return owner; + } + + + @JsonProperty(JSON_PROPERTY_OWNER) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setOwner(@jakarta.annotation.Nonnull String owner) { + this.owner = owner; + } + + + public Account name(@jakarta.annotation.Nullable String name) { + this.name = name; + return this; + } + + /** + * An optional name for the account. Must be 1-64 characters and can only contain alphanumeric characters, hyphens, and spaces. + * @return name + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getName() { + return name; + } + + + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setName(@jakarta.annotation.Nullable String name) { + this.name = name; + } + + + public Account createdAt(@jakarta.annotation.Nonnull OffsetDateTime createdAt) { + this.createdAt = createdAt; + return this; + } + + /** + * The timestamp when the account was created. + * @return createdAt + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_CREATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public OffsetDateTime getCreatedAt() { + return createdAt; + } + + + @JsonProperty(JSON_PROPERTY_CREATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCreatedAt(@jakarta.annotation.Nonnull OffsetDateTime createdAt) { + this.createdAt = createdAt; + } + + + public Account updatedAt(@jakarta.annotation.Nonnull OffsetDateTime updatedAt) { + this.updatedAt = updatedAt; + return this; + } + + /** + * The timestamp when the account was last updated. + * @return updatedAt + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_UPDATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public OffsetDateTime getUpdatedAt() { + return updatedAt; + } + + + @JsonProperty(JSON_PROPERTY_UPDATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUpdatedAt(@jakarta.annotation.Nonnull OffsetDateTime updatedAt) { + this.updatedAt = updatedAt; + } + + + /** + * Return true if this Account object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Account account = (Account) o; + return Objects.equals(this.accountId, account.accountId) && + Objects.equals(this.type, account.type) && + Objects.equals(this.owner, account.owner) && + Objects.equals(this.name, account.name) && + Objects.equals(this.createdAt, account.createdAt) && + Objects.equals(this.updatedAt, account.updatedAt); + } + + @Override + public int hashCode() { + return Objects.hash(accountId, type, owner, name, createdAt, updatedAt); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Account {\n"); + sb.append(" accountId: ").append(toIndentedString(accountId)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" owner: ").append(toIndentedString(owner)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); + sb.append(" updatedAt: ").append(toIndentedString(updatedAt)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `accountId` to the URL query string + if (getAccountId() != null) { + joiner.add(String.format("%saccountId%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAccountId()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `type` to the URL query string + if (getType() != null) { + joiner.add(String.format("%stype%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getType()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `owner` to the URL query string + if (getOwner() != null) { + joiner.add(String.format("%sowner%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getOwner()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `name` to the URL query string + if (getName() != null) { + joiner.add(String.format("%sname%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getName()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `createdAt` to the URL query string + if (getCreatedAt() != null) { + joiner.add(String.format("%screatedAt%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getCreatedAt()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `updatedAt` to the URL query string + if (getUpdatedAt() != null) { + joiner.add(String.format("%supdatedAt%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getUpdatedAt()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private Account instance; + + public Builder() { + this(new Account()); + } + + protected Builder(Account instance) { + this.instance = instance; + } + + public Account.Builder accountId(String accountId) { + this.instance.accountId = accountId; + return this; + } + public Account.Builder type(AccountType type) { + this.instance.type = type; + return this; + } + public Account.Builder owner(String owner) { + this.instance.owner = owner; + return this; + } + public Account.Builder name(String name) { + this.instance.name = name; + return this; + } + public Account.Builder createdAt(OffsetDateTime createdAt) { + this.instance.createdAt = createdAt; + return this; + } + public Account.Builder updatedAt(OffsetDateTime updatedAt) { + this.instance.updatedAt = updatedAt; + return this; + } + + + /** + * returns a built Account instance. + * + * The builder is not reusable. + */ + public Account build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static Account.Builder builder() { + return new Account.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public Account.Builder toBuilder() { + return new Account.Builder() + .accountId(getAccountId()) + .type(getType()) + .owner(getOwner()) + .name(getName()) + .createdAt(getCreatedAt()) + .updatedAt(getUpdatedAt()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/AccountType.java b/java/src/main/java/com/coinbase/cdp/openapi/model/AccountType.java new file mode 100644 index 000000000..95652c6c8 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/AccountType.java @@ -0,0 +1,80 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * The type of the Account. + */ +public enum AccountType { + + PRIME("prime"), + + BUSINESS("business"), + + CDP("cdp"); + + private String value; + + AccountType(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static AccountType fromValue(String value) { + for (AccountType b : AccountType.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + if (prefix == null) { + prefix = ""; + } + + return String.format("%s=%s", prefix, this.toString()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/AmountDetail.java b/java/src/main/java/com/coinbase/cdp/openapi/model/AmountDetail.java new file mode 100644 index 000000000..c91544ca5 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/AmountDetail.java @@ -0,0 +1,246 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * Available and total amounts for a specific currency. + */ +@JsonPropertyOrder({ + AmountDetail.JSON_PROPERTY_AVAILABLE, + AmountDetail.JSON_PROPERTY_TOTAL +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class AmountDetail { + public static final String JSON_PROPERTY_AVAILABLE = "available"; + @jakarta.annotation.Nonnull + private String available; + + public static final String JSON_PROPERTY_TOTAL = "total"; + @jakarta.annotation.Nonnull + private String total; + + public AmountDetail() { + } + + public AmountDetail available(@jakarta.annotation.Nonnull String available) { + this.available = available; + return this; + } + + /** + * The amount that is currently available to be used. + * @return available + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_AVAILABLE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAvailable() { + return available; + } + + + @JsonProperty(JSON_PROPERTY_AVAILABLE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAvailable(@jakarta.annotation.Nonnull String available) { + this.available = available; + } + + + public AmountDetail total(@jakarta.annotation.Nonnull String total) { + this.total = total; + return this; + } + + /** + * The total amount, including the amount that is currently on hold. + * @return total + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_TOTAL) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getTotal() { + return total; + } + + + @JsonProperty(JSON_PROPERTY_TOTAL) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTotal(@jakarta.annotation.Nonnull String total) { + this.total = total; + } + + + /** + * Return true if this AmountDetail object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AmountDetail amountDetail = (AmountDetail) o; + return Objects.equals(this.available, amountDetail.available) && + Objects.equals(this.total, amountDetail.total); + } + + @Override + public int hashCode() { + return Objects.hash(available, total); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AmountDetail {\n"); + sb.append(" available: ").append(toIndentedString(available)).append("\n"); + sb.append(" total: ").append(toIndentedString(total)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `available` to the URL query string + if (getAvailable() != null) { + joiner.add(String.format("%savailable%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAvailable()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `total` to the URL query string + if (getTotal() != null) { + joiner.add(String.format("%stotal%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getTotal()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private AmountDetail instance; + + public Builder() { + this(new AmountDetail()); + } + + protected Builder(AmountDetail instance) { + this.instance = instance; + } + + public AmountDetail.Builder available(String available) { + this.instance.available = available; + return this; + } + public AmountDetail.Builder total(String total) { + this.instance.total = total; + return this; + } + + + /** + * returns a built AmountDetail instance. + * + * The builder is not reusable. + */ + public AmountDetail build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static AmountDetail.Builder builder() { + return new AmountDetail.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public AmountDetail.Builder toBuilder() { + return new AmountDetail.Builder() + .available(getAvailable()) + .total(getTotal()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/AssetType.java b/java/src/main/java/com/coinbase/cdp/openapi/model/AssetType.java new file mode 100644 index 000000000..36ac5011b --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/AssetType.java @@ -0,0 +1,78 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * The type of the asset. + */ +public enum AssetType { + + FIAT("fiat"), + + CRYPTO("crypto"); + + private String value; + + AssetType(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static AssetType fromValue(String value) { + for (AssetType b : AssetType.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + if (prefix == null) { + prefix = ""; + } + + return String.format("%s=%s", prefix, this.toString()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/Balance.java b/java/src/main/java/com/coinbase/cdp/openapi/model/Balance.java new file mode 100644 index 000000000..87e3b7682 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/Balance.java @@ -0,0 +1,263 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.AmountDetail; +import com.coinbase.cdp.openapi.model.BalancesAsset; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * A balance of an asset. + */ +@JsonPropertyOrder({ + Balance.JSON_PROPERTY_ASSET, + Balance.JSON_PROPERTY_AMOUNT +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class Balance { + public static final String JSON_PROPERTY_ASSET = "asset"; + @jakarta.annotation.Nonnull + private BalancesAsset asset; + + public static final String JSON_PROPERTY_AMOUNT = "amount"; + @jakarta.annotation.Nonnull + private Map amount = new HashMap<>(); + + public Balance() { + } + + public Balance asset(@jakarta.annotation.Nonnull BalancesAsset asset) { + this.asset = asset; + return this; + } + + /** + * Get asset + * @return asset + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public BalancesAsset getAsset() { + return asset; + } + + + @JsonProperty(JSON_PROPERTY_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAsset(@jakarta.annotation.Nonnull BalancesAsset asset) { + this.asset = asset; + } + + + public Balance amount(@jakarta.annotation.Nonnull Map amount) { + this.amount = amount; + return this; + } + + public Balance putAmountItem(String key, AmountDetail amountItem) { + if (this.amount == null) { + this.amount = new HashMap<>(); + } + this.amount.put(key, amountItem); + return this; + } + + /** + * Amount details denominated in different assets. - The keys represent the asset symbols (e.g., \"btc\", \"usd\"), - Each value contains available and total amounts. - There will always be an entry for the asset specified in the `asset` field. + * @return amount + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_AMOUNT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public Map getAmount() { + return amount; + } + + + @JsonProperty(JSON_PROPERTY_AMOUNT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAmount(@jakarta.annotation.Nonnull Map amount) { + this.amount = amount; + } + + + /** + * Return true if this Balance object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Balance balance = (Balance) o; + return Objects.equals(this.asset, balance.asset) && + Objects.equals(this.amount, balance.amount); + } + + @Override + public int hashCode() { + return Objects.hash(asset, amount); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Balance {\n"); + sb.append(" asset: ").append(toIndentedString(asset)).append("\n"); + sb.append(" amount: ").append(toIndentedString(amount)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `asset` to the URL query string + if (getAsset() != null) { + joiner.add(getAsset().toUrlQueryString(prefix + "asset" + suffix)); + } + + // add `amount` to the URL query string + if (getAmount() != null) { + for (String _key : getAmount().keySet()) { + if (getAmount().get(_key) != null) { + joiner.add(getAmount().get(_key).toUrlQueryString(String.format("%samount%s%s", prefix, suffix, + "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, _key, containerSuffix)))); + } + } + } + + return joiner.toString(); + } + + public static class Builder { + + private Balance instance; + + public Builder() { + this(new Balance()); + } + + protected Builder(Balance instance) { + this.instance = instance; + } + + public Balance.Builder asset(BalancesAsset asset) { + this.instance.asset = asset; + return this; + } + public Balance.Builder amount(Map amount) { + this.instance.amount = amount; + return this; + } + + + /** + * returns a built Balance instance. + * + * The builder is not reusable. + */ + public Balance build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static Balance.Builder builder() { + return new Balance.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public Balance.Builder toBuilder() { + return new Balance.Builder() + .asset(getAsset()) + .amount(getAmount()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/Balances.java b/java/src/main/java/com/coinbase/cdp/openapi/model/Balances.java new file mode 100644 index 000000000..49933e579 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/Balances.java @@ -0,0 +1,221 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.Balance; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * A list of balances for an account. + */ +@JsonPropertyOrder({ + Balances.JSON_PROPERTY_BALANCES +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class Balances { + public static final String JSON_PROPERTY_BALANCES = "balances"; + @jakarta.annotation.Nonnull + private List balances = new ArrayList<>(); + + public Balances() { + } + + public Balances balances(@jakarta.annotation.Nonnull List balances) { + this.balances = balances; + return this; + } + + public Balances addBalancesItem(Balance balancesItem) { + if (this.balances == null) { + this.balances = new ArrayList<>(); + } + this.balances.add(balancesItem); + return this; + } + + /** + * The list of balances. + * @return balances + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_BALANCES) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public List getBalances() { + return balances; + } + + + @JsonProperty(JSON_PROPERTY_BALANCES) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBalances(@jakarta.annotation.Nonnull List balances) { + this.balances = balances; + } + + + /** + * Return true if this Balances object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Balances balances = (Balances) o; + return Objects.equals(this.balances, balances.balances); + } + + @Override + public int hashCode() { + return Objects.hash(balances); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Balances {\n"); + sb.append(" balances: ").append(toIndentedString(balances)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `balances` to the URL query string + if (getBalances() != null) { + for (int i = 0; i < getBalances().size(); i++) { + if (getBalances().get(i) != null) { + joiner.add(getBalances().get(i).toUrlQueryString(String.format("%sbalances%s%s", prefix, suffix, + "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, i, containerSuffix)))); + } + } + } + + return joiner.toString(); + } + + public static class Builder { + + private Balances instance; + + public Builder() { + this(new Balances()); + } + + protected Builder(Balances instance) { + this.instance = instance; + } + + public Balances.Builder balances(List balances) { + this.instance.balances = balances; + return this; + } + + + /** + * returns a built Balances instance. + * + * The builder is not reusable. + */ + public Balances build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static Balances.Builder builder() { + return new Balances.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public Balances.Builder toBuilder() { + return new Balances.Builder() + .balances(getBalances()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/BalancesAsset.java b/java/src/main/java/com/coinbase/cdp/openapi/model/BalancesAsset.java new file mode 100644 index 000000000..503e7b831 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/BalancesAsset.java @@ -0,0 +1,329 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.AssetType; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * An asset, e.g. fiat or crypto. + */ +@JsonPropertyOrder({ + BalancesAsset.JSON_PROPERTY_SYMBOL, + BalancesAsset.JSON_PROPERTY_TYPE, + BalancesAsset.JSON_PROPERTY_NAME, + BalancesAsset.JSON_PROPERTY_DECIMALS +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class BalancesAsset { + public static final String JSON_PROPERTY_SYMBOL = "symbol"; + @jakarta.annotation.Nonnull + private String symbol; + + public static final String JSON_PROPERTY_TYPE = "type"; + @jakarta.annotation.Nonnull + private AssetType type; + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nonnull + private String name; + + public static final String JSON_PROPERTY_DECIMALS = "decimals"; + @jakarta.annotation.Nonnull + private Integer decimals; + + public BalancesAsset() { + } + + public BalancesAsset symbol(@jakarta.annotation.Nonnull String symbol) { + this.symbol = symbol; + return this; + } + + /** + * The symbol of the asset (e.g., eth, usd, usdc, usdt). + * @return symbol + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_SYMBOL) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getSymbol() { + return symbol; + } + + + @JsonProperty(JSON_PROPERTY_SYMBOL) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setSymbol(@jakarta.annotation.Nonnull String symbol) { + this.symbol = symbol; + } + + + public BalancesAsset type(@jakarta.annotation.Nonnull AssetType type) { + this.type = type; + return this; + } + + /** + * Get type + * @return type + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_TYPE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public AssetType getType() { + return type; + } + + + @JsonProperty(JSON_PROPERTY_TYPE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setType(@jakarta.annotation.Nonnull AssetType type) { + this.type = type; + } + + + public BalancesAsset name(@jakarta.annotation.Nonnull String name) { + this.name = name; + return this; + } + + /** + * The name of the asset. + * @return name + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getName() { + return name; + } + + + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(@jakarta.annotation.Nonnull String name) { + this.name = name; + } + + + public BalancesAsset decimals(@jakarta.annotation.Nonnull Integer decimals) { + this.decimals = decimals; + return this; + } + + /** + * The number of decimals (i.e. significant digits to the right of the decimal point) supported for the asset. + * @return decimals + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_DECIMALS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public Integer getDecimals() { + return decimals; + } + + + @JsonProperty(JSON_PROPERTY_DECIMALS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDecimals(@jakarta.annotation.Nonnull Integer decimals) { + this.decimals = decimals; + } + + + /** + * Return true if this balances_Asset object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + BalancesAsset balancesAsset = (BalancesAsset) o; + return Objects.equals(this.symbol, balancesAsset.symbol) && + Objects.equals(this.type, balancesAsset.type) && + Objects.equals(this.name, balancesAsset.name) && + Objects.equals(this.decimals, balancesAsset.decimals); + } + + @Override + public int hashCode() { + return Objects.hash(symbol, type, name, decimals); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class BalancesAsset {\n"); + sb.append(" symbol: ").append(toIndentedString(symbol)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" decimals: ").append(toIndentedString(decimals)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `symbol` to the URL query string + if (getSymbol() != null) { + joiner.add(String.format("%ssymbol%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getSymbol()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `type` to the URL query string + if (getType() != null) { + joiner.add(String.format("%stype%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getType()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `name` to the URL query string + if (getName() != null) { + joiner.add(String.format("%sname%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getName()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `decimals` to the URL query string + if (getDecimals() != null) { + joiner.add(String.format("%sdecimals%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getDecimals()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private BalancesAsset instance; + + public Builder() { + this(new BalancesAsset()); + } + + protected Builder(BalancesAsset instance) { + this.instance = instance; + } + + public BalancesAsset.Builder symbol(String symbol) { + this.instance.symbol = symbol; + return this; + } + public BalancesAsset.Builder type(AssetType type) { + this.instance.type = type; + return this; + } + public BalancesAsset.Builder name(String name) { + this.instance.name = name; + return this; + } + public BalancesAsset.Builder decimals(Integer decimals) { + this.instance.decimals = decimals; + return this; + } + + + /** + * returns a built BalancesAsset instance. + * + * The builder is not reusable. + */ + public BalancesAsset build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static BalancesAsset.Builder builder() { + return new BalancesAsset.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public BalancesAsset.Builder toBuilder() { + return new BalancesAsset.Builder() + .symbol(getSymbol()) + .type(getType()) + .name(getName()) + .decimals(getDecimals()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/CreateAccountRequest.java b/java/src/main/java/com/coinbase/cdp/openapi/model/CreateAccountRequest.java new file mode 100644 index 000000000..6d5232615 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/CreateAccountRequest.java @@ -0,0 +1,205 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * CreateAccountRequest + */ +@JsonPropertyOrder({ + CreateAccountRequest.JSON_PROPERTY_NAME +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class CreateAccountRequest { + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nullable + private String name; + + public CreateAccountRequest() { + } + + public CreateAccountRequest name(@jakarta.annotation.Nullable String name) { + this.name = name; + return this; + } + + /** + * An optional name for the account. Must be 1-64 characters and can only contain alphanumeric characters, hyphens, and spaces. + * @return name + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getName() { + return name; + } + + + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setName(@jakarta.annotation.Nullable String name) { + this.name = name; + } + + + /** + * Return true if this CreateAccountRequest object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + CreateAccountRequest createAccountRequest = (CreateAccountRequest) o; + return Objects.equals(this.name, createAccountRequest.name); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CreateAccountRequest {\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `name` to the URL query string + if (getName() != null) { + joiner.add(String.format("%sname%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getName()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private CreateAccountRequest instance; + + public Builder() { + this(new CreateAccountRequest()); + } + + protected Builder(CreateAccountRequest instance) { + this.instance = instance; + } + + public CreateAccountRequest.Builder name(String name) { + this.instance.name = name; + return this; + } + + + /** + * returns a built CreateAccountRequest instance. + * + * The builder is not reusable. + */ + public CreateAccountRequest build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static CreateAccountRequest.Builder builder() { + return new CreateAccountRequest.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public CreateAccountRequest.Builder toBuilder() { + return new CreateAccountRequest.Builder() + .name(getName()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/CreateCryptoDepositDestinationRequest.java b/java/src/main/java/com/coinbase/cdp/openapi/model/CreateCryptoDepositDestinationRequest.java new file mode 100644 index 000000000..caae3dc5c --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/CreateCryptoDepositDestinationRequest.java @@ -0,0 +1,405 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.CreateDepositDestinationCrypto; +import com.coinbase.cdp.openapi.model.DepositDestinationTarget; +import com.coinbase.cdp.openapi.model.Metadata; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * CreateCryptoDepositDestinationRequest + */ +@JsonPropertyOrder({ + CreateCryptoDepositDestinationRequest.JSON_PROPERTY_ACCOUNT_ID, + CreateCryptoDepositDestinationRequest.JSON_PROPERTY_TYPE, + CreateCryptoDepositDestinationRequest.JSON_PROPERTY_TARGET, + CreateCryptoDepositDestinationRequest.JSON_PROPERTY_METADATA, + CreateCryptoDepositDestinationRequest.JSON_PROPERTY_CRYPTO +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class CreateCryptoDepositDestinationRequest { + public static final String JSON_PROPERTY_ACCOUNT_ID = "accountId"; + @jakarta.annotation.Nonnull + private String accountId; + + /** + * Gets or Sets type + */ + public enum TypeEnum { + CRYPTO(String.valueOf("crypto")); + + private String value; + + TypeEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static TypeEnum fromValue(String value) { + for (TypeEnum b : TypeEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + public static final String JSON_PROPERTY_TYPE = "type"; + @jakarta.annotation.Nonnull + private TypeEnum type; + + public static final String JSON_PROPERTY_TARGET = "target"; + @jakarta.annotation.Nullable + private DepositDestinationTarget target; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private Metadata metadata = new Metadata(); + + public static final String JSON_PROPERTY_CRYPTO = "crypto"; + @jakarta.annotation.Nonnull + private CreateDepositDestinationCrypto crypto; + + public CreateCryptoDepositDestinationRequest() { + } + + public CreateCryptoDepositDestinationRequest accountId(@jakarta.annotation.Nonnull String accountId) { + this.accountId = accountId; + return this; + } + + /** + * The ID of the Account, which is a UUID prefixed by the string `account_`. + * @return accountId + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ACCOUNT_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAccountId() { + return accountId; + } + + + @JsonProperty(JSON_PROPERTY_ACCOUNT_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAccountId(@jakarta.annotation.Nonnull String accountId) { + this.accountId = accountId; + } + + + public CreateCryptoDepositDestinationRequest type(@jakarta.annotation.Nonnull TypeEnum type) { + this.type = type; + return this; + } + + /** + * Get type + * @return type + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_TYPE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public TypeEnum getType() { + return type; + } + + + @JsonProperty(JSON_PROPERTY_TYPE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setType(@jakarta.annotation.Nonnull TypeEnum type) { + this.type = type; + } + + + public CreateCryptoDepositDestinationRequest target(@jakarta.annotation.Nullable DepositDestinationTarget target) { + this.target = target; + return this; + } + + /** + * Get target + * @return target + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_TARGET) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public DepositDestinationTarget getTarget() { + return target; + } + + + @JsonProperty(JSON_PROPERTY_TARGET) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setTarget(@jakarta.annotation.Nullable DepositDestinationTarget target) { + this.target = target; + } + + + public CreateCryptoDepositDestinationRequest metadata(@jakarta.annotation.Nullable Metadata metadata) { + this.metadata = metadata; + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_METADATA) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public Metadata getMetadata() { + return metadata; + } + + + @JsonProperty(JSON_PROPERTY_METADATA) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setMetadata(@jakarta.annotation.Nullable Metadata metadata) { + this.metadata = metadata; + } + + + public CreateCryptoDepositDestinationRequest crypto(@jakarta.annotation.Nonnull CreateDepositDestinationCrypto crypto) { + this.crypto = crypto; + return this; + } + + /** + * Crypto-specific details. Required when `type` is `crypto`. + * @return crypto + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_CRYPTO) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public CreateDepositDestinationCrypto getCrypto() { + return crypto; + } + + + @JsonProperty(JSON_PROPERTY_CRYPTO) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCrypto(@jakarta.annotation.Nonnull CreateDepositDestinationCrypto crypto) { + this.crypto = crypto; + } + + + /** + * Return true if this CreateCryptoDepositDestinationRequest object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + CreateCryptoDepositDestinationRequest createCryptoDepositDestinationRequest = (CreateCryptoDepositDestinationRequest) o; + return Objects.equals(this.accountId, createCryptoDepositDestinationRequest.accountId) && + Objects.equals(this.type, createCryptoDepositDestinationRequest.type) && + Objects.equals(this.target, createCryptoDepositDestinationRequest.target) && + Objects.equals(this.metadata, createCryptoDepositDestinationRequest.metadata) && + Objects.equals(this.crypto, createCryptoDepositDestinationRequest.crypto); + } + + @Override + public int hashCode() { + return Objects.hash(accountId, type, target, metadata, crypto); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CreateCryptoDepositDestinationRequest {\n"); + sb.append(" accountId: ").append(toIndentedString(accountId)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" target: ").append(toIndentedString(target)).append("\n"); + sb.append(" metadata: ").append(toIndentedString(metadata)).append("\n"); + sb.append(" crypto: ").append(toIndentedString(crypto)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `accountId` to the URL query string + if (getAccountId() != null) { + joiner.add(String.format("%saccountId%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAccountId()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `type` to the URL query string + if (getType() != null) { + joiner.add(String.format("%stype%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getType()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `target` to the URL query string + if (getTarget() != null) { + joiner.add(getTarget().toUrlQueryString(prefix + "target" + suffix)); + } + + // add `metadata` to the URL query string + if (getMetadata() != null) { + joiner.add(String.format("%smetadata%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getMetadata()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `crypto` to the URL query string + if (getCrypto() != null) { + joiner.add(getCrypto().toUrlQueryString(prefix + "crypto" + suffix)); + } + + return joiner.toString(); + } + + public static class Builder { + + private CreateCryptoDepositDestinationRequest instance; + + public Builder() { + this(new CreateCryptoDepositDestinationRequest()); + } + + protected Builder(CreateCryptoDepositDestinationRequest instance) { + this.instance = instance; + } + + public CreateCryptoDepositDestinationRequest.Builder accountId(String accountId) { + this.instance.accountId = accountId; + return this; + } + public CreateCryptoDepositDestinationRequest.Builder type(TypeEnum type) { + this.instance.type = type; + return this; + } + public CreateCryptoDepositDestinationRequest.Builder target(DepositDestinationTarget target) { + this.instance.target = target; + return this; + } + public CreateCryptoDepositDestinationRequest.Builder metadata(Metadata metadata) { + this.instance.metadata = metadata; + return this; + } + public CreateCryptoDepositDestinationRequest.Builder crypto(CreateDepositDestinationCrypto crypto) { + this.instance.crypto = crypto; + return this; + } + + + /** + * returns a built CreateCryptoDepositDestinationRequest instance. + * + * The builder is not reusable. + */ + public CreateCryptoDepositDestinationRequest build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static CreateCryptoDepositDestinationRequest.Builder builder() { + return new CreateCryptoDepositDestinationRequest.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public CreateCryptoDepositDestinationRequest.Builder toBuilder() { + return new CreateCryptoDepositDestinationRequest.Builder() + .accountId(getAccountId()) + .type(getType()) + .target(getTarget()) + .metadata(getMetadata()) + .crypto(getCrypto()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/CreateDepositDestinationCrypto.java b/java/src/main/java/com/coinbase/cdp/openapi/model/CreateDepositDestinationCrypto.java new file mode 100644 index 000000000..70e7b736f --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/CreateDepositDestinationCrypto.java @@ -0,0 +1,206 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.Network; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * Crypto-specific details for creating a deposit destination. + */ +@JsonPropertyOrder({ + CreateDepositDestinationCrypto.JSON_PROPERTY_NETWORK +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class CreateDepositDestinationCrypto { + public static final String JSON_PROPERTY_NETWORK = "network"; + @jakarta.annotation.Nonnull + private Network network; + + public CreateDepositDestinationCrypto() { + } + + public CreateDepositDestinationCrypto network(@jakarta.annotation.Nonnull Network network) { + this.network = network; + return this; + } + + /** + * Get network + * @return network + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_NETWORK) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public Network getNetwork() { + return network; + } + + + @JsonProperty(JSON_PROPERTY_NETWORK) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNetwork(@jakarta.annotation.Nonnull Network network) { + this.network = network; + } + + + /** + * Return true if this CreateDepositDestinationCrypto object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + CreateDepositDestinationCrypto createDepositDestinationCrypto = (CreateDepositDestinationCrypto) o; + return Objects.equals(this.network, createDepositDestinationCrypto.network); + } + + @Override + public int hashCode() { + return Objects.hash(network); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CreateDepositDestinationCrypto {\n"); + sb.append(" network: ").append(toIndentedString(network)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `network` to the URL query string + if (getNetwork() != null) { + joiner.add(String.format("%snetwork%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getNetwork()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private CreateDepositDestinationCrypto instance; + + public Builder() { + this(new CreateDepositDestinationCrypto()); + } + + protected Builder(CreateDepositDestinationCrypto instance) { + this.instance = instance; + } + + public CreateDepositDestinationCrypto.Builder network(Network network) { + this.instance.network = network; + return this; + } + + + /** + * returns a built CreateDepositDestinationCrypto instance. + * + * The builder is not reusable. + */ + public CreateDepositDestinationCrypto build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static CreateDepositDestinationCrypto.Builder builder() { + return new CreateDepositDestinationCrypto.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public CreateDepositDestinationCrypto.Builder toBuilder() { + return new CreateDepositDestinationCrypto.Builder() + .network(getNetwork()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/CreateDepositDestinationRequest.java b/java/src/main/java/com/coinbase/cdp/openapi/model/CreateDepositDestinationRequest.java new file mode 100644 index 000000000..147c9666e --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/CreateDepositDestinationRequest.java @@ -0,0 +1,253 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.CreateCryptoDepositDestinationRequest; +import com.coinbase.cdp.openapi.model.CreateDepositDestinationCrypto; +import com.coinbase.cdp.openapi.model.DepositDestinationTarget; +import com.coinbase.cdp.openapi.model.Metadata; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import com.fasterxml.jackson.core.type.TypeReference; + +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import com.coinbase.cdp.openapi.JSON; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +@JsonDeserialize(using = CreateDepositDestinationRequest.CreateDepositDestinationRequestDeserializer.class) +@JsonSerialize(using = CreateDepositDestinationRequest.CreateDepositDestinationRequestSerializer.class) +public class CreateDepositDestinationRequest extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(CreateDepositDestinationRequest.class.getName()); + + public static class CreateDepositDestinationRequestSerializer extends StdSerializer { + public CreateDepositDestinationRequestSerializer(Class t) { + super(t); + } + + public CreateDepositDestinationRequestSerializer() { + this(null); + } + + @Override + public void serialize(CreateDepositDestinationRequest value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { + jgen.writeObject(value.getActualInstance()); + } + } + + public static class CreateDepositDestinationRequestDeserializer extends StdDeserializer { + public CreateDepositDestinationRequestDeserializer() { + this(CreateDepositDestinationRequest.class); + } + + public CreateDepositDestinationRequestDeserializer(Class vc) { + super(vc); + } + + @Override + public CreateDepositDestinationRequest deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { + JsonNode tree = jp.readValueAsTree(); + Object deserialized = null; + boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS); + int match = 0; + JsonToken token = tree.traverse(jp.getCodec()).nextToken(); + // deserialize CreateCryptoDepositDestinationRequest + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if (CreateCryptoDepositDestinationRequest.class.equals(Integer.class) || CreateCryptoDepositDestinationRequest.class.equals(Long.class) || CreateCryptoDepositDestinationRequest.class.equals(Float.class) || CreateCryptoDepositDestinationRequest.class.equals(Double.class) || CreateCryptoDepositDestinationRequest.class.equals(Boolean.class) || CreateCryptoDepositDestinationRequest.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= ((CreateCryptoDepositDestinationRequest.class.equals(Integer.class) || CreateCryptoDepositDestinationRequest.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= ((CreateCryptoDepositDestinationRequest.class.equals(Float.class) || CreateCryptoDepositDestinationRequest.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= (CreateCryptoDepositDestinationRequest.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= (CreateCryptoDepositDestinationRequest.class.equals(String.class) && token == JsonToken.VALUE_STRING); + } + } + if (attemptParsing) { + deserialized = tree.traverse(jp.getCodec()).readValueAs(CreateCryptoDepositDestinationRequest.class); + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema 'CreateCryptoDepositDestinationRequest'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'CreateCryptoDepositDestinationRequest'", e); + } + + if (match == 1) { + CreateDepositDestinationRequest ret = new CreateDepositDestinationRequest(); + ret.setActualInstance(deserialized); + return ret; + } + throw new IOException(String.format("Failed deserialization for CreateDepositDestinationRequest: %d classes match result, expected 1", match)); + } + + /** + * Handle deserialization of the 'null' value. + */ + @Override + public CreateDepositDestinationRequest getNullValue(DeserializationContext ctxt) throws JsonMappingException { + throw new JsonMappingException(ctxt.getParser(), "CreateDepositDestinationRequest cannot be null"); + } + } + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public CreateDepositDestinationRequest() { + super("oneOf", Boolean.FALSE); + } + + public CreateDepositDestinationRequest(CreateCryptoDepositDestinationRequest o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("CreateCryptoDepositDestinationRequest", CreateCryptoDepositDestinationRequest.class); + JSON.registerDescendants(CreateDepositDestinationRequest.class, Collections.unmodifiableMap(schemas)); + // Initialize and register the discriminator mappings. + Map> mappings = new HashMap>(); + mappings.put("crypto", CreateCryptoDepositDestinationRequest.class); + mappings.put("CreateCryptoDepositDestinationRequest", CreateCryptoDepositDestinationRequest.class); + mappings.put("CreateDepositDestinationRequest", CreateDepositDestinationRequest.class); + JSON.registerDiscriminator(CreateDepositDestinationRequest.class, "type", mappings); + } + + @Override + public Map> getSchemas() { + return CreateDepositDestinationRequest.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * CreateCryptoDepositDestinationRequest + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(CreateCryptoDepositDestinationRequest.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be CreateCryptoDepositDestinationRequest"); + } + + /** + * Get the actual instance, which can be the following: + * CreateCryptoDepositDestinationRequest + * + * @return The actual instance (CreateCryptoDepositDestinationRequest) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `CreateCryptoDepositDestinationRequest`. If the actual instance is not `CreateCryptoDepositDestinationRequest`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `CreateCryptoDepositDestinationRequest` + * @throws ClassCastException if the instance is not `CreateCryptoDepositDestinationRequest` + */ + public CreateCryptoDepositDestinationRequest getCreateCryptoDepositDestinationRequest() throws ClassCastException { + return (CreateCryptoDepositDestinationRequest)super.getActualInstance(); + } + + + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + if (getActualInstance() instanceof CreateCryptoDepositDestinationRequest) { + if (getActualInstance() != null) { + joiner.add(((CreateCryptoDepositDestinationRequest)getActualInstance()).toUrlQueryString(prefix + "one_of_0" + suffix)); + } + return joiner.toString(); + } + return null; + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/CreateDepositDestinationRequestBase.java b/java/src/main/java/com/coinbase/cdp/openapi/model/CreateDepositDestinationRequestBase.java new file mode 100644 index 000000000..2ff4c6b36 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/CreateDepositDestinationRequestBase.java @@ -0,0 +1,330 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.DepositDestinationTarget; +import com.coinbase.cdp.openapi.model.Metadata; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * Common fields for creating a deposit destination. + */ +@JsonPropertyOrder({ + CreateDepositDestinationRequestBase.JSON_PROPERTY_ACCOUNT_ID, + CreateDepositDestinationRequestBase.JSON_PROPERTY_TYPE, + CreateDepositDestinationRequestBase.JSON_PROPERTY_TARGET, + CreateDepositDestinationRequestBase.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class CreateDepositDestinationRequestBase { + public static final String JSON_PROPERTY_ACCOUNT_ID = "accountId"; + @jakarta.annotation.Nonnull + private String accountId; + + public static final String JSON_PROPERTY_TYPE = "type"; + @jakarta.annotation.Nonnull + private String type; + + public static final String JSON_PROPERTY_TARGET = "target"; + @jakarta.annotation.Nullable + private DepositDestinationTarget target; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private Metadata metadata = new Metadata(); + + public CreateDepositDestinationRequestBase() { + } + + public CreateDepositDestinationRequestBase accountId(@jakarta.annotation.Nonnull String accountId) { + this.accountId = accountId; + return this; + } + + /** + * The ID of the Account, which is a UUID prefixed by the string `account_`. + * @return accountId + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ACCOUNT_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAccountId() { + return accountId; + } + + + @JsonProperty(JSON_PROPERTY_ACCOUNT_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAccountId(@jakarta.annotation.Nonnull String accountId) { + this.accountId = accountId; + } + + + public CreateDepositDestinationRequestBase type(@jakarta.annotation.Nonnull String type) { + this.type = type; + return this; + } + + /** + * The type of deposit destination. + * @return type + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_TYPE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getType() { + return type; + } + + + @JsonProperty(JSON_PROPERTY_TYPE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setType(@jakarta.annotation.Nonnull String type) { + this.type = type; + } + + + public CreateDepositDestinationRequestBase target(@jakarta.annotation.Nullable DepositDestinationTarget target) { + this.target = target; + return this; + } + + /** + * Get target + * @return target + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_TARGET) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public DepositDestinationTarget getTarget() { + return target; + } + + + @JsonProperty(JSON_PROPERTY_TARGET) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setTarget(@jakarta.annotation.Nullable DepositDestinationTarget target) { + this.target = target; + } + + + public CreateDepositDestinationRequestBase metadata(@jakarta.annotation.Nullable Metadata metadata) { + this.metadata = metadata; + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_METADATA) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public Metadata getMetadata() { + return metadata; + } + + + @JsonProperty(JSON_PROPERTY_METADATA) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setMetadata(@jakarta.annotation.Nullable Metadata metadata) { + this.metadata = metadata; + } + + + /** + * Return true if this CreateDepositDestinationRequestBase object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + CreateDepositDestinationRequestBase createDepositDestinationRequestBase = (CreateDepositDestinationRequestBase) o; + return Objects.equals(this.accountId, createDepositDestinationRequestBase.accountId) && + Objects.equals(this.type, createDepositDestinationRequestBase.type) && + Objects.equals(this.target, createDepositDestinationRequestBase.target) && + Objects.equals(this.metadata, createDepositDestinationRequestBase.metadata); + } + + @Override + public int hashCode() { + return Objects.hash(accountId, type, target, metadata); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CreateDepositDestinationRequestBase {\n"); + sb.append(" accountId: ").append(toIndentedString(accountId)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" target: ").append(toIndentedString(target)).append("\n"); + sb.append(" metadata: ").append(toIndentedString(metadata)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `accountId` to the URL query string + if (getAccountId() != null) { + joiner.add(String.format("%saccountId%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAccountId()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `type` to the URL query string + if (getType() != null) { + joiner.add(String.format("%stype%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getType()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `target` to the URL query string + if (getTarget() != null) { + joiner.add(getTarget().toUrlQueryString(prefix + "target" + suffix)); + } + + // add `metadata` to the URL query string + if (getMetadata() != null) { + joiner.add(String.format("%smetadata%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getMetadata()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private CreateDepositDestinationRequestBase instance; + + public Builder() { + this(new CreateDepositDestinationRequestBase()); + } + + protected Builder(CreateDepositDestinationRequestBase instance) { + this.instance = instance; + } + + public CreateDepositDestinationRequestBase.Builder accountId(String accountId) { + this.instance.accountId = accountId; + return this; + } + public CreateDepositDestinationRequestBase.Builder type(String type) { + this.instance.type = type; + return this; + } + public CreateDepositDestinationRequestBase.Builder target(DepositDestinationTarget target) { + this.instance.target = target; + return this; + } + public CreateDepositDestinationRequestBase.Builder metadata(Metadata metadata) { + this.instance.metadata = metadata; + return this; + } + + + /** + * returns a built CreateDepositDestinationRequestBase instance. + * + * The builder is not reusable. + */ + public CreateDepositDestinationRequestBase build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static CreateDepositDestinationRequestBase.Builder builder() { + return new CreateDepositDestinationRequestBase.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public CreateDepositDestinationRequestBase.Builder toBuilder() { + return new CreateDepositDestinationRequestBase.Builder() + .accountId(getAccountId()) + .type(getType()) + .target(getTarget()) + .metadata(getMetadata()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/CreateEvmEip7702Delegation201Response.java b/java/src/main/java/com/coinbase/cdp/openapi/model/CreateEvmEip7702Delegation201Response.java new file mode 100644 index 000000000..964342cd8 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/CreateEvmEip7702Delegation201Response.java @@ -0,0 +1,206 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import java.util.UUID; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * CreateEvmEip7702Delegation201Response + */ +@JsonPropertyOrder({ + CreateEvmEip7702Delegation201Response.JSON_PROPERTY_DELEGATION_OPERATION_ID +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class CreateEvmEip7702Delegation201Response { + public static final String JSON_PROPERTY_DELEGATION_OPERATION_ID = "delegationOperationId"; + @jakarta.annotation.Nonnull + private UUID delegationOperationId; + + public CreateEvmEip7702Delegation201Response() { + } + + public CreateEvmEip7702Delegation201Response delegationOperationId(@jakarta.annotation.Nonnull UUID delegationOperationId) { + this.delegationOperationId = delegationOperationId; + return this; + } + + /** + * The unique identifier for the delegation operation. Use this to poll the operation status. + * @return delegationOperationId + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_DELEGATION_OPERATION_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public UUID getDelegationOperationId() { + return delegationOperationId; + } + + + @JsonProperty(JSON_PROPERTY_DELEGATION_OPERATION_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDelegationOperationId(@jakarta.annotation.Nonnull UUID delegationOperationId) { + this.delegationOperationId = delegationOperationId; + } + + + /** + * Return true if this createEvmEip7702Delegation_201_response object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + CreateEvmEip7702Delegation201Response createEvmEip7702Delegation201Response = (CreateEvmEip7702Delegation201Response) o; + return Objects.equals(this.delegationOperationId, createEvmEip7702Delegation201Response.delegationOperationId); + } + + @Override + public int hashCode() { + return Objects.hash(delegationOperationId); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CreateEvmEip7702Delegation201Response {\n"); + sb.append(" delegationOperationId: ").append(toIndentedString(delegationOperationId)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `delegationOperationId` to the URL query string + if (getDelegationOperationId() != null) { + joiner.add(String.format("%sdelegationOperationId%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getDelegationOperationId()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private CreateEvmEip7702Delegation201Response instance; + + public Builder() { + this(new CreateEvmEip7702Delegation201Response()); + } + + protected Builder(CreateEvmEip7702Delegation201Response instance) { + this.instance = instance; + } + + public CreateEvmEip7702Delegation201Response.Builder delegationOperationId(UUID delegationOperationId) { + this.instance.delegationOperationId = delegationOperationId; + return this; + } + + + /** + * returns a built CreateEvmEip7702Delegation201Response instance. + * + * The builder is not reusable. + */ + public CreateEvmEip7702Delegation201Response build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static CreateEvmEip7702Delegation201Response.Builder builder() { + return new CreateEvmEip7702Delegation201Response.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public CreateEvmEip7702Delegation201Response.Builder toBuilder() { + return new CreateEvmEip7702Delegation201Response.Builder() + .delegationOperationId(getDelegationOperationId()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/CreateTransferSource.java b/java/src/main/java/com/coinbase/cdp/openapi/model/CreateTransferSource.java new file mode 100644 index 000000000..d6c8778b7 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/CreateTransferSource.java @@ -0,0 +1,296 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.PaymentMethod; +import com.coinbase.cdp.openapi.model.TransfersAccount; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import com.fasterxml.jackson.core.type.TypeReference; + +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import com.coinbase.cdp.openapi.JSON; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +@JsonDeserialize(using = CreateTransferSource.CreateTransferSourceDeserializer.class) +@JsonSerialize(using = CreateTransferSource.CreateTransferSourceSerializer.class) +public class CreateTransferSource extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(CreateTransferSource.class.getName()); + + public static class CreateTransferSourceSerializer extends StdSerializer { + public CreateTransferSourceSerializer(Class t) { + super(t); + } + + public CreateTransferSourceSerializer() { + this(null); + } + + @Override + public void serialize(CreateTransferSource value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { + jgen.writeObject(value.getActualInstance()); + } + } + + public static class CreateTransferSourceDeserializer extends StdDeserializer { + public CreateTransferSourceDeserializer() { + this(CreateTransferSource.class); + } + + public CreateTransferSourceDeserializer(Class vc) { + super(vc); + } + + @Override + public CreateTransferSource deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { + JsonNode tree = jp.readValueAsTree(); + Object deserialized = null; + boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS); + int match = 0; + JsonToken token = tree.traverse(jp.getCodec()).nextToken(); + // deserialize PaymentMethod + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if (PaymentMethod.class.equals(Integer.class) || PaymentMethod.class.equals(Long.class) || PaymentMethod.class.equals(Float.class) || PaymentMethod.class.equals(Double.class) || PaymentMethod.class.equals(Boolean.class) || PaymentMethod.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= ((PaymentMethod.class.equals(Integer.class) || PaymentMethod.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= ((PaymentMethod.class.equals(Float.class) || PaymentMethod.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= (PaymentMethod.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= (PaymentMethod.class.equals(String.class) && token == JsonToken.VALUE_STRING); + } + } + if (attemptParsing) { + deserialized = tree.traverse(jp.getCodec()).readValueAs(PaymentMethod.class); + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema 'PaymentMethod'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'PaymentMethod'", e); + } + + // deserialize TransfersAccount + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if (TransfersAccount.class.equals(Integer.class) || TransfersAccount.class.equals(Long.class) || TransfersAccount.class.equals(Float.class) || TransfersAccount.class.equals(Double.class) || TransfersAccount.class.equals(Boolean.class) || TransfersAccount.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= ((TransfersAccount.class.equals(Integer.class) || TransfersAccount.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= ((TransfersAccount.class.equals(Float.class) || TransfersAccount.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= (TransfersAccount.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= (TransfersAccount.class.equals(String.class) && token == JsonToken.VALUE_STRING); + } + } + if (attemptParsing) { + deserialized = tree.traverse(jp.getCodec()).readValueAs(TransfersAccount.class); + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema 'TransfersAccount'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'TransfersAccount'", e); + } + + if (match == 1) { + CreateTransferSource ret = new CreateTransferSource(); + ret.setActualInstance(deserialized); + return ret; + } + throw new IOException(String.format("Failed deserialization for CreateTransferSource: %d classes match result, expected 1", match)); + } + + /** + * Handle deserialization of the 'null' value. + */ + @Override + public CreateTransferSource getNullValue(DeserializationContext ctxt) throws JsonMappingException { + throw new JsonMappingException(ctxt.getParser(), "CreateTransferSource cannot be null"); + } + } + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public CreateTransferSource() { + super("oneOf", Boolean.FALSE); + } + + public CreateTransferSource(PaymentMethod o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public CreateTransferSource(TransfersAccount o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("PaymentMethod", PaymentMethod.class); + schemas.put("TransfersAccount", TransfersAccount.class); + JSON.registerDescendants(CreateTransferSource.class, Collections.unmodifiableMap(schemas)); + } + + @Override + public Map> getSchemas() { + return CreateTransferSource.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * PaymentMethod, TransfersAccount + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(PaymentMethod.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(TransfersAccount.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be PaymentMethod, TransfersAccount"); + } + + /** + * Get the actual instance, which can be the following: + * PaymentMethod, TransfersAccount + * + * @return The actual instance (PaymentMethod, TransfersAccount) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `PaymentMethod`. If the actual instance is not `PaymentMethod`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `PaymentMethod` + * @throws ClassCastException if the instance is not `PaymentMethod` + */ + public PaymentMethod getPaymentMethod() throws ClassCastException { + return (PaymentMethod)super.getActualInstance(); + } + + /** + * Get the actual instance of `TransfersAccount`. If the actual instance is not `TransfersAccount`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `TransfersAccount` + * @throws ClassCastException if the instance is not `TransfersAccount` + */ + public TransfersAccount getTransfersAccount() throws ClassCastException { + return (TransfersAccount)super.getActualInstance(); + } + + + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + if (getActualInstance() instanceof TransfersAccount) { + if (getActualInstance() != null) { + joiner.add(((TransfersAccount)getActualInstance()).toUrlQueryString(prefix + "one_of_0" + suffix)); + } + return joiner.toString(); + } + if (getActualInstance() instanceof PaymentMethod) { + if (getActualInstance() != null) { + joiner.add(((PaymentMethod)getActualInstance()).toUrlQueryString(prefix + "one_of_1" + suffix)); + } + return joiner.toString(); + } + return null; + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/CryptoDepositDestination.java b/java/src/main/java/com/coinbase/cdp/openapi/model/CryptoDepositDestination.java new file mode 100644 index 000000000..80cc23898 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/CryptoDepositDestination.java @@ -0,0 +1,571 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.DepositDestinationCrypto; +import com.coinbase.cdp.openapi.model.DepositDestinationStatus; +import com.coinbase.cdp.openapi.model.DepositDestinationTarget; +import com.coinbase.cdp.openapi.model.Metadata; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * A cryptocurrency deposit destination. + */ +@JsonPropertyOrder({ + CryptoDepositDestination.JSON_PROPERTY_DEPOSIT_DESTINATION_ID, + CryptoDepositDestination.JSON_PROPERTY_ACCOUNT_ID, + CryptoDepositDestination.JSON_PROPERTY_TYPE, + CryptoDepositDestination.JSON_PROPERTY_CRYPTO, + CryptoDepositDestination.JSON_PROPERTY_TARGET, + CryptoDepositDestination.JSON_PROPERTY_STATUS, + CryptoDepositDestination.JSON_PROPERTY_METADATA, + CryptoDepositDestination.JSON_PROPERTY_CREATED_AT, + CryptoDepositDestination.JSON_PROPERTY_UPDATED_AT +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class CryptoDepositDestination { + public static final String JSON_PROPERTY_DEPOSIT_DESTINATION_ID = "depositDestinationId"; + @jakarta.annotation.Nonnull + private String depositDestinationId; + + public static final String JSON_PROPERTY_ACCOUNT_ID = "accountId"; + @jakarta.annotation.Nonnull + private String accountId; + + /** + * The type of deposit destination. + */ + public enum TypeEnum { + CRYPTO(String.valueOf("crypto")); + + private String value; + + TypeEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static TypeEnum fromValue(String value) { + for (TypeEnum b : TypeEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + public static final String JSON_PROPERTY_TYPE = "type"; + @jakarta.annotation.Nonnull + private TypeEnum type; + + public static final String JSON_PROPERTY_CRYPTO = "crypto"; + @jakarta.annotation.Nonnull + private DepositDestinationCrypto crypto; + + public static final String JSON_PROPERTY_TARGET = "target"; + @jakarta.annotation.Nullable + private DepositDestinationTarget target; + + public static final String JSON_PROPERTY_STATUS = "status"; + @jakarta.annotation.Nonnull + private DepositDestinationStatus status; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private Metadata metadata = new Metadata(); + + public static final String JSON_PROPERTY_CREATED_AT = "createdAt"; + @jakarta.annotation.Nonnull + private OffsetDateTime createdAt; + + public static final String JSON_PROPERTY_UPDATED_AT = "updatedAt"; + @jakarta.annotation.Nonnull + private OffsetDateTime updatedAt; + + public CryptoDepositDestination() { + } + + public CryptoDepositDestination depositDestinationId(@jakarta.annotation.Nonnull String depositDestinationId) { + this.depositDestinationId = depositDestinationId; + return this; + } + + /** + * The ID of the Deposit Destination, which is a UUID prefixed by the string `depositDestination_`. + * @return depositDestinationId + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_DEPOSIT_DESTINATION_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getDepositDestinationId() { + return depositDestinationId; + } + + + @JsonProperty(JSON_PROPERTY_DEPOSIT_DESTINATION_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDepositDestinationId(@jakarta.annotation.Nonnull String depositDestinationId) { + this.depositDestinationId = depositDestinationId; + } + + + public CryptoDepositDestination accountId(@jakarta.annotation.Nonnull String accountId) { + this.accountId = accountId; + return this; + } + + /** + * The ID of the Account, which is a UUID prefixed by the string `account_`. + * @return accountId + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ACCOUNT_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAccountId() { + return accountId; + } + + + @JsonProperty(JSON_PROPERTY_ACCOUNT_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAccountId(@jakarta.annotation.Nonnull String accountId) { + this.accountId = accountId; + } + + + public CryptoDepositDestination type(@jakarta.annotation.Nonnull TypeEnum type) { + this.type = type; + return this; + } + + /** + * The type of deposit destination. + * @return type + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_TYPE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public TypeEnum getType() { + return type; + } + + + @JsonProperty(JSON_PROPERTY_TYPE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setType(@jakarta.annotation.Nonnull TypeEnum type) { + this.type = type; + } + + + public CryptoDepositDestination crypto(@jakarta.annotation.Nonnull DepositDestinationCrypto crypto) { + this.crypto = crypto; + return this; + } + + /** + * Crypto-specific details for this deposit destination. Always populated in responses. Contains the network and address. + * @return crypto + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_CRYPTO) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public DepositDestinationCrypto getCrypto() { + return crypto; + } + + + @JsonProperty(JSON_PROPERTY_CRYPTO) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCrypto(@jakarta.annotation.Nonnull DepositDestinationCrypto crypto) { + this.crypto = crypto; + } + + + public CryptoDepositDestination target(@jakarta.annotation.Nullable DepositDestinationTarget target) { + this.target = target; + return this; + } + + /** + * Get target + * @return target + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_TARGET) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public DepositDestinationTarget getTarget() { + return target; + } + + + @JsonProperty(JSON_PROPERTY_TARGET) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setTarget(@jakarta.annotation.Nullable DepositDestinationTarget target) { + this.target = target; + } + + + public CryptoDepositDestination status(@jakarta.annotation.Nonnull DepositDestinationStatus status) { + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_STATUS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public DepositDestinationStatus getStatus() { + return status; + } + + + @JsonProperty(JSON_PROPERTY_STATUS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStatus(@jakarta.annotation.Nonnull DepositDestinationStatus status) { + this.status = status; + } + + + public CryptoDepositDestination metadata(@jakarta.annotation.Nullable Metadata metadata) { + this.metadata = metadata; + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_METADATA) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public Metadata getMetadata() { + return metadata; + } + + + @JsonProperty(JSON_PROPERTY_METADATA) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setMetadata(@jakarta.annotation.Nullable Metadata metadata) { + this.metadata = metadata; + } + + + public CryptoDepositDestination createdAt(@jakarta.annotation.Nonnull OffsetDateTime createdAt) { + this.createdAt = createdAt; + return this; + } + + /** + * The timestamp when the deposit destination was created. + * @return createdAt + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_CREATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public OffsetDateTime getCreatedAt() { + return createdAt; + } + + + @JsonProperty(JSON_PROPERTY_CREATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCreatedAt(@jakarta.annotation.Nonnull OffsetDateTime createdAt) { + this.createdAt = createdAt; + } + + + public CryptoDepositDestination updatedAt(@jakarta.annotation.Nonnull OffsetDateTime updatedAt) { + this.updatedAt = updatedAt; + return this; + } + + /** + * The timestamp when the deposit destination was last updated. + * @return updatedAt + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_UPDATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public OffsetDateTime getUpdatedAt() { + return updatedAt; + } + + + @JsonProperty(JSON_PROPERTY_UPDATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUpdatedAt(@jakarta.annotation.Nonnull OffsetDateTime updatedAt) { + this.updatedAt = updatedAt; + } + + + /** + * Return true if this CryptoDepositDestination object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + CryptoDepositDestination cryptoDepositDestination = (CryptoDepositDestination) o; + return Objects.equals(this.depositDestinationId, cryptoDepositDestination.depositDestinationId) && + Objects.equals(this.accountId, cryptoDepositDestination.accountId) && + Objects.equals(this.type, cryptoDepositDestination.type) && + Objects.equals(this.crypto, cryptoDepositDestination.crypto) && + Objects.equals(this.target, cryptoDepositDestination.target) && + Objects.equals(this.status, cryptoDepositDestination.status) && + Objects.equals(this.metadata, cryptoDepositDestination.metadata) && + Objects.equals(this.createdAt, cryptoDepositDestination.createdAt) && + Objects.equals(this.updatedAt, cryptoDepositDestination.updatedAt); + } + + @Override + public int hashCode() { + return Objects.hash(depositDestinationId, accountId, type, crypto, target, status, metadata, createdAt, updatedAt); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CryptoDepositDestination {\n"); + sb.append(" depositDestinationId: ").append(toIndentedString(depositDestinationId)).append("\n"); + sb.append(" accountId: ").append(toIndentedString(accountId)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" crypto: ").append(toIndentedString(crypto)).append("\n"); + sb.append(" target: ").append(toIndentedString(target)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" metadata: ").append(toIndentedString(metadata)).append("\n"); + sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); + sb.append(" updatedAt: ").append(toIndentedString(updatedAt)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `depositDestinationId` to the URL query string + if (getDepositDestinationId() != null) { + joiner.add(String.format("%sdepositDestinationId%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getDepositDestinationId()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `accountId` to the URL query string + if (getAccountId() != null) { + joiner.add(String.format("%saccountId%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAccountId()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `type` to the URL query string + if (getType() != null) { + joiner.add(String.format("%stype%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getType()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `crypto` to the URL query string + if (getCrypto() != null) { + joiner.add(getCrypto().toUrlQueryString(prefix + "crypto" + suffix)); + } + + // add `target` to the URL query string + if (getTarget() != null) { + joiner.add(getTarget().toUrlQueryString(prefix + "target" + suffix)); + } + + // add `status` to the URL query string + if (getStatus() != null) { + joiner.add(String.format("%sstatus%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getStatus()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `metadata` to the URL query string + if (getMetadata() != null) { + joiner.add(String.format("%smetadata%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getMetadata()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `createdAt` to the URL query string + if (getCreatedAt() != null) { + joiner.add(String.format("%screatedAt%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getCreatedAt()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `updatedAt` to the URL query string + if (getUpdatedAt() != null) { + joiner.add(String.format("%supdatedAt%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getUpdatedAt()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private CryptoDepositDestination instance; + + public Builder() { + this(new CryptoDepositDestination()); + } + + protected Builder(CryptoDepositDestination instance) { + this.instance = instance; + } + + public CryptoDepositDestination.Builder depositDestinationId(String depositDestinationId) { + this.instance.depositDestinationId = depositDestinationId; + return this; + } + public CryptoDepositDestination.Builder accountId(String accountId) { + this.instance.accountId = accountId; + return this; + } + public CryptoDepositDestination.Builder type(TypeEnum type) { + this.instance.type = type; + return this; + } + public CryptoDepositDestination.Builder crypto(DepositDestinationCrypto crypto) { + this.instance.crypto = crypto; + return this; + } + public CryptoDepositDestination.Builder target(DepositDestinationTarget target) { + this.instance.target = target; + return this; + } + public CryptoDepositDestination.Builder status(DepositDestinationStatus status) { + this.instance.status = status; + return this; + } + public CryptoDepositDestination.Builder metadata(Metadata metadata) { + this.instance.metadata = metadata; + return this; + } + public CryptoDepositDestination.Builder createdAt(OffsetDateTime createdAt) { + this.instance.createdAt = createdAt; + return this; + } + public CryptoDepositDestination.Builder updatedAt(OffsetDateTime updatedAt) { + this.instance.updatedAt = updatedAt; + return this; + } + + + /** + * returns a built CryptoDepositDestination instance. + * + * The builder is not reusable. + */ + public CryptoDepositDestination build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static CryptoDepositDestination.Builder builder() { + return new CryptoDepositDestination.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public CryptoDepositDestination.Builder toBuilder() { + return new CryptoDepositDestination.Builder() + .depositDestinationId(getDepositDestinationId()) + .accountId(getAccountId()) + .type(getType()) + .crypto(getCrypto()) + .target(getTarget()) + .status(getStatus()) + .metadata(getMetadata()) + .createdAt(getCreatedAt()) + .updatedAt(getUpdatedAt()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/DepositDestination.java b/java/src/main/java/com/coinbase/cdp/openapi/model/DepositDestination.java new file mode 100644 index 000000000..d8da02269 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/DepositDestination.java @@ -0,0 +1,255 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.CryptoDepositDestination; +import com.coinbase.cdp.openapi.model.DepositDestinationCrypto; +import com.coinbase.cdp.openapi.model.DepositDestinationStatus; +import com.coinbase.cdp.openapi.model.DepositDestinationTarget; +import com.coinbase.cdp.openapi.model.Metadata; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import com.fasterxml.jackson.core.type.TypeReference; + +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import com.coinbase.cdp.openapi.JSON; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +@JsonDeserialize(using = DepositDestination.DepositDestinationDeserializer.class) +@JsonSerialize(using = DepositDestination.DepositDestinationSerializer.class) +public class DepositDestination extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(DepositDestination.class.getName()); + + public static class DepositDestinationSerializer extends StdSerializer { + public DepositDestinationSerializer(Class t) { + super(t); + } + + public DepositDestinationSerializer() { + this(null); + } + + @Override + public void serialize(DepositDestination value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { + jgen.writeObject(value.getActualInstance()); + } + } + + public static class DepositDestinationDeserializer extends StdDeserializer { + public DepositDestinationDeserializer() { + this(DepositDestination.class); + } + + public DepositDestinationDeserializer(Class vc) { + super(vc); + } + + @Override + public DepositDestination deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { + JsonNode tree = jp.readValueAsTree(); + Object deserialized = null; + boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS); + int match = 0; + JsonToken token = tree.traverse(jp.getCodec()).nextToken(); + // deserialize CryptoDepositDestination + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if (CryptoDepositDestination.class.equals(Integer.class) || CryptoDepositDestination.class.equals(Long.class) || CryptoDepositDestination.class.equals(Float.class) || CryptoDepositDestination.class.equals(Double.class) || CryptoDepositDestination.class.equals(Boolean.class) || CryptoDepositDestination.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= ((CryptoDepositDestination.class.equals(Integer.class) || CryptoDepositDestination.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= ((CryptoDepositDestination.class.equals(Float.class) || CryptoDepositDestination.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= (CryptoDepositDestination.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= (CryptoDepositDestination.class.equals(String.class) && token == JsonToken.VALUE_STRING); + } + } + if (attemptParsing) { + deserialized = tree.traverse(jp.getCodec()).readValueAs(CryptoDepositDestination.class); + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema 'CryptoDepositDestination'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'CryptoDepositDestination'", e); + } + + if (match == 1) { + DepositDestination ret = new DepositDestination(); + ret.setActualInstance(deserialized); + return ret; + } + throw new IOException(String.format("Failed deserialization for DepositDestination: %d classes match result, expected 1", match)); + } + + /** + * Handle deserialization of the 'null' value. + */ + @Override + public DepositDestination getNullValue(DeserializationContext ctxt) throws JsonMappingException { + throw new JsonMappingException(ctxt.getParser(), "DepositDestination cannot be null"); + } + } + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public DepositDestination() { + super("oneOf", Boolean.FALSE); + } + + public DepositDestination(CryptoDepositDestination o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("CryptoDepositDestination", CryptoDepositDestination.class); + JSON.registerDescendants(DepositDestination.class, Collections.unmodifiableMap(schemas)); + // Initialize and register the discriminator mappings. + Map> mappings = new HashMap>(); + mappings.put("crypto", CryptoDepositDestination.class); + mappings.put("CryptoDepositDestination", CryptoDepositDestination.class); + mappings.put("DepositDestination", DepositDestination.class); + JSON.registerDiscriminator(DepositDestination.class, "type", mappings); + } + + @Override + public Map> getSchemas() { + return DepositDestination.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * CryptoDepositDestination + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(CryptoDepositDestination.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be CryptoDepositDestination"); + } + + /** + * Get the actual instance, which can be the following: + * CryptoDepositDestination + * + * @return The actual instance (CryptoDepositDestination) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `CryptoDepositDestination`. If the actual instance is not `CryptoDepositDestination`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `CryptoDepositDestination` + * @throws ClassCastException if the instance is not `CryptoDepositDestination` + */ + public CryptoDepositDestination getCryptoDepositDestination() throws ClassCastException { + return (CryptoDepositDestination)super.getActualInstance(); + } + + + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + if (getActualInstance() instanceof CryptoDepositDestination) { + if (getActualInstance() != null) { + joiner.add(((CryptoDepositDestination)getActualInstance()).toUrlQueryString(prefix + "one_of_0" + suffix)); + } + return joiner.toString(); + } + return null; + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/DepositDestinationCrypto.java b/java/src/main/java/com/coinbase/cdp/openapi/model/DepositDestinationCrypto.java new file mode 100644 index 000000000..8827c5d7a --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/DepositDestinationCrypto.java @@ -0,0 +1,247 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.Network; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * Crypto-specific deposit destination details. In responses, this object is always present. Contains the network and address for the deposit destination. + */ +@JsonPropertyOrder({ + DepositDestinationCrypto.JSON_PROPERTY_NETWORK, + DepositDestinationCrypto.JSON_PROPERTY_ADDRESS +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class DepositDestinationCrypto { + public static final String JSON_PROPERTY_NETWORK = "network"; + @jakarta.annotation.Nonnull + private Network network; + + public static final String JSON_PROPERTY_ADDRESS = "address"; + @jakarta.annotation.Nonnull + private String address; + + public DepositDestinationCrypto() { + } + + public DepositDestinationCrypto network(@jakarta.annotation.Nonnull Network network) { + this.network = network; + return this; + } + + /** + * Get network + * @return network + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_NETWORK) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public Network getNetwork() { + return network; + } + + + @JsonProperty(JSON_PROPERTY_NETWORK) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNetwork(@jakarta.annotation.Nonnull Network network) { + this.network = network; + } + + + public DepositDestinationCrypto address(@jakarta.annotation.Nonnull String address) { + this.address = address; + return this; + } + + /** + * A blockchain address. Format varies by network (e.g., 0x-prefixed for EVM, base58 for Solana). + * @return address + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ADDRESS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAddress() { + return address; + } + + + @JsonProperty(JSON_PROPERTY_ADDRESS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAddress(@jakarta.annotation.Nonnull String address) { + this.address = address; + } + + + /** + * Return true if this DepositDestinationCrypto object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DepositDestinationCrypto depositDestinationCrypto = (DepositDestinationCrypto) o; + return Objects.equals(this.network, depositDestinationCrypto.network) && + Objects.equals(this.address, depositDestinationCrypto.address); + } + + @Override + public int hashCode() { + return Objects.hash(network, address); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DepositDestinationCrypto {\n"); + sb.append(" network: ").append(toIndentedString(network)).append("\n"); + sb.append(" address: ").append(toIndentedString(address)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `network` to the URL query string + if (getNetwork() != null) { + joiner.add(String.format("%snetwork%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getNetwork()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `address` to the URL query string + if (getAddress() != null) { + joiner.add(String.format("%saddress%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAddress()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private DepositDestinationCrypto instance; + + public Builder() { + this(new DepositDestinationCrypto()); + } + + protected Builder(DepositDestinationCrypto instance) { + this.instance = instance; + } + + public DepositDestinationCrypto.Builder network(Network network) { + this.instance.network = network; + return this; + } + public DepositDestinationCrypto.Builder address(String address) { + this.instance.address = address; + return this; + } + + + /** + * returns a built DepositDestinationCrypto instance. + * + * The builder is not reusable. + */ + public DepositDestinationCrypto build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static DepositDestinationCrypto.Builder builder() { + return new DepositDestinationCrypto.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public DepositDestinationCrypto.Builder toBuilder() { + return new DepositDestinationCrypto.Builder() + .network(getNetwork()) + .address(getAddress()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/DepositDestinationReference.java b/java/src/main/java/com/coinbase/cdp/openapi/model/DepositDestinationReference.java new file mode 100644 index 000000000..a8a52529e --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/DepositDestinationReference.java @@ -0,0 +1,205 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * A reference to the deposit destination associated with the transfer. + */ +@JsonPropertyOrder({ + DepositDestinationReference.JSON_PROPERTY_ID +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class DepositDestinationReference { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public DepositDestinationReference() { + } + + public DepositDestinationReference id(@jakarta.annotation.Nonnull String id) { + this.id = id; + return this; + } + + /** + * The ID of the Deposit Destination, which is a UUID prefixed by the string `depositDestination_`. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getId() { + return id; + } + + + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + /** + * Return true if this DepositDestinationReference object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DepositDestinationReference depositDestinationReference = (DepositDestinationReference) o; + return Objects.equals(this.id, depositDestinationReference.id); + } + + @Override + public int hashCode() { + return Objects.hash(id); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DepositDestinationReference {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `id` to the URL query string + if (getId() != null) { + joiner.add(String.format("%sid%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getId()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private DepositDestinationReference instance; + + public Builder() { + this(new DepositDestinationReference()); + } + + protected Builder(DepositDestinationReference instance) { + this.instance = instance; + } + + public DepositDestinationReference.Builder id(String id) { + this.instance.id = id; + return this; + } + + + /** + * returns a built DepositDestinationReference instance. + * + * The builder is not reusable. + */ + public DepositDestinationReference build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static DepositDestinationReference.Builder builder() { + return new DepositDestinationReference.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public DepositDestinationReference.Builder toBuilder() { + return new DepositDestinationReference.Builder() + .id(getId()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/DepositDestinationStatus.java b/java/src/main/java/com/coinbase/cdp/openapi/model/DepositDestinationStatus.java new file mode 100644 index 000000000..fc5ab41b7 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/DepositDestinationStatus.java @@ -0,0 +1,80 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * The status of the deposit destination. + */ +public enum DepositDestinationStatus { + + ACTIVE("active"), + + INACTIVE("inactive"), + + PENDING("pending"); + + private String value; + + DepositDestinationStatus(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static DepositDestinationStatus fromValue(String value) { + for (DepositDestinationStatus b : DepositDestinationStatus.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + if (prefix == null) { + prefix = ""; + } + + return String.format("%s=%s", prefix, this.toString()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/DepositDestinationTarget.java b/java/src/main/java/com/coinbase/cdp/openapi/model/DepositDestinationTarget.java new file mode 100644 index 000000000..116080c55 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/DepositDestinationTarget.java @@ -0,0 +1,241 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.DepositDestinationTargetAccount; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import com.fasterxml.jackson.core.type.TypeReference; + +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import com.coinbase.cdp.openapi.JSON; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +@JsonDeserialize(using = DepositDestinationTarget.DepositDestinationTargetDeserializer.class) +@JsonSerialize(using = DepositDestinationTarget.DepositDestinationTargetSerializer.class) +public class DepositDestinationTarget extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(DepositDestinationTarget.class.getName()); + + public static class DepositDestinationTargetSerializer extends StdSerializer { + public DepositDestinationTargetSerializer(Class t) { + super(t); + } + + public DepositDestinationTargetSerializer() { + this(null); + } + + @Override + public void serialize(DepositDestinationTarget value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { + jgen.writeObject(value.getActualInstance()); + } + } + + public static class DepositDestinationTargetDeserializer extends StdDeserializer { + public DepositDestinationTargetDeserializer() { + this(DepositDestinationTarget.class); + } + + public DepositDestinationTargetDeserializer(Class vc) { + super(vc); + } + + @Override + public DepositDestinationTarget deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { + JsonNode tree = jp.readValueAsTree(); + Object deserialized = null; + boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS); + int match = 0; + JsonToken token = tree.traverse(jp.getCodec()).nextToken(); + // deserialize DepositDestinationTargetAccount + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if (DepositDestinationTargetAccount.class.equals(Integer.class) || DepositDestinationTargetAccount.class.equals(Long.class) || DepositDestinationTargetAccount.class.equals(Float.class) || DepositDestinationTargetAccount.class.equals(Double.class) || DepositDestinationTargetAccount.class.equals(Boolean.class) || DepositDestinationTargetAccount.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= ((DepositDestinationTargetAccount.class.equals(Integer.class) || DepositDestinationTargetAccount.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= ((DepositDestinationTargetAccount.class.equals(Float.class) || DepositDestinationTargetAccount.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= (DepositDestinationTargetAccount.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= (DepositDestinationTargetAccount.class.equals(String.class) && token == JsonToken.VALUE_STRING); + } + } + if (attemptParsing) { + deserialized = tree.traverse(jp.getCodec()).readValueAs(DepositDestinationTargetAccount.class); + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema 'DepositDestinationTargetAccount'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'DepositDestinationTargetAccount'", e); + } + + if (match == 1) { + DepositDestinationTarget ret = new DepositDestinationTarget(); + ret.setActualInstance(deserialized); + return ret; + } + throw new IOException(String.format("Failed deserialization for DepositDestinationTarget: %d classes match result, expected 1", match)); + } + + /** + * Handle deserialization of the 'null' value. + */ + @Override + public DepositDestinationTarget getNullValue(DeserializationContext ctxt) throws JsonMappingException { + throw new JsonMappingException(ctxt.getParser(), "DepositDestinationTarget cannot be null"); + } + } + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public DepositDestinationTarget() { + super("oneOf", Boolean.FALSE); + } + + public DepositDestinationTarget(DepositDestinationTargetAccount o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("DepositDestinationTargetAccount", DepositDestinationTargetAccount.class); + JSON.registerDescendants(DepositDestinationTarget.class, Collections.unmodifiableMap(schemas)); + } + + @Override + public Map> getSchemas() { + return DepositDestinationTarget.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * DepositDestinationTargetAccount + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(DepositDestinationTargetAccount.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be DepositDestinationTargetAccount"); + } + + /** + * Get the actual instance, which can be the following: + * DepositDestinationTargetAccount + * + * @return The actual instance (DepositDestinationTargetAccount) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `DepositDestinationTargetAccount`. If the actual instance is not `DepositDestinationTargetAccount`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `DepositDestinationTargetAccount` + * @throws ClassCastException if the instance is not `DepositDestinationTargetAccount` + */ + public DepositDestinationTargetAccount getDepositDestinationTargetAccount() throws ClassCastException { + return (DepositDestinationTargetAccount)super.getActualInstance(); + } + + + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + if (getActualInstance() instanceof DepositDestinationTargetAccount) { + if (getActualInstance() != null) { + joiner.add(((DepositDestinationTargetAccount)getActualInstance()).toUrlQueryString(prefix + "one_of_0" + suffix)); + } + return joiner.toString(); + } + return null; + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/DepositDestinationTargetAccount.java b/java/src/main/java/com/coinbase/cdp/openapi/model/DepositDestinationTargetAccount.java new file mode 100644 index 000000000..d13be79f5 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/DepositDestinationTargetAccount.java @@ -0,0 +1,246 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * The account and asset where incoming deposits should be credited. + */ +@JsonPropertyOrder({ + DepositDestinationTargetAccount.JSON_PROPERTY_ACCOUNT_ID, + DepositDestinationTargetAccount.JSON_PROPERTY_ASSET +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class DepositDestinationTargetAccount { + public static final String JSON_PROPERTY_ACCOUNT_ID = "accountId"; + @jakarta.annotation.Nullable + private String accountId; + + public static final String JSON_PROPERTY_ASSET = "asset"; + @jakarta.annotation.Nonnull + private String asset; + + public DepositDestinationTargetAccount() { + } + + public DepositDestinationTargetAccount accountId(@jakarta.annotation.Nullable String accountId) { + this.accountId = accountId; + return this; + } + + /** + * The ID of the CDP Account to which deposited funds should be transferred. + * @return accountId + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ACCOUNT_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getAccountId() { + return accountId; + } + + + @JsonProperty(JSON_PROPERTY_ACCOUNT_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setAccountId(@jakarta.annotation.Nullable String accountId) { + this.accountId = accountId; + } + + + public DepositDestinationTargetAccount asset(@jakarta.annotation.Nonnull String asset) { + this.asset = asset; + return this; + } + + /** + * The symbol of the asset that should land in the target account. + * @return asset + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAsset() { + return asset; + } + + + @JsonProperty(JSON_PROPERTY_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAsset(@jakarta.annotation.Nonnull String asset) { + this.asset = asset; + } + + + /** + * Return true if this DepositDestinationTargetAccount object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DepositDestinationTargetAccount depositDestinationTargetAccount = (DepositDestinationTargetAccount) o; + return Objects.equals(this.accountId, depositDestinationTargetAccount.accountId) && + Objects.equals(this.asset, depositDestinationTargetAccount.asset); + } + + @Override + public int hashCode() { + return Objects.hash(accountId, asset); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DepositDestinationTargetAccount {\n"); + sb.append(" accountId: ").append(toIndentedString(accountId)).append("\n"); + sb.append(" asset: ").append(toIndentedString(asset)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `accountId` to the URL query string + if (getAccountId() != null) { + joiner.add(String.format("%saccountId%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAccountId()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `asset` to the URL query string + if (getAsset() != null) { + joiner.add(String.format("%sasset%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAsset()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private DepositDestinationTargetAccount instance; + + public Builder() { + this(new DepositDestinationTargetAccount()); + } + + protected Builder(DepositDestinationTargetAccount instance) { + this.instance = instance; + } + + public DepositDestinationTargetAccount.Builder accountId(String accountId) { + this.instance.accountId = accountId; + return this; + } + public DepositDestinationTargetAccount.Builder asset(String asset) { + this.instance.asset = asset; + return this; + } + + + /** + * returns a built DepositDestinationTargetAccount instance. + * + * The builder is not reusable. + */ + public DepositDestinationTargetAccount build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static DepositDestinationTargetAccount.Builder builder() { + return new DepositDestinationTargetAccount.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public DepositDestinationTargetAccount.Builder toBuilder() { + return new DepositDestinationTargetAccount.Builder() + .accountId(getAccountId()) + .asset(getAsset()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/DepositTravelRuleBeneficiary.java b/java/src/main/java/com/coinbase/cdp/openapi/model/DepositTravelRuleBeneficiary.java new file mode 100644 index 000000000..5b66770e7 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/DepositTravelRuleBeneficiary.java @@ -0,0 +1,205 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * Beneficiary information for a deposit travel rule submission. + */ +@JsonPropertyOrder({ + DepositTravelRuleBeneficiary.JSON_PROPERTY_NAME +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class DepositTravelRuleBeneficiary { + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nullable + private String name; + + public DepositTravelRuleBeneficiary() { + } + + public DepositTravelRuleBeneficiary name(@jakarta.annotation.Nullable String name) { + this.name = name; + return this; + } + + /** + * Full name of the beneficiary. + * @return name + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getName() { + return name; + } + + + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setName(@jakarta.annotation.Nullable String name) { + this.name = name; + } + + + /** + * Return true if this DepositTravelRuleBeneficiary object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DepositTravelRuleBeneficiary depositTravelRuleBeneficiary = (DepositTravelRuleBeneficiary) o; + return Objects.equals(this.name, depositTravelRuleBeneficiary.name); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DepositTravelRuleBeneficiary {\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `name` to the URL query string + if (getName() != null) { + joiner.add(String.format("%sname%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getName()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private DepositTravelRuleBeneficiary instance; + + public Builder() { + this(new DepositTravelRuleBeneficiary()); + } + + protected Builder(DepositTravelRuleBeneficiary instance) { + this.instance = instance; + } + + public DepositTravelRuleBeneficiary.Builder name(String name) { + this.instance.name = name; + return this; + } + + + /** + * returns a built DepositTravelRuleBeneficiary instance. + * + * The builder is not reusable. + */ + public DepositTravelRuleBeneficiary build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static DepositTravelRuleBeneficiary.Builder builder() { + return new DepositTravelRuleBeneficiary.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public DepositTravelRuleBeneficiary.Builder toBuilder() { + return new DepositTravelRuleBeneficiary.Builder() + .name(getName()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/DepositTravelRuleOriginator.java b/java/src/main/java/com/coinbase/cdp/openapi/model/DepositTravelRuleOriginator.java new file mode 100644 index 000000000..aad05de54 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/DepositTravelRuleOriginator.java @@ -0,0 +1,454 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.DateOfBirth; +import com.coinbase.cdp.openapi.model.DepositTravelRuleVasp; +import com.coinbase.cdp.openapi.model.PhysicalAddress; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * Originator information for a deposit travel rule submission. + */ +@JsonPropertyOrder({ + DepositTravelRuleOriginator.JSON_PROPERTY_NAME, + DepositTravelRuleOriginator.JSON_PROPERTY_ADDRESS, + DepositTravelRuleOriginator.JSON_PROPERTY_WALLET_TYPE, + DepositTravelRuleOriginator.JSON_PROPERTY_VIRTUAL_ASSET_SERVICE_PROVIDER, + DepositTravelRuleOriginator.JSON_PROPERTY_PERSONAL_ID, + DepositTravelRuleOriginator.JSON_PROPERTY_DATE_OF_BIRTH +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class DepositTravelRuleOriginator { + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nullable + private String name; + + public static final String JSON_PROPERTY_ADDRESS = "address"; + @jakarta.annotation.Nullable + private PhysicalAddress address; + + /** + * The type of the originator's wallet. + */ + public enum WalletTypeEnum { + /** + * The originator's wallet is held by a custodial service. + */ + CUSTODIAL(String.valueOf("custodial")), + + /** + * The originator's wallet is self-custodied. + */ + SELF_CUSTODY(String.valueOf("self_custody")); + + private String value; + + WalletTypeEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static WalletTypeEnum fromValue(String value) { + for (WalletTypeEnum b : WalletTypeEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + public static final String JSON_PROPERTY_WALLET_TYPE = "walletType"; + @jakarta.annotation.Nullable + private WalletTypeEnum walletType; + + public static final String JSON_PROPERTY_VIRTUAL_ASSET_SERVICE_PROVIDER = "virtualAssetServiceProvider"; + @jakarta.annotation.Nullable + private DepositTravelRuleVasp virtualAssetServiceProvider; + + public static final String JSON_PROPERTY_PERSONAL_ID = "personalId"; + @jakarta.annotation.Nullable + private String personalId; + + public static final String JSON_PROPERTY_DATE_OF_BIRTH = "dateOfBirth"; + @jakarta.annotation.Nullable + private DateOfBirth dateOfBirth; + + public DepositTravelRuleOriginator() { + } + + public DepositTravelRuleOriginator name(@jakarta.annotation.Nullable String name) { + this.name = name; + return this; + } + + /** + * Full name of the originator. + * @return name + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getName() { + return name; + } + + + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setName(@jakarta.annotation.Nullable String name) { + this.name = name; + } + + + public DepositTravelRuleOriginator address(@jakarta.annotation.Nullable PhysicalAddress address) { + this.address = address; + return this; + } + + /** + * Get address + * @return address + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ADDRESS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public PhysicalAddress getAddress() { + return address; + } + + + @JsonProperty(JSON_PROPERTY_ADDRESS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setAddress(@jakarta.annotation.Nullable PhysicalAddress address) { + this.address = address; + } + + + public DepositTravelRuleOriginator walletType(@jakarta.annotation.Nullable WalletTypeEnum walletType) { + this.walletType = walletType; + return this; + } + + /** + * The type of the originator's wallet. + * @return walletType + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_WALLET_TYPE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public WalletTypeEnum getWalletType() { + return walletType; + } + + + @JsonProperty(JSON_PROPERTY_WALLET_TYPE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setWalletType(@jakarta.annotation.Nullable WalletTypeEnum walletType) { + this.walletType = walletType; + } + + + public DepositTravelRuleOriginator virtualAssetServiceProvider(@jakarta.annotation.Nullable DepositTravelRuleVasp virtualAssetServiceProvider) { + this.virtualAssetServiceProvider = virtualAssetServiceProvider; + return this; + } + + /** + * Get virtualAssetServiceProvider + * @return virtualAssetServiceProvider + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_VIRTUAL_ASSET_SERVICE_PROVIDER) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public DepositTravelRuleVasp getVirtualAssetServiceProvider() { + return virtualAssetServiceProvider; + } + + + @JsonProperty(JSON_PROPERTY_VIRTUAL_ASSET_SERVICE_PROVIDER) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setVirtualAssetServiceProvider(@jakarta.annotation.Nullable DepositTravelRuleVasp virtualAssetServiceProvider) { + this.virtualAssetServiceProvider = virtualAssetServiceProvider; + } + + + public DepositTravelRuleOriginator personalId(@jakarta.annotation.Nullable String personalId) { + this.personalId = personalId; + return this; + } + + /** + * Government-issued personal identification number for the originator. + * @return personalId + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_PERSONAL_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getPersonalId() { + return personalId; + } + + + @JsonProperty(JSON_PROPERTY_PERSONAL_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setPersonalId(@jakarta.annotation.Nullable String personalId) { + this.personalId = personalId; + } + + + public DepositTravelRuleOriginator dateOfBirth(@jakarta.annotation.Nullable DateOfBirth dateOfBirth) { + this.dateOfBirth = dateOfBirth; + return this; + } + + /** + * Get dateOfBirth + * @return dateOfBirth + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_DATE_OF_BIRTH) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public DateOfBirth getDateOfBirth() { + return dateOfBirth; + } + + + @JsonProperty(JSON_PROPERTY_DATE_OF_BIRTH) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setDateOfBirth(@jakarta.annotation.Nullable DateOfBirth dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } + + + /** + * Return true if this DepositTravelRuleOriginator object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DepositTravelRuleOriginator depositTravelRuleOriginator = (DepositTravelRuleOriginator) o; + return Objects.equals(this.name, depositTravelRuleOriginator.name) && + Objects.equals(this.address, depositTravelRuleOriginator.address) && + Objects.equals(this.walletType, depositTravelRuleOriginator.walletType) && + Objects.equals(this.virtualAssetServiceProvider, depositTravelRuleOriginator.virtualAssetServiceProvider) && + Objects.equals(this.personalId, depositTravelRuleOriginator.personalId) && + Objects.equals(this.dateOfBirth, depositTravelRuleOriginator.dateOfBirth); + } + + @Override + public int hashCode() { + return Objects.hash(name, address, walletType, virtualAssetServiceProvider, personalId, dateOfBirth); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DepositTravelRuleOriginator {\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" address: ").append(toIndentedString(address)).append("\n"); + sb.append(" walletType: ").append(toIndentedString(walletType)).append("\n"); + sb.append(" virtualAssetServiceProvider: ").append(toIndentedString(virtualAssetServiceProvider)).append("\n"); + sb.append(" personalId: ").append(toIndentedString(personalId)).append("\n"); + sb.append(" dateOfBirth: ").append(toIndentedString(dateOfBirth)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `name` to the URL query string + if (getName() != null) { + joiner.add(String.format("%sname%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getName()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `address` to the URL query string + if (getAddress() != null) { + joiner.add(getAddress().toUrlQueryString(prefix + "address" + suffix)); + } + + // add `walletType` to the URL query string + if (getWalletType() != null) { + joiner.add(String.format("%swalletType%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getWalletType()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `virtualAssetServiceProvider` to the URL query string + if (getVirtualAssetServiceProvider() != null) { + joiner.add(getVirtualAssetServiceProvider().toUrlQueryString(prefix + "virtualAssetServiceProvider" + suffix)); + } + + // add `personalId` to the URL query string + if (getPersonalId() != null) { + joiner.add(String.format("%spersonalId%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getPersonalId()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `dateOfBirth` to the URL query string + if (getDateOfBirth() != null) { + joiner.add(getDateOfBirth().toUrlQueryString(prefix + "dateOfBirth" + suffix)); + } + + return joiner.toString(); + } + + public static class Builder { + + private DepositTravelRuleOriginator instance; + + public Builder() { + this(new DepositTravelRuleOriginator()); + } + + protected Builder(DepositTravelRuleOriginator instance) { + this.instance = instance; + } + + public DepositTravelRuleOriginator.Builder name(String name) { + this.instance.name = name; + return this; + } + public DepositTravelRuleOriginator.Builder address(PhysicalAddress address) { + this.instance.address = address; + return this; + } + public DepositTravelRuleOriginator.Builder walletType(WalletTypeEnum walletType) { + this.instance.walletType = walletType; + return this; + } + public DepositTravelRuleOriginator.Builder virtualAssetServiceProvider(DepositTravelRuleVasp virtualAssetServiceProvider) { + this.instance.virtualAssetServiceProvider = virtualAssetServiceProvider; + return this; + } + public DepositTravelRuleOriginator.Builder personalId(String personalId) { + this.instance.personalId = personalId; + return this; + } + public DepositTravelRuleOriginator.Builder dateOfBirth(DateOfBirth dateOfBirth) { + this.instance.dateOfBirth = dateOfBirth; + return this; + } + + + /** + * returns a built DepositTravelRuleOriginator instance. + * + * The builder is not reusable. + */ + public DepositTravelRuleOriginator build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static DepositTravelRuleOriginator.Builder builder() { + return new DepositTravelRuleOriginator.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public DepositTravelRuleOriginator.Builder toBuilder() { + return new DepositTravelRuleOriginator.Builder() + .name(getName()) + .address(getAddress()) + .walletType(getWalletType()) + .virtualAssetServiceProvider(getVirtualAssetServiceProvider()) + .personalId(getPersonalId()) + .dateOfBirth(getDateOfBirth()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/DepositTravelRuleRequest.java b/java/src/main/java/com/coinbase/cdp/openapi/model/DepositTravelRuleRequest.java new file mode 100644 index 000000000..cdea38bc7 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/DepositTravelRuleRequest.java @@ -0,0 +1,289 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.DepositTravelRuleBeneficiary; +import com.coinbase.cdp.openapi.model.DepositTravelRuleOriginator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * Request body for submitting travel rule information for a deposit transfer. Required fields vary by jurisdiction. + */ +@JsonPropertyOrder({ + DepositTravelRuleRequest.JSON_PROPERTY_ORIGINATOR, + DepositTravelRuleRequest.JSON_PROPERTY_BENEFICIARY, + DepositTravelRuleRequest.JSON_PROPERTY_IS_SELF +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class DepositTravelRuleRequest { + public static final String JSON_PROPERTY_ORIGINATOR = "originator"; + @jakarta.annotation.Nullable + private DepositTravelRuleOriginator originator; + + public static final String JSON_PROPERTY_BENEFICIARY = "beneficiary"; + @jakarta.annotation.Nullable + private DepositTravelRuleBeneficiary beneficiary; + + public static final String JSON_PROPERTY_IS_SELF = "isSelf"; + @jakarta.annotation.Nullable + private Boolean isSelf; + + public DepositTravelRuleRequest() { + } + + public DepositTravelRuleRequest originator(@jakarta.annotation.Nullable DepositTravelRuleOriginator originator) { + this.originator = originator; + return this; + } + + /** + * Get originator + * @return originator + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ORIGINATOR) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public DepositTravelRuleOriginator getOriginator() { + return originator; + } + + + @JsonProperty(JSON_PROPERTY_ORIGINATOR) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setOriginator(@jakarta.annotation.Nullable DepositTravelRuleOriginator originator) { + this.originator = originator; + } + + + public DepositTravelRuleRequest beneficiary(@jakarta.annotation.Nullable DepositTravelRuleBeneficiary beneficiary) { + this.beneficiary = beneficiary; + return this; + } + + /** + * Get beneficiary + * @return beneficiary + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_BENEFICIARY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public DepositTravelRuleBeneficiary getBeneficiary() { + return beneficiary; + } + + + @JsonProperty(JSON_PROPERTY_BENEFICIARY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setBeneficiary(@jakarta.annotation.Nullable DepositTravelRuleBeneficiary beneficiary) { + this.beneficiary = beneficiary; + } + + + public DepositTravelRuleRequest isSelf(@jakarta.annotation.Nullable Boolean isSelf) { + this.isSelf = isSelf; + return this; + } + + /** + * Indicates whether the user attests that the originating wallet belongs to them. + * @return isSelf + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_IS_SELF) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public Boolean getIsSelf() { + return isSelf; + } + + + @JsonProperty(JSON_PROPERTY_IS_SELF) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setIsSelf(@jakarta.annotation.Nullable Boolean isSelf) { + this.isSelf = isSelf; + } + + + /** + * Return true if this DepositTravelRuleRequest object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DepositTravelRuleRequest depositTravelRuleRequest = (DepositTravelRuleRequest) o; + return Objects.equals(this.originator, depositTravelRuleRequest.originator) && + Objects.equals(this.beneficiary, depositTravelRuleRequest.beneficiary) && + Objects.equals(this.isSelf, depositTravelRuleRequest.isSelf); + } + + @Override + public int hashCode() { + return Objects.hash(originator, beneficiary, isSelf); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DepositTravelRuleRequest {\n"); + sb.append(" originator: ").append(toIndentedString(originator)).append("\n"); + sb.append(" beneficiary: ").append(toIndentedString(beneficiary)).append("\n"); + sb.append(" isSelf: ").append(toIndentedString(isSelf)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `originator` to the URL query string + if (getOriginator() != null) { + joiner.add(getOriginator().toUrlQueryString(prefix + "originator" + suffix)); + } + + // add `beneficiary` to the URL query string + if (getBeneficiary() != null) { + joiner.add(getBeneficiary().toUrlQueryString(prefix + "beneficiary" + suffix)); + } + + // add `isSelf` to the URL query string + if (getIsSelf() != null) { + joiner.add(String.format("%sisSelf%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getIsSelf()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private DepositTravelRuleRequest instance; + + public Builder() { + this(new DepositTravelRuleRequest()); + } + + protected Builder(DepositTravelRuleRequest instance) { + this.instance = instance; + } + + public DepositTravelRuleRequest.Builder originator(DepositTravelRuleOriginator originator) { + this.instance.originator = originator; + return this; + } + public DepositTravelRuleRequest.Builder beneficiary(DepositTravelRuleBeneficiary beneficiary) { + this.instance.beneficiary = beneficiary; + return this; + } + public DepositTravelRuleRequest.Builder isSelf(Boolean isSelf) { + this.instance.isSelf = isSelf; + return this; + } + + + /** + * returns a built DepositTravelRuleRequest instance. + * + * The builder is not reusable. + */ + public DepositTravelRuleRequest build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static DepositTravelRuleRequest.Builder builder() { + return new DepositTravelRuleRequest.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public DepositTravelRuleRequest.Builder toBuilder() { + return new DepositTravelRuleRequest.Builder() + .originator(getOriginator()) + .beneficiary(getBeneficiary()) + .isSelf(getIsSelf()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/DepositTravelRuleResponse.java b/java/src/main/java/com/coinbase/cdp/openapi/model/DepositTravelRuleResponse.java new file mode 100644 index 000000000..ebd516e15 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/DepositTravelRuleResponse.java @@ -0,0 +1,302 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.TravelRuleStatus; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * Response from submitting travel rule information for a deposit transfer. + */ +@JsonPropertyOrder({ + DepositTravelRuleResponse.JSON_PROPERTY_STATUS, + DepositTravelRuleResponse.JSON_PROPERTY_MISSING_FIELDS, + DepositTravelRuleResponse.JSON_PROPERTY_REASON +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class DepositTravelRuleResponse { + public static final String JSON_PROPERTY_STATUS = "status"; + @jakarta.annotation.Nonnull + private TravelRuleStatus status; + + public static final String JSON_PROPERTY_MISSING_FIELDS = "missingFields"; + @jakarta.annotation.Nullable + private List missingFields = new ArrayList<>(); + + public static final String JSON_PROPERTY_REASON = "reason"; + @jakarta.annotation.Nullable + private String reason; + + public DepositTravelRuleResponse() { + } + + public DepositTravelRuleResponse status(@jakarta.annotation.Nonnull TravelRuleStatus status) { + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_STATUS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public TravelRuleStatus getStatus() { + return status; + } + + + @JsonProperty(JSON_PROPERTY_STATUS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStatus(@jakarta.annotation.Nonnull TravelRuleStatus status) { + this.status = status; + } + + + public DepositTravelRuleResponse missingFields(@jakarta.annotation.Nullable List missingFields) { + this.missingFields = missingFields; + return this; + } + + public DepositTravelRuleResponse addMissingFieldsItem(String missingFieldsItem) { + if (this.missingFields == null) { + this.missingFields = new ArrayList<>(); + } + this.missingFields.add(missingFieldsItem); + return this; + } + + /** + * List of field paths that are still required to complete travel rule compliance. Each entry is a dot-separated path (e.g., \"originator.name\", \"originator.address.countryCode\"). Empty when status is \"completed\". + * @return missingFields + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_MISSING_FIELDS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public List getMissingFields() { + return missingFields; + } + + + @JsonProperty(JSON_PROPERTY_MISSING_FIELDS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setMissingFields(@jakarta.annotation.Nullable List missingFields) { + this.missingFields = missingFields; + } + + + public DepositTravelRuleResponse reason(@jakarta.annotation.Nullable String reason) { + this.reason = reason; + return this; + } + + /** + * Additional context about the current status. Present when status is `incomplete` to explain what needs to be fixed before the transfer can proceed. + * @return reason + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_REASON) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getReason() { + return reason; + } + + + @JsonProperty(JSON_PROPERTY_REASON) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setReason(@jakarta.annotation.Nullable String reason) { + this.reason = reason; + } + + + /** + * Return true if this DepositTravelRuleResponse object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DepositTravelRuleResponse depositTravelRuleResponse = (DepositTravelRuleResponse) o; + return Objects.equals(this.status, depositTravelRuleResponse.status) && + Objects.equals(this.missingFields, depositTravelRuleResponse.missingFields) && + Objects.equals(this.reason, depositTravelRuleResponse.reason); + } + + @Override + public int hashCode() { + return Objects.hash(status, missingFields, reason); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DepositTravelRuleResponse {\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" missingFields: ").append(toIndentedString(missingFields)).append("\n"); + sb.append(" reason: ").append(toIndentedString(reason)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `status` to the URL query string + if (getStatus() != null) { + joiner.add(String.format("%sstatus%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getStatus()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `missingFields` to the URL query string + if (getMissingFields() != null) { + for (int i = 0; i < getMissingFields().size(); i++) { + joiner.add(String.format("%smissingFields%s%s=%s", prefix, suffix, + "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, i, containerSuffix), + URLEncoder.encode(ApiClient.valueToString(getMissingFields().get(i)), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + } + + // add `reason` to the URL query string + if (getReason() != null) { + joiner.add(String.format("%sreason%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getReason()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private DepositTravelRuleResponse instance; + + public Builder() { + this(new DepositTravelRuleResponse()); + } + + protected Builder(DepositTravelRuleResponse instance) { + this.instance = instance; + } + + public DepositTravelRuleResponse.Builder status(TravelRuleStatus status) { + this.instance.status = status; + return this; + } + public DepositTravelRuleResponse.Builder missingFields(List missingFields) { + this.instance.missingFields = missingFields; + return this; + } + public DepositTravelRuleResponse.Builder reason(String reason) { + this.instance.reason = reason; + return this; + } + + + /** + * returns a built DepositTravelRuleResponse instance. + * + * The builder is not reusable. + */ + public DepositTravelRuleResponse build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static DepositTravelRuleResponse.Builder builder() { + return new DepositTravelRuleResponse.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public DepositTravelRuleResponse.Builder toBuilder() { + return new DepositTravelRuleResponse.Builder() + .status(getStatus()) + .missingFields(getMissingFields()) + .reason(getReason()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/DepositTravelRuleVasp.java b/java/src/main/java/com/coinbase/cdp/openapi/model/DepositTravelRuleVasp.java new file mode 100644 index 000000000..1cef6e03d --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/DepositTravelRuleVasp.java @@ -0,0 +1,246 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * Information about the Virtual Asset Service Provider (VASP) for a deposit travel rule submission. + */ +@JsonPropertyOrder({ + DepositTravelRuleVasp.JSON_PROPERTY_IDENTIFIER, + DepositTravelRuleVasp.JSON_PROPERTY_NAME +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class DepositTravelRuleVasp { + public static final String JSON_PROPERTY_IDENTIFIER = "identifier"; + @jakarta.annotation.Nullable + private String identifier; + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nullable + private String name; + + public DepositTravelRuleVasp() { + } + + public DepositTravelRuleVasp identifier(@jakarta.annotation.Nullable String identifier) { + this.identifier = identifier; + return this; + } + + /** + * The Legal Entity Identifier (LEI) of the Virtual Asset Service Provider (VASP). + * @return identifier + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_IDENTIFIER) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getIdentifier() { + return identifier; + } + + + @JsonProperty(JSON_PROPERTY_IDENTIFIER) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setIdentifier(@jakarta.annotation.Nullable String identifier) { + this.identifier = identifier; + } + + + public DepositTravelRuleVasp name(@jakarta.annotation.Nullable String name) { + this.name = name; + return this; + } + + /** + * The name of the Virtual Asset Service Provider (VASP). + * @return name + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getName() { + return name; + } + + + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setName(@jakarta.annotation.Nullable String name) { + this.name = name; + } + + + /** + * Return true if this DepositTravelRuleVasp object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DepositTravelRuleVasp depositTravelRuleVasp = (DepositTravelRuleVasp) o; + return Objects.equals(this.identifier, depositTravelRuleVasp.identifier) && + Objects.equals(this.name, depositTravelRuleVasp.name); + } + + @Override + public int hashCode() { + return Objects.hash(identifier, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DepositTravelRuleVasp {\n"); + sb.append(" identifier: ").append(toIndentedString(identifier)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `identifier` to the URL query string + if (getIdentifier() != null) { + joiner.add(String.format("%sidentifier%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getIdentifier()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `name` to the URL query string + if (getName() != null) { + joiner.add(String.format("%sname%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getName()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private DepositTravelRuleVasp instance; + + public Builder() { + this(new DepositTravelRuleVasp()); + } + + protected Builder(DepositTravelRuleVasp instance) { + this.instance = instance; + } + + public DepositTravelRuleVasp.Builder identifier(String identifier) { + this.instance.identifier = identifier; + return this; + } + public DepositTravelRuleVasp.Builder name(String name) { + this.instance.name = name; + return this; + } + + + /** + * returns a built DepositTravelRuleVasp instance. + * + * The builder is not reusable. + */ + public DepositTravelRuleVasp build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static DepositTravelRuleVasp.Builder builder() { + return new DepositTravelRuleVasp.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public DepositTravelRuleVasp.Builder toBuilder() { + return new DepositTravelRuleVasp.Builder() + .identifier(getIdentifier()) + .name(getName()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/EmailAddress.java b/java/src/main/java/com/coinbase/cdp/openapi/model/EmailAddress.java new file mode 100644 index 000000000..3e5dceeaa --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/EmailAddress.java @@ -0,0 +1,205 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * The target of the payment is an email address. + */ +@JsonPropertyOrder({ + EmailAddress.JSON_PROPERTY_EMAIL +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class EmailAddress { + public static final String JSON_PROPERTY_EMAIL = "email"; + @jakarta.annotation.Nonnull + private String email; + + public EmailAddress() { + } + + public EmailAddress email(@jakarta.annotation.Nonnull String email) { + this.email = email; + return this; + } + + /** + * The email address of the recipient. The recipient will need to have an account with Coinbase or onboard to Coinbase to receive the payment. + * @return email + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_EMAIL) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getEmail() { + return email; + } + + + @JsonProperty(JSON_PROPERTY_EMAIL) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEmail(@jakarta.annotation.Nonnull String email) { + this.email = email; + } + + + /** + * Return true if this EmailAddress object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EmailAddress emailAddress = (EmailAddress) o; + return Objects.equals(this.email, emailAddress.email); + } + + @Override + public int hashCode() { + return Objects.hash(email); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EmailAddress {\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `email` to the URL query string + if (getEmail() != null) { + joiner.add(String.format("%semail%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getEmail()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private EmailAddress instance; + + public Builder() { + this(new EmailAddress()); + } + + protected Builder(EmailAddress instance) { + this.instance = instance; + } + + public EmailAddress.Builder email(String email) { + this.instance.email = email; + return this; + } + + + /** + * returns a built EmailAddress instance. + * + * The builder is not reusable. + */ + public EmailAddress build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static EmailAddress.Builder builder() { + return new EmailAddress.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public EmailAddress.Builder toBuilder() { + return new EmailAddress.Builder() + .email(getEmail()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/EmailInstrument.java b/java/src/main/java/com/coinbase/cdp/openapi/model/EmailInstrument.java new file mode 100644 index 000000000..09c1e6d17 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/EmailInstrument.java @@ -0,0 +1,246 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * The target of the payment is an email address. + */ +@JsonPropertyOrder({ + EmailInstrument.JSON_PROPERTY_EMAIL, + EmailInstrument.JSON_PROPERTY_ASSET +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class EmailInstrument { + public static final String JSON_PROPERTY_EMAIL = "email"; + @jakarta.annotation.Nonnull + private String email; + + public static final String JSON_PROPERTY_ASSET = "asset"; + @jakarta.annotation.Nonnull + private String asset; + + public EmailInstrument() { + } + + public EmailInstrument email(@jakarta.annotation.Nonnull String email) { + this.email = email; + return this; + } + + /** + * The email address of the recipient. The recipient will need to have an account with Coinbase or onboard to Coinbase to receive the payment. + * @return email + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_EMAIL) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getEmail() { + return email; + } + + + @JsonProperty(JSON_PROPERTY_EMAIL) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEmail(@jakarta.annotation.Nonnull String email) { + this.email = email; + } + + + public EmailInstrument asset(@jakarta.annotation.Nonnull String asset) { + this.asset = asset; + return this; + } + + /** + * Asset symbol of the payment received by the recipient. + * @return asset + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAsset() { + return asset; + } + + + @JsonProperty(JSON_PROPERTY_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAsset(@jakarta.annotation.Nonnull String asset) { + this.asset = asset; + } + + + /** + * Return true if this EmailInstrument object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EmailInstrument emailInstrument = (EmailInstrument) o; + return Objects.equals(this.email, emailInstrument.email) && + Objects.equals(this.asset, emailInstrument.asset); + } + + @Override + public int hashCode() { + return Objects.hash(email, asset); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EmailInstrument {\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" asset: ").append(toIndentedString(asset)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `email` to the URL query string + if (getEmail() != null) { + joiner.add(String.format("%semail%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getEmail()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `asset` to the URL query string + if (getAsset() != null) { + joiner.add(String.format("%sasset%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAsset()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private EmailInstrument instance; + + public Builder() { + this(new EmailInstrument()); + } + + protected Builder(EmailInstrument instance) { + this.instance = instance; + } + + public EmailInstrument.Builder email(String email) { + this.instance.email = email; + return this; + } + public EmailInstrument.Builder asset(String asset) { + this.instance.asset = asset; + return this; + } + + + /** + * returns a built EmailInstrument instance. + * + * The builder is not reusable. + */ + public EmailInstrument build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static EmailInstrument.Builder builder() { + return new EmailInstrument.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public EmailInstrument.Builder toBuilder() { + return new EmailInstrument.Builder() + .email(getEmail()) + .asset(getAsset()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/ErrorType.java b/java/src/main/java/com/coinbase/cdp/openapi/model/ErrorType.java index 10d4cf7a2..56e27a743 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/model/ErrorType.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/ErrorType.java @@ -40,6 +40,8 @@ public enum ErrorType { CLIENT_CLOSED_REQUEST("client_closed_request"), + ENDPOINT_UNAVAILABLE("endpoint_unavailable"), + FAUCET_LIMIT_EXCEEDED("faucet_limit_exceeded"), FORBIDDEN("forbidden"), @@ -74,6 +76,8 @@ public enum ErrorType { UNAUTHORIZED("unauthorized"), + UNSUPPORTED_TOS_LANGUAGE("unsupported_tos_language"), + POLICY_VIOLATION("policy_violation"), POLICY_IN_USE("policy_in_use"), @@ -122,6 +126,8 @@ public enum ErrorType { TRANSFER_ASSET_NOT_SUPPORTED("transfer_asset_not_supported"), + TRANSFER_QUOTE_EXPIRED("transfer_quote_expired"), + INSUFFICIENT_BALANCE("insufficient_balance"), METADATA_TOO_MANY_ENTRIES("metadata_too_many_entries"), @@ -156,7 +162,17 @@ public enum ErrorType { INSUFFICIENT_ALLOWANCE("insufficient_allowance"), - TRANSACTION_SIMULATION_FAILED("transaction_simulation_failed"); + TRANSACTION_SIMULATION_FAILED("transaction_simulation_failed"), + + DELEGATION_NOT_FOUND("delegation_not_found"), + + DELEGATION_EXPIRED("delegation_expired"), + + DELEGATION_REVOKED("delegation_revoked"), + + DELEGATION_NOT_AUTHORIZED("delegation_not_authorized"), + + DELEGATION_NOT_ENABLED("delegation_not_enabled"); private String value; diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/FedwireDetails.java b/java/src/main/java/com/coinbase/cdp/openapi/model/FedwireDetails.java new file mode 100644 index 000000000..660bc03e6 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/FedwireDetails.java @@ -0,0 +1,328 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * Details specific to Fedwire (domestic USD wire) payment methods. + */ +@JsonPropertyOrder({ + FedwireDetails.JSON_PROPERTY_ASSET, + FedwireDetails.JSON_PROPERTY_BANK_NAME, + FedwireDetails.JSON_PROPERTY_ACCOUNT_LAST4, + FedwireDetails.JSON_PROPERTY_ROUTING_NUMBER +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class FedwireDetails { + public static final String JSON_PROPERTY_ASSET = "asset"; + @jakarta.annotation.Nonnull + private String asset; + + public static final String JSON_PROPERTY_BANK_NAME = "bankName"; + @jakarta.annotation.Nonnull + private String bankName; + + public static final String JSON_PROPERTY_ACCOUNT_LAST4 = "accountLast4"; + @jakarta.annotation.Nonnull + private String accountLast4; + + public static final String JSON_PROPERTY_ROUTING_NUMBER = "routingNumber"; + @jakarta.annotation.Nonnull + private String routingNumber; + + public FedwireDetails() { + } + + public FedwireDetails asset(@jakarta.annotation.Nonnull String asset) { + this.asset = asset; + return this; + } + + /** + * The asset for this payment method. Always `usd` for Fedwire. + * @return asset + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAsset() { + return asset; + } + + + @JsonProperty(JSON_PROPERTY_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAsset(@jakarta.annotation.Nonnull String asset) { + this.asset = asset; + } + + + public FedwireDetails bankName(@jakarta.annotation.Nonnull String bankName) { + this.bankName = bankName; + return this; + } + + /** + * The name of the bank. + * @return bankName + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_BANK_NAME) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getBankName() { + return bankName; + } + + + @JsonProperty(JSON_PROPERTY_BANK_NAME) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBankName(@jakarta.annotation.Nonnull String bankName) { + this.bankName = bankName; + } + + + public FedwireDetails accountLast4(@jakarta.annotation.Nonnull String accountLast4) { + this.accountLast4 = accountLast4; + return this; + } + + /** + * The last 4 digits of the bank account number. + * @return accountLast4 + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ACCOUNT_LAST4) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAccountLast4() { + return accountLast4; + } + + + @JsonProperty(JSON_PROPERTY_ACCOUNT_LAST4) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAccountLast4(@jakarta.annotation.Nonnull String accountLast4) { + this.accountLast4 = accountLast4; + } + + + public FedwireDetails routingNumber(@jakarta.annotation.Nonnull String routingNumber) { + this.routingNumber = routingNumber; + return this; + } + + /** + * The ABA routing number of the bank. + * @return routingNumber + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ROUTING_NUMBER) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getRoutingNumber() { + return routingNumber; + } + + + @JsonProperty(JSON_PROPERTY_ROUTING_NUMBER) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setRoutingNumber(@jakarta.annotation.Nonnull String routingNumber) { + this.routingNumber = routingNumber; + } + + + /** + * Return true if this FedwireDetails object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FedwireDetails fedwireDetails = (FedwireDetails) o; + return Objects.equals(this.asset, fedwireDetails.asset) && + Objects.equals(this.bankName, fedwireDetails.bankName) && + Objects.equals(this.accountLast4, fedwireDetails.accountLast4) && + Objects.equals(this.routingNumber, fedwireDetails.routingNumber); + } + + @Override + public int hashCode() { + return Objects.hash(asset, bankName, accountLast4, routingNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FedwireDetails {\n"); + sb.append(" asset: ").append(toIndentedString(asset)).append("\n"); + sb.append(" bankName: ").append(toIndentedString(bankName)).append("\n"); + sb.append(" accountLast4: ").append(toIndentedString(accountLast4)).append("\n"); + sb.append(" routingNumber: ").append(toIndentedString(routingNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `asset` to the URL query string + if (getAsset() != null) { + joiner.add(String.format("%sasset%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAsset()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `bankName` to the URL query string + if (getBankName() != null) { + joiner.add(String.format("%sbankName%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getBankName()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `accountLast4` to the URL query string + if (getAccountLast4() != null) { + joiner.add(String.format("%saccountLast4%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAccountLast4()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `routingNumber` to the URL query string + if (getRoutingNumber() != null) { + joiner.add(String.format("%sroutingNumber%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getRoutingNumber()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private FedwireDetails instance; + + public Builder() { + this(new FedwireDetails()); + } + + protected Builder(FedwireDetails instance) { + this.instance = instance; + } + + public FedwireDetails.Builder asset(String asset) { + this.instance.asset = asset; + return this; + } + public FedwireDetails.Builder bankName(String bankName) { + this.instance.bankName = bankName; + return this; + } + public FedwireDetails.Builder accountLast4(String accountLast4) { + this.instance.accountLast4 = accountLast4; + return this; + } + public FedwireDetails.Builder routingNumber(String routingNumber) { + this.instance.routingNumber = routingNumber; + return this; + } + + + /** + * returns a built FedwireDetails instance. + * + * The builder is not reusable. + */ + public FedwireDetails build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static FedwireDetails.Builder builder() { + return new FedwireDetails.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public FedwireDetails.Builder toBuilder() { + return new FedwireDetails.Builder() + .asset(getAsset()) + .bankName(getBankName()) + .accountLast4(getAccountLast4()) + .routingNumber(getRoutingNumber()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/FedwirePaymentMethod.java b/java/src/main/java/com/coinbase/cdp/openapi/model/FedwirePaymentMethod.java new file mode 100644 index 000000000..3533f2af7 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/FedwirePaymentMethod.java @@ -0,0 +1,445 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.FedwireDetails; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * A Fedwire (domestic USD wire) payment method linked to your entity. + */ +@JsonPropertyOrder({ + FedwirePaymentMethod.JSON_PROPERTY_PAYMENT_METHOD_ID, + FedwirePaymentMethod.JSON_PROPERTY_ACTIVE, + FedwirePaymentMethod.JSON_PROPERTY_CREATED_AT, + FedwirePaymentMethod.JSON_PROPERTY_UPDATED_AT, + FedwirePaymentMethod.JSON_PROPERTY_PAYMENT_RAIL, + FedwirePaymentMethod.JSON_PROPERTY_FEDWIRE +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class FedwirePaymentMethod { + public static final String JSON_PROPERTY_PAYMENT_METHOD_ID = "paymentMethodId"; + @jakarta.annotation.Nonnull + private String paymentMethodId; + + public static final String JSON_PROPERTY_ACTIVE = "active"; + @jakarta.annotation.Nonnull + private Boolean active; + + public static final String JSON_PROPERTY_CREATED_AT = "createdAt"; + @jakarta.annotation.Nonnull + private OffsetDateTime createdAt; + + public static final String JSON_PROPERTY_UPDATED_AT = "updatedAt"; + @jakarta.annotation.Nonnull + private OffsetDateTime updatedAt; + + /** + * The payment rail for this payment method. + */ + public enum PaymentRailEnum { + FEDWIRE(String.valueOf("fedwire")); + + private String value; + + PaymentRailEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static PaymentRailEnum fromValue(String value) { + for (PaymentRailEnum b : PaymentRailEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + public static final String JSON_PROPERTY_PAYMENT_RAIL = "paymentRail"; + @jakarta.annotation.Nonnull + private PaymentRailEnum paymentRail; + + public static final String JSON_PROPERTY_FEDWIRE = "fedwire"; + @jakarta.annotation.Nonnull + private FedwireDetails fedwire; + + public FedwirePaymentMethod() { + } + + public FedwirePaymentMethod paymentMethodId(@jakarta.annotation.Nonnull String paymentMethodId) { + this.paymentMethodId = paymentMethodId; + return this; + } + + /** + * The ID of the Payment Method, which is a UUID prefixed by the string `paymentMethod_`. + * @return paymentMethodId + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_PAYMENT_METHOD_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getPaymentMethodId() { + return paymentMethodId; + } + + + @JsonProperty(JSON_PROPERTY_PAYMENT_METHOD_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setPaymentMethodId(@jakarta.annotation.Nonnull String paymentMethodId) { + this.paymentMethodId = paymentMethodId; + } + + + public FedwirePaymentMethod active(@jakarta.annotation.Nonnull Boolean active) { + this.active = active; + return this; + } + + /** + * Whether the payment method is active and can be used in transfers. A payment method may be inactive due to verification requirements or entity-level restrictions. + * @return active + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ACTIVE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public Boolean getActive() { + return active; + } + + + @JsonProperty(JSON_PROPERTY_ACTIVE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setActive(@jakarta.annotation.Nonnull Boolean active) { + this.active = active; + } + + + public FedwirePaymentMethod createdAt(@jakarta.annotation.Nonnull OffsetDateTime createdAt) { + this.createdAt = createdAt; + return this; + } + + /** + * The timestamp when the payment method was created. + * @return createdAt + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_CREATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public OffsetDateTime getCreatedAt() { + return createdAt; + } + + + @JsonProperty(JSON_PROPERTY_CREATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCreatedAt(@jakarta.annotation.Nonnull OffsetDateTime createdAt) { + this.createdAt = createdAt; + } + + + public FedwirePaymentMethod updatedAt(@jakarta.annotation.Nonnull OffsetDateTime updatedAt) { + this.updatedAt = updatedAt; + return this; + } + + /** + * The timestamp when the payment method was last updated. + * @return updatedAt + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_UPDATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public OffsetDateTime getUpdatedAt() { + return updatedAt; + } + + + @JsonProperty(JSON_PROPERTY_UPDATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUpdatedAt(@jakarta.annotation.Nonnull OffsetDateTime updatedAt) { + this.updatedAt = updatedAt; + } + + + public FedwirePaymentMethod paymentRail(@jakarta.annotation.Nonnull PaymentRailEnum paymentRail) { + this.paymentRail = paymentRail; + return this; + } + + /** + * The payment rail for this payment method. + * @return paymentRail + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_PAYMENT_RAIL) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public PaymentRailEnum getPaymentRail() { + return paymentRail; + } + + + @JsonProperty(JSON_PROPERTY_PAYMENT_RAIL) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setPaymentRail(@jakarta.annotation.Nonnull PaymentRailEnum paymentRail) { + this.paymentRail = paymentRail; + } + + + public FedwirePaymentMethod fedwire(@jakarta.annotation.Nonnull FedwireDetails fedwire) { + this.fedwire = fedwire; + return this; + } + + /** + * Fedwire (domestic USD wire) details. + * @return fedwire + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_FEDWIRE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public FedwireDetails getFedwire() { + return fedwire; + } + + + @JsonProperty(JSON_PROPERTY_FEDWIRE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setFedwire(@jakarta.annotation.Nonnull FedwireDetails fedwire) { + this.fedwire = fedwire; + } + + + /** + * Return true if this FedwirePaymentMethod object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FedwirePaymentMethod fedwirePaymentMethod = (FedwirePaymentMethod) o; + return Objects.equals(this.paymentMethodId, fedwirePaymentMethod.paymentMethodId) && + Objects.equals(this.active, fedwirePaymentMethod.active) && + Objects.equals(this.createdAt, fedwirePaymentMethod.createdAt) && + Objects.equals(this.updatedAt, fedwirePaymentMethod.updatedAt) && + Objects.equals(this.paymentRail, fedwirePaymentMethod.paymentRail) && + Objects.equals(this.fedwire, fedwirePaymentMethod.fedwire); + } + + @Override + public int hashCode() { + return Objects.hash(paymentMethodId, active, createdAt, updatedAt, paymentRail, fedwire); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FedwirePaymentMethod {\n"); + sb.append(" paymentMethodId: ").append(toIndentedString(paymentMethodId)).append("\n"); + sb.append(" active: ").append(toIndentedString(active)).append("\n"); + sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); + sb.append(" updatedAt: ").append(toIndentedString(updatedAt)).append("\n"); + sb.append(" paymentRail: ").append(toIndentedString(paymentRail)).append("\n"); + sb.append(" fedwire: ").append(toIndentedString(fedwire)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `paymentMethodId` to the URL query string + if (getPaymentMethodId() != null) { + joiner.add(String.format("%spaymentMethodId%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getPaymentMethodId()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `active` to the URL query string + if (getActive() != null) { + joiner.add(String.format("%sactive%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getActive()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `createdAt` to the URL query string + if (getCreatedAt() != null) { + joiner.add(String.format("%screatedAt%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getCreatedAt()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `updatedAt` to the URL query string + if (getUpdatedAt() != null) { + joiner.add(String.format("%supdatedAt%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getUpdatedAt()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `paymentRail` to the URL query string + if (getPaymentRail() != null) { + joiner.add(String.format("%spaymentRail%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getPaymentRail()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `fedwire` to the URL query string + if (getFedwire() != null) { + joiner.add(getFedwire().toUrlQueryString(prefix + "fedwire" + suffix)); + } + + return joiner.toString(); + } + + public static class Builder { + + private FedwirePaymentMethod instance; + + public Builder() { + this(new FedwirePaymentMethod()); + } + + protected Builder(FedwirePaymentMethod instance) { + this.instance = instance; + } + + public FedwirePaymentMethod.Builder paymentMethodId(String paymentMethodId) { + this.instance.paymentMethodId = paymentMethodId; + return this; + } + public FedwirePaymentMethod.Builder active(Boolean active) { + this.instance.active = active; + return this; + } + public FedwirePaymentMethod.Builder createdAt(OffsetDateTime createdAt) { + this.instance.createdAt = createdAt; + return this; + } + public FedwirePaymentMethod.Builder updatedAt(OffsetDateTime updatedAt) { + this.instance.updatedAt = updatedAt; + return this; + } + public FedwirePaymentMethod.Builder paymentRail(PaymentRailEnum paymentRail) { + this.instance.paymentRail = paymentRail; + return this; + } + public FedwirePaymentMethod.Builder fedwire(FedwireDetails fedwire) { + this.instance.fedwire = fedwire; + return this; + } + + + /** + * returns a built FedwirePaymentMethod instance. + * + * The builder is not reusable. + */ + public FedwirePaymentMethod build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static FedwirePaymentMethod.Builder builder() { + return new FedwirePaymentMethod.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public FedwirePaymentMethod.Builder toBuilder() { + return new FedwirePaymentMethod.Builder() + .paymentMethodId(getPaymentMethodId()) + .active(getActive()) + .createdAt(getCreatedAt()) + .updatedAt(getUpdatedAt()) + .paymentRail(getPaymentRail()) + .fedwire(getFedwire()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/ListBalances200Response.java b/java/src/main/java/com/coinbase/cdp/openapi/model/ListBalances200Response.java new file mode 100644 index 000000000..b8d08175b --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/ListBalances200Response.java @@ -0,0 +1,262 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.Balance; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * ListBalances200Response + */ +@JsonPropertyOrder({ + ListBalances200Response.JSON_PROPERTY_BALANCES, + ListBalances200Response.JSON_PROPERTY_NEXT_PAGE_TOKEN +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class ListBalances200Response { + public static final String JSON_PROPERTY_BALANCES = "balances"; + @jakarta.annotation.Nonnull + private List balances = new ArrayList<>(); + + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "nextPageToken"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public ListBalances200Response() { + } + + public ListBalances200Response balances(@jakarta.annotation.Nonnull List balances) { + this.balances = balances; + return this; + } + + public ListBalances200Response addBalancesItem(Balance balancesItem) { + if (this.balances == null) { + this.balances = new ArrayList<>(); + } + this.balances.add(balancesItem); + return this; + } + + /** + * The list of balances. + * @return balances + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_BALANCES) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public List getBalances() { + return balances; + } + + + @JsonProperty(JSON_PROPERTY_BALANCES) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBalances(@jakarta.annotation.Nonnull List balances) { + this.balances = balances; + } + + + public ListBalances200Response nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + return this; + } + + /** + * The token for the next page of items, if any. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_NEXT_PAGE_TOKEN) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(JSON_PROPERTY_NEXT_PAGE_TOKEN) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + /** + * Return true if this listBalances_200_response object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ListBalances200Response listBalances200Response = (ListBalances200Response) o; + return Objects.equals(this.balances, listBalances200Response.balances) && + Objects.equals(this.nextPageToken, listBalances200Response.nextPageToken); + } + + @Override + public int hashCode() { + return Objects.hash(balances, nextPageToken); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ListBalances200Response {\n"); + sb.append(" balances: ").append(toIndentedString(balances)).append("\n"); + sb.append(" nextPageToken: ").append(toIndentedString(nextPageToken)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `balances` to the URL query string + if (getBalances() != null) { + for (int i = 0; i < getBalances().size(); i++) { + if (getBalances().get(i) != null) { + joiner.add(getBalances().get(i).toUrlQueryString(String.format("%sbalances%s%s", prefix, suffix, + "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, i, containerSuffix)))); + } + } + } + + // add `nextPageToken` to the URL query string + if (getNextPageToken() != null) { + joiner.add(String.format("%snextPageToken%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getNextPageToken()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private ListBalances200Response instance; + + public Builder() { + this(new ListBalances200Response()); + } + + protected Builder(ListBalances200Response instance) { + this.instance = instance; + } + + public ListBalances200Response.Builder balances(List balances) { + this.instance.balances = balances; + return this; + } + public ListBalances200Response.Builder nextPageToken(String nextPageToken) { + this.instance.nextPageToken = nextPageToken; + return this; + } + + + /** + * returns a built ListBalances200Response instance. + * + * The builder is not reusable. + */ + public ListBalances200Response build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static ListBalances200Response.Builder builder() { + return new ListBalances200Response.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public ListBalances200Response.Builder toBuilder() { + return new ListBalances200Response.Builder() + .balances(getBalances()) + .nextPageToken(getNextPageToken()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/ListDepositDestinations200Response.java b/java/src/main/java/com/coinbase/cdp/openapi/model/ListDepositDestinations200Response.java new file mode 100644 index 000000000..7e5ae0d70 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/ListDepositDestinations200Response.java @@ -0,0 +1,262 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.DepositDestination; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * ListDepositDestinations200Response + */ +@JsonPropertyOrder({ + ListDepositDestinations200Response.JSON_PROPERTY_NEXT_PAGE_TOKEN, + ListDepositDestinations200Response.JSON_PROPERTY_DEPOSIT_DESTINATIONS +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class ListDepositDestinations200Response { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "nextPageToken"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_DEPOSIT_DESTINATIONS = "depositDestinations"; + @jakarta.annotation.Nonnull + private List depositDestinations = new ArrayList<>(); + + public ListDepositDestinations200Response() { + } + + public ListDepositDestinations200Response nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + return this; + } + + /** + * The token for the next page of items, if any. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_NEXT_PAGE_TOKEN) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(JSON_PROPERTY_NEXT_PAGE_TOKEN) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public ListDepositDestinations200Response depositDestinations(@jakarta.annotation.Nonnull List depositDestinations) { + this.depositDestinations = depositDestinations; + return this; + } + + public ListDepositDestinations200Response addDepositDestinationsItem(DepositDestination depositDestinationsItem) { + if (this.depositDestinations == null) { + this.depositDestinations = new ArrayList<>(); + } + this.depositDestinations.add(depositDestinationsItem); + return this; + } + + /** + * The list of deposit destinations. + * @return depositDestinations + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_DEPOSIT_DESTINATIONS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public List getDepositDestinations() { + return depositDestinations; + } + + + @JsonProperty(JSON_PROPERTY_DEPOSIT_DESTINATIONS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDepositDestinations(@jakarta.annotation.Nonnull List depositDestinations) { + this.depositDestinations = depositDestinations; + } + + + /** + * Return true if this listDepositDestinations_200_response object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ListDepositDestinations200Response listDepositDestinations200Response = (ListDepositDestinations200Response) o; + return Objects.equals(this.nextPageToken, listDepositDestinations200Response.nextPageToken) && + Objects.equals(this.depositDestinations, listDepositDestinations200Response.depositDestinations); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, depositDestinations); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ListDepositDestinations200Response {\n"); + sb.append(" nextPageToken: ").append(toIndentedString(nextPageToken)).append("\n"); + sb.append(" depositDestinations: ").append(toIndentedString(depositDestinations)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `nextPageToken` to the URL query string + if (getNextPageToken() != null) { + joiner.add(String.format("%snextPageToken%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getNextPageToken()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `depositDestinations` to the URL query string + if (getDepositDestinations() != null) { + for (int i = 0; i < getDepositDestinations().size(); i++) { + if (getDepositDestinations().get(i) != null) { + joiner.add(getDepositDestinations().get(i).toUrlQueryString(String.format("%sdepositDestinations%s%s", prefix, suffix, + "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, i, containerSuffix)))); + } + } + } + + return joiner.toString(); + } + + public static class Builder { + + private ListDepositDestinations200Response instance; + + public Builder() { + this(new ListDepositDestinations200Response()); + } + + protected Builder(ListDepositDestinations200Response instance) { + this.instance = instance; + } + + public ListDepositDestinations200Response.Builder nextPageToken(String nextPageToken) { + this.instance.nextPageToken = nextPageToken; + return this; + } + public ListDepositDestinations200Response.Builder depositDestinations(List depositDestinations) { + this.instance.depositDestinations = depositDestinations; + return this; + } + + + /** + * returns a built ListDepositDestinations200Response instance. + * + * The builder is not reusable. + */ + public ListDepositDestinations200Response build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static ListDepositDestinations200Response.Builder builder() { + return new ListDepositDestinations200Response.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public ListDepositDestinations200Response.Builder toBuilder() { + return new ListDepositDestinations200Response.Builder() + .nextPageToken(getNextPageToken()) + .depositDestinations(getDepositDestinations()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/ListFoundationAccounts200Response.java b/java/src/main/java/com/coinbase/cdp/openapi/model/ListFoundationAccounts200Response.java new file mode 100644 index 000000000..9366040c9 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/ListFoundationAccounts200Response.java @@ -0,0 +1,262 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.Account; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * ListFoundationAccounts200Response + */ +@JsonPropertyOrder({ + ListFoundationAccounts200Response.JSON_PROPERTY_NEXT_PAGE_TOKEN, + ListFoundationAccounts200Response.JSON_PROPERTY_ACCOUNTS +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class ListFoundationAccounts200Response { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "nextPageToken"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_ACCOUNTS = "accounts"; + @jakarta.annotation.Nonnull + private List accounts = new ArrayList<>(); + + public ListFoundationAccounts200Response() { + } + + public ListFoundationAccounts200Response nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + return this; + } + + /** + * The token for the next page of items, if any. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_NEXT_PAGE_TOKEN) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(JSON_PROPERTY_NEXT_PAGE_TOKEN) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public ListFoundationAccounts200Response accounts(@jakarta.annotation.Nonnull List accounts) { + this.accounts = accounts; + return this; + } + + public ListFoundationAccounts200Response addAccountsItem(Account accountsItem) { + if (this.accounts == null) { + this.accounts = new ArrayList<>(); + } + this.accounts.add(accountsItem); + return this; + } + + /** + * The list of accounts. + * @return accounts + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ACCOUNTS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public List getAccounts() { + return accounts; + } + + + @JsonProperty(JSON_PROPERTY_ACCOUNTS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAccounts(@jakarta.annotation.Nonnull List accounts) { + this.accounts = accounts; + } + + + /** + * Return true if this listFoundationAccounts_200_response object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ListFoundationAccounts200Response listFoundationAccounts200Response = (ListFoundationAccounts200Response) o; + return Objects.equals(this.nextPageToken, listFoundationAccounts200Response.nextPageToken) && + Objects.equals(this.accounts, listFoundationAccounts200Response.accounts); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, accounts); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ListFoundationAccounts200Response {\n"); + sb.append(" nextPageToken: ").append(toIndentedString(nextPageToken)).append("\n"); + sb.append(" accounts: ").append(toIndentedString(accounts)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `nextPageToken` to the URL query string + if (getNextPageToken() != null) { + joiner.add(String.format("%snextPageToken%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getNextPageToken()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `accounts` to the URL query string + if (getAccounts() != null) { + for (int i = 0; i < getAccounts().size(); i++) { + if (getAccounts().get(i) != null) { + joiner.add(getAccounts().get(i).toUrlQueryString(String.format("%saccounts%s%s", prefix, suffix, + "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, i, containerSuffix)))); + } + } + } + + return joiner.toString(); + } + + public static class Builder { + + private ListFoundationAccounts200Response instance; + + public Builder() { + this(new ListFoundationAccounts200Response()); + } + + protected Builder(ListFoundationAccounts200Response instance) { + this.instance = instance; + } + + public ListFoundationAccounts200Response.Builder nextPageToken(String nextPageToken) { + this.instance.nextPageToken = nextPageToken; + return this; + } + public ListFoundationAccounts200Response.Builder accounts(List accounts) { + this.instance.accounts = accounts; + return this; + } + + + /** + * returns a built ListFoundationAccounts200Response instance. + * + * The builder is not reusable. + */ + public ListFoundationAccounts200Response build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static ListFoundationAccounts200Response.Builder builder() { + return new ListFoundationAccounts200Response.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public ListFoundationAccounts200Response.Builder toBuilder() { + return new ListFoundationAccounts200Response.Builder() + .nextPageToken(getNextPageToken()) + .accounts(getAccounts()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/ListPaymentMethods200Response.java b/java/src/main/java/com/coinbase/cdp/openapi/model/ListPaymentMethods200Response.java new file mode 100644 index 000000000..0e0f1ec12 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/ListPaymentMethods200Response.java @@ -0,0 +1,262 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.PaymentMethodsPaymentMethod; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * ListPaymentMethods200Response + */ +@JsonPropertyOrder({ + ListPaymentMethods200Response.JSON_PROPERTY_NEXT_PAGE_TOKEN, + ListPaymentMethods200Response.JSON_PROPERTY_PAYMENT_METHODS +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class ListPaymentMethods200Response { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "nextPageToken"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_PAYMENT_METHODS = "paymentMethods"; + @jakarta.annotation.Nonnull + private List paymentMethods = new ArrayList<>(); + + public ListPaymentMethods200Response() { + } + + public ListPaymentMethods200Response nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + return this; + } + + /** + * The token for the next page of items, if any. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_NEXT_PAGE_TOKEN) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(JSON_PROPERTY_NEXT_PAGE_TOKEN) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public ListPaymentMethods200Response paymentMethods(@jakarta.annotation.Nonnull List paymentMethods) { + this.paymentMethods = paymentMethods; + return this; + } + + public ListPaymentMethods200Response addPaymentMethodsItem(PaymentMethodsPaymentMethod paymentMethodsItem) { + if (this.paymentMethods == null) { + this.paymentMethods = new ArrayList<>(); + } + this.paymentMethods.add(paymentMethodsItem); + return this; + } + + /** + * The list of payment methods. + * @return paymentMethods + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_PAYMENT_METHODS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public List getPaymentMethods() { + return paymentMethods; + } + + + @JsonProperty(JSON_PROPERTY_PAYMENT_METHODS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setPaymentMethods(@jakarta.annotation.Nonnull List paymentMethods) { + this.paymentMethods = paymentMethods; + } + + + /** + * Return true if this listPaymentMethods_200_response object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ListPaymentMethods200Response listPaymentMethods200Response = (ListPaymentMethods200Response) o; + return Objects.equals(this.nextPageToken, listPaymentMethods200Response.nextPageToken) && + Objects.equals(this.paymentMethods, listPaymentMethods200Response.paymentMethods); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, paymentMethods); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ListPaymentMethods200Response {\n"); + sb.append(" nextPageToken: ").append(toIndentedString(nextPageToken)).append("\n"); + sb.append(" paymentMethods: ").append(toIndentedString(paymentMethods)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `nextPageToken` to the URL query string + if (getNextPageToken() != null) { + joiner.add(String.format("%snextPageToken%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getNextPageToken()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `paymentMethods` to the URL query string + if (getPaymentMethods() != null) { + for (int i = 0; i < getPaymentMethods().size(); i++) { + if (getPaymentMethods().get(i) != null) { + joiner.add(getPaymentMethods().get(i).toUrlQueryString(String.format("%spaymentMethods%s%s", prefix, suffix, + "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, i, containerSuffix)))); + } + } + } + + return joiner.toString(); + } + + public static class Builder { + + private ListPaymentMethods200Response instance; + + public Builder() { + this(new ListPaymentMethods200Response()); + } + + protected Builder(ListPaymentMethods200Response instance) { + this.instance = instance; + } + + public ListPaymentMethods200Response.Builder nextPageToken(String nextPageToken) { + this.instance.nextPageToken = nextPageToken; + return this; + } + public ListPaymentMethods200Response.Builder paymentMethods(List paymentMethods) { + this.instance.paymentMethods = paymentMethods; + return this; + } + + + /** + * returns a built ListPaymentMethods200Response instance. + * + * The builder is not reusable. + */ + public ListPaymentMethods200Response build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static ListPaymentMethods200Response.Builder builder() { + return new ListPaymentMethods200Response.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public ListPaymentMethods200Response.Builder toBuilder() { + return new ListPaymentMethods200Response.Builder() + .nextPageToken(getNextPageToken()) + .paymentMethods(getPaymentMethods()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/ListTransfers200Response.java b/java/src/main/java/com/coinbase/cdp/openapi/model/ListTransfers200Response.java new file mode 100644 index 000000000..bdaaaa21f --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/ListTransfers200Response.java @@ -0,0 +1,262 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.Transfer; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * ListTransfers200Response + */ +@JsonPropertyOrder({ + ListTransfers200Response.JSON_PROPERTY_NEXT_PAGE_TOKEN, + ListTransfers200Response.JSON_PROPERTY_TRANSFERS +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class ListTransfers200Response { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "nextPageToken"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_TRANSFERS = "transfers"; + @jakarta.annotation.Nonnull + private List transfers = new ArrayList<>(); + + public ListTransfers200Response() { + } + + public ListTransfers200Response nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + return this; + } + + /** + * The token for the next page of items, if any. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_NEXT_PAGE_TOKEN) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(JSON_PROPERTY_NEXT_PAGE_TOKEN) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public ListTransfers200Response transfers(@jakarta.annotation.Nonnull List transfers) { + this.transfers = transfers; + return this; + } + + public ListTransfers200Response addTransfersItem(Transfer transfersItem) { + if (this.transfers == null) { + this.transfers = new ArrayList<>(); + } + this.transfers.add(transfersItem); + return this; + } + + /** + * The list of transfers. + * @return transfers + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_TRANSFERS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public List getTransfers() { + return transfers; + } + + + @JsonProperty(JSON_PROPERTY_TRANSFERS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTransfers(@jakarta.annotation.Nonnull List transfers) { + this.transfers = transfers; + } + + + /** + * Return true if this listTransfers_200_response object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ListTransfers200Response listTransfers200Response = (ListTransfers200Response) o; + return Objects.equals(this.nextPageToken, listTransfers200Response.nextPageToken) && + Objects.equals(this.transfers, listTransfers200Response.transfers); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, transfers); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ListTransfers200Response {\n"); + sb.append(" nextPageToken: ").append(toIndentedString(nextPageToken)).append("\n"); + sb.append(" transfers: ").append(toIndentedString(transfers)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `nextPageToken` to the URL query string + if (getNextPageToken() != null) { + joiner.add(String.format("%snextPageToken%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getNextPageToken()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `transfers` to the URL query string + if (getTransfers() != null) { + for (int i = 0; i < getTransfers().size(); i++) { + if (getTransfers().get(i) != null) { + joiner.add(getTransfers().get(i).toUrlQueryString(String.format("%stransfers%s%s", prefix, suffix, + "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, i, containerSuffix)))); + } + } + } + + return joiner.toString(); + } + + public static class Builder { + + private ListTransfers200Response instance; + + public Builder() { + this(new ListTransfers200Response()); + } + + protected Builder(ListTransfers200Response instance) { + this.instance = instance; + } + + public ListTransfers200Response.Builder nextPageToken(String nextPageToken) { + this.instance.nextPageToken = nextPageToken; + return this; + } + public ListTransfers200Response.Builder transfers(List transfers) { + this.instance.transfers = transfers; + return this; + } + + + /** + * returns a built ListTransfers200Response instance. + * + * The builder is not reusable. + */ + public ListTransfers200Response build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static ListTransfers200Response.Builder builder() { + return new ListTransfers200Response.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public ListTransfers200Response.Builder toBuilder() { + return new ListTransfers200Response.Builder() + .nextPageToken(getNextPageToken()) + .transfers(getTransfers()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/Network.java b/java/src/main/java/com/coinbase/cdp/openapi/model/Network.java new file mode 100644 index 000000000..e803f95a7 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/Network.java @@ -0,0 +1,94 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * The blockchain network for the payment. Supported networks depend on the account type. See [API and Network Support](https://docs.cdp.coinbase.com/api-reference/payment-apis/supported-networks-assets#by-asset-and-network) for more details. + */ +public enum Network { + + BASE("base"), + + ETHEREUM("ethereum"), + + SOLANA("solana"), + + APTOS("aptos"), + + ARBITRUM("arbitrum"), + + ARBITRUM_SEPOLIA("arbitrum-sepolia"), + + OPTIMISM("optimism"), + + POLYGON("polygon"), + + WORLD("world"), + + WORLD_SEPOLIA("world-sepolia"); + + private String value; + + Network(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static Network fromValue(String value) { + for (Network b : Network.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + if (prefix == null) { + prefix = ""; + } + + return String.format("%s=%s", prefix, this.toString()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/OnchainAddress.java b/java/src/main/java/com/coinbase/cdp/openapi/model/OnchainAddress.java new file mode 100644 index 000000000..e8efee141 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/OnchainAddress.java @@ -0,0 +1,329 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.Network; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * The target of the payment is an onchain address. + */ +@JsonPropertyOrder({ + OnchainAddress.JSON_PROPERTY_ADDRESS, + OnchainAddress.JSON_PROPERTY_NETWORK, + OnchainAddress.JSON_PROPERTY_DESTINATION_TAG, + OnchainAddress.JSON_PROPERTY_ASSET +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class OnchainAddress { + public static final String JSON_PROPERTY_ADDRESS = "address"; + @jakarta.annotation.Nonnull + private String address; + + public static final String JSON_PROPERTY_NETWORK = "network"; + @jakarta.annotation.Nonnull + private Network network; + + public static final String JSON_PROPERTY_DESTINATION_TAG = "destinationTag"; + @jakarta.annotation.Nullable + private String destinationTag; + + public static final String JSON_PROPERTY_ASSET = "asset"; + @jakarta.annotation.Nonnull + private String asset; + + public OnchainAddress() { + } + + public OnchainAddress address(@jakarta.annotation.Nonnull String address) { + this.address = address; + return this; + } + + /** + * The onchain crypto address of the recipient. Examples: - EVM address: 0xabc1234567890abcdef1234567890abcdef123456 - Solana address: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT - XRP address: rhccc5p23aKiCGFcEqqnjEfLRZ6xEvfy3s + * @return address + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ADDRESS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAddress() { + return address; + } + + + @JsonProperty(JSON_PROPERTY_ADDRESS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAddress(@jakarta.annotation.Nonnull String address) { + this.address = address; + } + + + public OnchainAddress network(@jakarta.annotation.Nonnull Network network) { + this.network = network; + return this; + } + + /** + * Get network + * @return network + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_NETWORK) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public Network getNetwork() { + return network; + } + + + @JsonProperty(JSON_PROPERTY_NETWORK) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNetwork(@jakarta.annotation.Nonnull Network network) { + this.network = network; + } + + + public OnchainAddress destinationTag(@jakarta.annotation.Nullable String destinationTag) { + this.destinationTag = destinationTag; + return this; + } + + /** + * The destination tag of the onchain address. Destination tags are used by certain networks (primarily XRP/Ripple) to identify specific recipients when multiple users share a single address. The tag ensures funds are credited to the correct account within the shared address. Examples by network: - XRP/Ripple: Numeric values like \"1234567890\" or \"123456\" - Stellar (XLM): Memos which can be text, ID, or hash format Note: Most networks (Ethereum, Bitcoin, Solana) do not use destination tags. + * @return destinationTag + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_DESTINATION_TAG) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getDestinationTag() { + return destinationTag; + } + + + @JsonProperty(JSON_PROPERTY_DESTINATION_TAG) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setDestinationTag(@jakarta.annotation.Nullable String destinationTag) { + this.destinationTag = destinationTag; + } + + + public OnchainAddress asset(@jakarta.annotation.Nonnull String asset) { + this.asset = asset; + return this; + } + + /** + * Asset symbol of the payment received by the recipient. + * @return asset + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAsset() { + return asset; + } + + + @JsonProperty(JSON_PROPERTY_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAsset(@jakarta.annotation.Nonnull String asset) { + this.asset = asset; + } + + + /** + * Return true if this OnchainAddress object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OnchainAddress onchainAddress = (OnchainAddress) o; + return Objects.equals(this.address, onchainAddress.address) && + Objects.equals(this.network, onchainAddress.network) && + Objects.equals(this.destinationTag, onchainAddress.destinationTag) && + Objects.equals(this.asset, onchainAddress.asset); + } + + @Override + public int hashCode() { + return Objects.hash(address, network, destinationTag, asset); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OnchainAddress {\n"); + sb.append(" address: ").append(toIndentedString(address)).append("\n"); + sb.append(" network: ").append(toIndentedString(network)).append("\n"); + sb.append(" destinationTag: ").append(toIndentedString(destinationTag)).append("\n"); + sb.append(" asset: ").append(toIndentedString(asset)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `address` to the URL query string + if (getAddress() != null) { + joiner.add(String.format("%saddress%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAddress()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `network` to the URL query string + if (getNetwork() != null) { + joiner.add(String.format("%snetwork%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getNetwork()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `destinationTag` to the URL query string + if (getDestinationTag() != null) { + joiner.add(String.format("%sdestinationTag%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getDestinationTag()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `asset` to the URL query string + if (getAsset() != null) { + joiner.add(String.format("%sasset%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAsset()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private OnchainAddress instance; + + public Builder() { + this(new OnchainAddress()); + } + + protected Builder(OnchainAddress instance) { + this.instance = instance; + } + + public OnchainAddress.Builder address(String address) { + this.instance.address = address; + return this; + } + public OnchainAddress.Builder network(Network network) { + this.instance.network = network; + return this; + } + public OnchainAddress.Builder destinationTag(String destinationTag) { + this.instance.destinationTag = destinationTag; + return this; + } + public OnchainAddress.Builder asset(String asset) { + this.instance.asset = asset; + return this; + } + + + /** + * returns a built OnchainAddress instance. + * + * The builder is not reusable. + */ + public OnchainAddress build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static OnchainAddress.Builder builder() { + return new OnchainAddress.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public OnchainAddress.Builder toBuilder() { + return new OnchainAddress.Builder() + .address(getAddress()) + .network(getNetwork()) + .destinationTag(getDestinationTag()) + .asset(getAsset()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/OnchainDataResult.java b/java/src/main/java/com/coinbase/cdp/openapi/model/OnchainDataResult.java index 5e347de26..e40d15487 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/model/OnchainDataResult.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/OnchainDataResult.java @@ -29,7 +29,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.Map; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @@ -46,7 +45,7 @@ public class OnchainDataResult { public static final String JSON_PROPERTY_RESULT = "result"; @jakarta.annotation.Nullable - private List> result = new ArrayList<>(); + private List result = new ArrayList<>(); public static final String JSON_PROPERTY_SCHEMA = "schema"; @jakarta.annotation.Nullable @@ -59,12 +58,12 @@ public class OnchainDataResult { public OnchainDataResult() { } - public OnchainDataResult result(@jakarta.annotation.Nullable List> result) { + public OnchainDataResult result(@jakarta.annotation.Nullable List result) { this.result = result; return this; } - public OnchainDataResult addResultItem(Map resultItem) { + public OnchainDataResult addResultItem(Object resultItem) { if (this.result == null) { this.result = new ArrayList<>(); } @@ -79,14 +78,14 @@ public OnchainDataResult addResultItem(Map resultItem) { @jakarta.annotation.Nullable @JsonProperty(JSON_PROPERTY_RESULT) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public List> getResult() { + public List getResult() { return result; } @JsonProperty(JSON_PROPERTY_RESULT) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setResult(@jakarta.annotation.Nullable List> result) { + public void setResult(@jakarta.annotation.Nullable List result) { this.result = result; } @@ -249,7 +248,7 @@ protected Builder(OnchainDataResult instance) { this.instance = instance; } - public OnchainDataResult.Builder result(List> result) { + public OnchainDataResult.Builder result(List result) { this.instance.result = result; return this; } diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/OriginatingBankAccountUS.java b/java/src/main/java/com/coinbase/cdp/openapi/model/OriginatingBankAccountUS.java new file mode 100644 index 000000000..06c0f31c3 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/OriginatingBankAccountUS.java @@ -0,0 +1,287 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * The originating US bank account details for the transfer source. Present when funds were deposited from an external bank account into a deposit destination. Only the last 4 digits of the account number are exposed. + */ +@JsonPropertyOrder({ + OriginatingBankAccountUS.JSON_PROPERTY_BANK_NAME, + OriginatingBankAccountUS.JSON_PROPERTY_ACCOUNT_LAST4, + OriginatingBankAccountUS.JSON_PROPERTY_CURRENCY +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class OriginatingBankAccountUS { + public static final String JSON_PROPERTY_BANK_NAME = "bankName"; + @jakarta.annotation.Nonnull + private String bankName; + + public static final String JSON_PROPERTY_ACCOUNT_LAST4 = "accountLast4"; + @jakarta.annotation.Nonnull + private String accountLast4; + + public static final String JSON_PROPERTY_CURRENCY = "currency"; + @jakarta.annotation.Nonnull + private String currency; + + public OriginatingBankAccountUS() { + } + + public OriginatingBankAccountUS bankName(@jakarta.annotation.Nonnull String bankName) { + this.bankName = bankName; + return this; + } + + /** + * The name of the bank that originated the deposit. + * @return bankName + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_BANK_NAME) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getBankName() { + return bankName; + } + + + @JsonProperty(JSON_PROPERTY_BANK_NAME) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBankName(@jakarta.annotation.Nonnull String bankName) { + this.bankName = bankName; + } + + + public OriginatingBankAccountUS accountLast4(@jakarta.annotation.Nonnull String accountLast4) { + this.accountLast4 = accountLast4; + return this; + } + + /** + * The last 4 digits of the originating bank account number. + * @return accountLast4 + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ACCOUNT_LAST4) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAccountLast4() { + return accountLast4; + } + + + @JsonProperty(JSON_PROPERTY_ACCOUNT_LAST4) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAccountLast4(@jakarta.annotation.Nonnull String accountLast4) { + this.accountLast4 = accountLast4; + } + + + public OriginatingBankAccountUS currency(@jakarta.annotation.Nonnull String currency) { + this.currency = currency; + return this; + } + + /** + * The fiat currency of the deposit (e.g., `usd`). + * @return currency + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_CURRENCY) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getCurrency() { + return currency; + } + + + @JsonProperty(JSON_PROPERTY_CURRENCY) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCurrency(@jakarta.annotation.Nonnull String currency) { + this.currency = currency; + } + + + /** + * Return true if this OriginatingBankAccountUS object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OriginatingBankAccountUS originatingBankAccountUS = (OriginatingBankAccountUS) o; + return Objects.equals(this.bankName, originatingBankAccountUS.bankName) && + Objects.equals(this.accountLast4, originatingBankAccountUS.accountLast4) && + Objects.equals(this.currency, originatingBankAccountUS.currency); + } + + @Override + public int hashCode() { + return Objects.hash(bankName, accountLast4, currency); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OriginatingBankAccountUS {\n"); + sb.append(" bankName: ").append(toIndentedString(bankName)).append("\n"); + sb.append(" accountLast4: ").append(toIndentedString(accountLast4)).append("\n"); + sb.append(" currency: ").append(toIndentedString(currency)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `bankName` to the URL query string + if (getBankName() != null) { + joiner.add(String.format("%sbankName%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getBankName()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `accountLast4` to the URL query string + if (getAccountLast4() != null) { + joiner.add(String.format("%saccountLast4%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAccountLast4()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `currency` to the URL query string + if (getCurrency() != null) { + joiner.add(String.format("%scurrency%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getCurrency()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private OriginatingBankAccountUS instance; + + public Builder() { + this(new OriginatingBankAccountUS()); + } + + protected Builder(OriginatingBankAccountUS instance) { + this.instance = instance; + } + + public OriginatingBankAccountUS.Builder bankName(String bankName) { + this.instance.bankName = bankName; + return this; + } + public OriginatingBankAccountUS.Builder accountLast4(String accountLast4) { + this.instance.accountLast4 = accountLast4; + return this; + } + public OriginatingBankAccountUS.Builder currency(String currency) { + this.instance.currency = currency; + return this; + } + + + /** + * returns a built OriginatingBankAccountUS instance. + * + * The builder is not reusable. + */ + public OriginatingBankAccountUS build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static OriginatingBankAccountUS.Builder builder() { + return new OriginatingBankAccountUS.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public OriginatingBankAccountUS.Builder toBuilder() { + return new OriginatingBankAccountUS.Builder() + .bankName(getBankName()) + .accountLast4(getAccountLast4()) + .currency(getCurrency()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/PaymentMethod.java b/java/src/main/java/com/coinbase/cdp/openapi/model/PaymentMethod.java new file mode 100644 index 000000000..fb4cfaf08 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/PaymentMethod.java @@ -0,0 +1,246 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * The Payment Method specific details for the transfer. + */ +@JsonPropertyOrder({ + PaymentMethod.JSON_PROPERTY_PAYMENT_METHOD_ID, + PaymentMethod.JSON_PROPERTY_ASSET +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class PaymentMethod { + public static final String JSON_PROPERTY_PAYMENT_METHOD_ID = "paymentMethodId"; + @jakarta.annotation.Nonnull + private String paymentMethodId; + + public static final String JSON_PROPERTY_ASSET = "asset"; + @jakarta.annotation.Nonnull + private String asset; + + public PaymentMethod() { + } + + public PaymentMethod paymentMethodId(@jakarta.annotation.Nonnull String paymentMethodId) { + this.paymentMethodId = paymentMethodId; + return this; + } + + /** + * The ID of the Payment Method. + * @return paymentMethodId + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_PAYMENT_METHOD_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getPaymentMethodId() { + return paymentMethodId; + } + + + @JsonProperty(JSON_PROPERTY_PAYMENT_METHOD_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setPaymentMethodId(@jakarta.annotation.Nonnull String paymentMethodId) { + this.paymentMethodId = paymentMethodId; + } + + + public PaymentMethod asset(@jakarta.annotation.Nonnull String asset) { + this.asset = asset; + return this; + } + + /** + * The symbol of the asset (e.g., eth, usd, usdc, usdt). + * @return asset + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAsset() { + return asset; + } + + + @JsonProperty(JSON_PROPERTY_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAsset(@jakarta.annotation.Nonnull String asset) { + this.asset = asset; + } + + + /** + * Return true if this PaymentMethod object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + PaymentMethod paymentMethod = (PaymentMethod) o; + return Objects.equals(this.paymentMethodId, paymentMethod.paymentMethodId) && + Objects.equals(this.asset, paymentMethod.asset); + } + + @Override + public int hashCode() { + return Objects.hash(paymentMethodId, asset); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class PaymentMethod {\n"); + sb.append(" paymentMethodId: ").append(toIndentedString(paymentMethodId)).append("\n"); + sb.append(" asset: ").append(toIndentedString(asset)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `paymentMethodId` to the URL query string + if (getPaymentMethodId() != null) { + joiner.add(String.format("%spaymentMethodId%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getPaymentMethodId()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `asset` to the URL query string + if (getAsset() != null) { + joiner.add(String.format("%sasset%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAsset()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private PaymentMethod instance; + + public Builder() { + this(new PaymentMethod()); + } + + protected Builder(PaymentMethod instance) { + this.instance = instance; + } + + public PaymentMethod.Builder paymentMethodId(String paymentMethodId) { + this.instance.paymentMethodId = paymentMethodId; + return this; + } + public PaymentMethod.Builder asset(String asset) { + this.instance.asset = asset; + return this; + } + + + /** + * returns a built PaymentMethod instance. + * + * The builder is not reusable. + */ + public PaymentMethod build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static PaymentMethod.Builder builder() { + return new PaymentMethod.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public PaymentMethod.Builder toBuilder() { + return new PaymentMethod.Builder() + .paymentMethodId(getPaymentMethodId()) + .asset(getAsset()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/PaymentMethodBase.java b/java/src/main/java/com/coinbase/cdp/openapi/model/PaymentMethodBase.java new file mode 100644 index 000000000..e3026671a --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/PaymentMethodBase.java @@ -0,0 +1,329 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * Common properties shared by all payment method types. + */ +@JsonPropertyOrder({ + PaymentMethodBase.JSON_PROPERTY_PAYMENT_METHOD_ID, + PaymentMethodBase.JSON_PROPERTY_ACTIVE, + PaymentMethodBase.JSON_PROPERTY_CREATED_AT, + PaymentMethodBase.JSON_PROPERTY_UPDATED_AT +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class PaymentMethodBase { + public static final String JSON_PROPERTY_PAYMENT_METHOD_ID = "paymentMethodId"; + @jakarta.annotation.Nonnull + private String paymentMethodId; + + public static final String JSON_PROPERTY_ACTIVE = "active"; + @jakarta.annotation.Nonnull + private Boolean active; + + public static final String JSON_PROPERTY_CREATED_AT = "createdAt"; + @jakarta.annotation.Nonnull + private OffsetDateTime createdAt; + + public static final String JSON_PROPERTY_UPDATED_AT = "updatedAt"; + @jakarta.annotation.Nonnull + private OffsetDateTime updatedAt; + + public PaymentMethodBase() { + } + + public PaymentMethodBase paymentMethodId(@jakarta.annotation.Nonnull String paymentMethodId) { + this.paymentMethodId = paymentMethodId; + return this; + } + + /** + * The ID of the Payment Method, which is a UUID prefixed by the string `paymentMethod_`. + * @return paymentMethodId + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_PAYMENT_METHOD_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getPaymentMethodId() { + return paymentMethodId; + } + + + @JsonProperty(JSON_PROPERTY_PAYMENT_METHOD_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setPaymentMethodId(@jakarta.annotation.Nonnull String paymentMethodId) { + this.paymentMethodId = paymentMethodId; + } + + + public PaymentMethodBase active(@jakarta.annotation.Nonnull Boolean active) { + this.active = active; + return this; + } + + /** + * Whether the payment method is active and can be used in transfers. A payment method may be inactive due to verification requirements or entity-level restrictions. + * @return active + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ACTIVE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public Boolean getActive() { + return active; + } + + + @JsonProperty(JSON_PROPERTY_ACTIVE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setActive(@jakarta.annotation.Nonnull Boolean active) { + this.active = active; + } + + + public PaymentMethodBase createdAt(@jakarta.annotation.Nonnull OffsetDateTime createdAt) { + this.createdAt = createdAt; + return this; + } + + /** + * The timestamp when the payment method was created. + * @return createdAt + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_CREATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public OffsetDateTime getCreatedAt() { + return createdAt; + } + + + @JsonProperty(JSON_PROPERTY_CREATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCreatedAt(@jakarta.annotation.Nonnull OffsetDateTime createdAt) { + this.createdAt = createdAt; + } + + + public PaymentMethodBase updatedAt(@jakarta.annotation.Nonnull OffsetDateTime updatedAt) { + this.updatedAt = updatedAt; + return this; + } + + /** + * The timestamp when the payment method was last updated. + * @return updatedAt + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_UPDATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public OffsetDateTime getUpdatedAt() { + return updatedAt; + } + + + @JsonProperty(JSON_PROPERTY_UPDATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUpdatedAt(@jakarta.annotation.Nonnull OffsetDateTime updatedAt) { + this.updatedAt = updatedAt; + } + + + /** + * Return true if this PaymentMethodBase object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + PaymentMethodBase paymentMethodBase = (PaymentMethodBase) o; + return Objects.equals(this.paymentMethodId, paymentMethodBase.paymentMethodId) && + Objects.equals(this.active, paymentMethodBase.active) && + Objects.equals(this.createdAt, paymentMethodBase.createdAt) && + Objects.equals(this.updatedAt, paymentMethodBase.updatedAt); + } + + @Override + public int hashCode() { + return Objects.hash(paymentMethodId, active, createdAt, updatedAt); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class PaymentMethodBase {\n"); + sb.append(" paymentMethodId: ").append(toIndentedString(paymentMethodId)).append("\n"); + sb.append(" active: ").append(toIndentedString(active)).append("\n"); + sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); + sb.append(" updatedAt: ").append(toIndentedString(updatedAt)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `paymentMethodId` to the URL query string + if (getPaymentMethodId() != null) { + joiner.add(String.format("%spaymentMethodId%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getPaymentMethodId()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `active` to the URL query string + if (getActive() != null) { + joiner.add(String.format("%sactive%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getActive()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `createdAt` to the URL query string + if (getCreatedAt() != null) { + joiner.add(String.format("%screatedAt%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getCreatedAt()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `updatedAt` to the URL query string + if (getUpdatedAt() != null) { + joiner.add(String.format("%supdatedAt%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getUpdatedAt()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private PaymentMethodBase instance; + + public Builder() { + this(new PaymentMethodBase()); + } + + protected Builder(PaymentMethodBase instance) { + this.instance = instance; + } + + public PaymentMethodBase.Builder paymentMethodId(String paymentMethodId) { + this.instance.paymentMethodId = paymentMethodId; + return this; + } + public PaymentMethodBase.Builder active(Boolean active) { + this.instance.active = active; + return this; + } + public PaymentMethodBase.Builder createdAt(OffsetDateTime createdAt) { + this.instance.createdAt = createdAt; + return this; + } + public PaymentMethodBase.Builder updatedAt(OffsetDateTime updatedAt) { + this.instance.updatedAt = updatedAt; + return this; + } + + + /** + * returns a built PaymentMethodBase instance. + * + * The builder is not reusable. + */ + public PaymentMethodBase build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static PaymentMethodBase.Builder builder() { + return new PaymentMethodBase.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public PaymentMethodBase.Builder toBuilder() { + return new PaymentMethodBase.Builder() + .paymentMethodId(getPaymentMethodId()) + .active(getActive()) + .createdAt(getCreatedAt()) + .updatedAt(getUpdatedAt()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/PaymentMethodsPaymentMethod.java b/java/src/main/java/com/coinbase/cdp/openapi/model/PaymentMethodsPaymentMethod.java new file mode 100644 index 000000000..e4a83f756 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/PaymentMethodsPaymentMethod.java @@ -0,0 +1,368 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.FedwireDetails; +import com.coinbase.cdp.openapi.model.FedwirePaymentMethod; +import com.coinbase.cdp.openapi.model.SepaDetails; +import com.coinbase.cdp.openapi.model.SepaPaymentMethod; +import com.coinbase.cdp.openapi.model.SwiftDetails; +import com.coinbase.cdp.openapi.model.SwiftPaymentMethod; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import com.fasterxml.jackson.core.type.TypeReference; + +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import com.coinbase.cdp.openapi.JSON; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +@JsonDeserialize(using = PaymentMethodsPaymentMethod.PaymentMethodsPaymentMethodDeserializer.class) +@JsonSerialize(using = PaymentMethodsPaymentMethod.PaymentMethodsPaymentMethodSerializer.class) +public class PaymentMethodsPaymentMethod extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(PaymentMethodsPaymentMethod.class.getName()); + + public static class PaymentMethodsPaymentMethodSerializer extends StdSerializer { + public PaymentMethodsPaymentMethodSerializer(Class t) { + super(t); + } + + public PaymentMethodsPaymentMethodSerializer() { + this(null); + } + + @Override + public void serialize(PaymentMethodsPaymentMethod value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { + jgen.writeObject(value.getActualInstance()); + } + } + + public static class PaymentMethodsPaymentMethodDeserializer extends StdDeserializer { + public PaymentMethodsPaymentMethodDeserializer() { + this(PaymentMethodsPaymentMethod.class); + } + + public PaymentMethodsPaymentMethodDeserializer(Class vc) { + super(vc); + } + + @Override + public PaymentMethodsPaymentMethod deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { + JsonNode tree = jp.readValueAsTree(); + Object deserialized = null; + boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS); + int match = 0; + JsonToken token = tree.traverse(jp.getCodec()).nextToken(); + // deserialize FedwirePaymentMethod + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if (FedwirePaymentMethod.class.equals(Integer.class) || FedwirePaymentMethod.class.equals(Long.class) || FedwirePaymentMethod.class.equals(Float.class) || FedwirePaymentMethod.class.equals(Double.class) || FedwirePaymentMethod.class.equals(Boolean.class) || FedwirePaymentMethod.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= ((FedwirePaymentMethod.class.equals(Integer.class) || FedwirePaymentMethod.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= ((FedwirePaymentMethod.class.equals(Float.class) || FedwirePaymentMethod.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= (FedwirePaymentMethod.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= (FedwirePaymentMethod.class.equals(String.class) && token == JsonToken.VALUE_STRING); + } + } + if (attemptParsing) { + deserialized = tree.traverse(jp.getCodec()).readValueAs(FedwirePaymentMethod.class); + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema 'FedwirePaymentMethod'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'FedwirePaymentMethod'", e); + } + + // deserialize SepaPaymentMethod + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if (SepaPaymentMethod.class.equals(Integer.class) || SepaPaymentMethod.class.equals(Long.class) || SepaPaymentMethod.class.equals(Float.class) || SepaPaymentMethod.class.equals(Double.class) || SepaPaymentMethod.class.equals(Boolean.class) || SepaPaymentMethod.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= ((SepaPaymentMethod.class.equals(Integer.class) || SepaPaymentMethod.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= ((SepaPaymentMethod.class.equals(Float.class) || SepaPaymentMethod.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= (SepaPaymentMethod.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= (SepaPaymentMethod.class.equals(String.class) && token == JsonToken.VALUE_STRING); + } + } + if (attemptParsing) { + deserialized = tree.traverse(jp.getCodec()).readValueAs(SepaPaymentMethod.class); + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema 'SepaPaymentMethod'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'SepaPaymentMethod'", e); + } + + // deserialize SwiftPaymentMethod + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if (SwiftPaymentMethod.class.equals(Integer.class) || SwiftPaymentMethod.class.equals(Long.class) || SwiftPaymentMethod.class.equals(Float.class) || SwiftPaymentMethod.class.equals(Double.class) || SwiftPaymentMethod.class.equals(Boolean.class) || SwiftPaymentMethod.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= ((SwiftPaymentMethod.class.equals(Integer.class) || SwiftPaymentMethod.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= ((SwiftPaymentMethod.class.equals(Float.class) || SwiftPaymentMethod.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= (SwiftPaymentMethod.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= (SwiftPaymentMethod.class.equals(String.class) && token == JsonToken.VALUE_STRING); + } + } + if (attemptParsing) { + deserialized = tree.traverse(jp.getCodec()).readValueAs(SwiftPaymentMethod.class); + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema 'SwiftPaymentMethod'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'SwiftPaymentMethod'", e); + } + + if (match == 1) { + PaymentMethodsPaymentMethod ret = new PaymentMethodsPaymentMethod(); + ret.setActualInstance(deserialized); + return ret; + } + throw new IOException(String.format("Failed deserialization for PaymentMethodsPaymentMethod: %d classes match result, expected 1", match)); + } + + /** + * Handle deserialization of the 'null' value. + */ + @Override + public PaymentMethodsPaymentMethod getNullValue(DeserializationContext ctxt) throws JsonMappingException { + throw new JsonMappingException(ctxt.getParser(), "PaymentMethodsPaymentMethod cannot be null"); + } + } + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public PaymentMethodsPaymentMethod() { + super("oneOf", Boolean.FALSE); + } + + public PaymentMethodsPaymentMethod(FedwirePaymentMethod o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public PaymentMethodsPaymentMethod(SepaPaymentMethod o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public PaymentMethodsPaymentMethod(SwiftPaymentMethod o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("FedwirePaymentMethod", FedwirePaymentMethod.class); + schemas.put("SepaPaymentMethod", SepaPaymentMethod.class); + schemas.put("SwiftPaymentMethod", SwiftPaymentMethod.class); + JSON.registerDescendants(PaymentMethodsPaymentMethod.class, Collections.unmodifiableMap(schemas)); + // Initialize and register the discriminator mappings. + Map> mappings = new HashMap>(); + mappings.put("fedwire", FedwirePaymentMethod.class); + mappings.put("sepa", SepaPaymentMethod.class); + mappings.put("swift", SwiftPaymentMethod.class); + mappings.put("FedwirePaymentMethod", FedwirePaymentMethod.class); + mappings.put("SepaPaymentMethod", SepaPaymentMethod.class); + mappings.put("SwiftPaymentMethod", SwiftPaymentMethod.class); + mappings.put("payment-methods_PaymentMethod", PaymentMethodsPaymentMethod.class); + JSON.registerDiscriminator(PaymentMethodsPaymentMethod.class, "paymentRail", mappings); + } + + @Override + public Map> getSchemas() { + return PaymentMethodsPaymentMethod.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * FedwirePaymentMethod, SepaPaymentMethod, SwiftPaymentMethod + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(FedwirePaymentMethod.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(SepaPaymentMethod.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(SwiftPaymentMethod.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be FedwirePaymentMethod, SepaPaymentMethod, SwiftPaymentMethod"); + } + + /** + * Get the actual instance, which can be the following: + * FedwirePaymentMethod, SepaPaymentMethod, SwiftPaymentMethod + * + * @return The actual instance (FedwirePaymentMethod, SepaPaymentMethod, SwiftPaymentMethod) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `FedwirePaymentMethod`. If the actual instance is not `FedwirePaymentMethod`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `FedwirePaymentMethod` + * @throws ClassCastException if the instance is not `FedwirePaymentMethod` + */ + public FedwirePaymentMethod getFedwirePaymentMethod() throws ClassCastException { + return (FedwirePaymentMethod)super.getActualInstance(); + } + + /** + * Get the actual instance of `SepaPaymentMethod`. If the actual instance is not `SepaPaymentMethod`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `SepaPaymentMethod` + * @throws ClassCastException if the instance is not `SepaPaymentMethod` + */ + public SepaPaymentMethod getSepaPaymentMethod() throws ClassCastException { + return (SepaPaymentMethod)super.getActualInstance(); + } + + /** + * Get the actual instance of `SwiftPaymentMethod`. If the actual instance is not `SwiftPaymentMethod`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `SwiftPaymentMethod` + * @throws ClassCastException if the instance is not `SwiftPaymentMethod` + */ + public SwiftPaymentMethod getSwiftPaymentMethod() throws ClassCastException { + return (SwiftPaymentMethod)super.getActualInstance(); + } + + + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + if (getActualInstance() instanceof FedwirePaymentMethod) { + if (getActualInstance() != null) { + joiner.add(((FedwirePaymentMethod)getActualInstance()).toUrlQueryString(prefix + "one_of_0" + suffix)); + } + return joiner.toString(); + } + if (getActualInstance() instanceof SwiftPaymentMethod) { + if (getActualInstance() != null) { + joiner.add(((SwiftPaymentMethod)getActualInstance()).toUrlQueryString(prefix + "one_of_1" + suffix)); + } + return joiner.toString(); + } + if (getActualInstance() instanceof SepaPaymentMethod) { + if (getActualInstance() != null) { + joiner.add(((SepaPaymentMethod)getActualInstance()).toUrlQueryString(prefix + "one_of_2" + suffix)); + } + return joiner.toString(); + } + return null; + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/PhysicalAddress.java b/java/src/main/java/com/coinbase/cdp/openapi/model/PhysicalAddress.java new file mode 100644 index 000000000..80e93a14c --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/PhysicalAddress.java @@ -0,0 +1,410 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * A physical address with standard address components including street, city, state/province, postal code, and country. + */ +@JsonPropertyOrder({ + PhysicalAddress.JSON_PROPERTY_LINE1, + PhysicalAddress.JSON_PROPERTY_LINE2, + PhysicalAddress.JSON_PROPERTY_CITY, + PhysicalAddress.JSON_PROPERTY_STATE, + PhysicalAddress.JSON_PROPERTY_POST_CODE, + PhysicalAddress.JSON_PROPERTY_COUNTRY_CODE +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class PhysicalAddress { + public static final String JSON_PROPERTY_LINE1 = "line1"; + @jakarta.annotation.Nullable + private String line1; + + public static final String JSON_PROPERTY_LINE2 = "line2"; + @jakarta.annotation.Nullable + private String line2; + + public static final String JSON_PROPERTY_CITY = "city"; + @jakarta.annotation.Nullable + private String city; + + public static final String JSON_PROPERTY_STATE = "state"; + @jakarta.annotation.Nullable + private String state; + + public static final String JSON_PROPERTY_POST_CODE = "postCode"; + @jakarta.annotation.Nullable + private String postCode; + + public static final String JSON_PROPERTY_COUNTRY_CODE = "countryCode"; + @jakarta.annotation.Nullable + private String countryCode; + + public PhysicalAddress() { + } + + public PhysicalAddress line1(@jakarta.annotation.Nullable String line1) { + this.line1 = line1; + return this; + } + + /** + * Primary street address. + * @return line1 + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_LINE1) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getLine1() { + return line1; + } + + + @JsonProperty(JSON_PROPERTY_LINE1) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setLine1(@jakarta.annotation.Nullable String line1) { + this.line1 = line1; + } + + + public PhysicalAddress line2(@jakarta.annotation.Nullable String line2) { + this.line2 = line2; + return this; + } + + /** + * Secondary address information. + * @return line2 + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_LINE2) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getLine2() { + return line2; + } + + + @JsonProperty(JSON_PROPERTY_LINE2) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setLine2(@jakarta.annotation.Nullable String line2) { + this.line2 = line2; + } + + + public PhysicalAddress city(@jakarta.annotation.Nullable String city) { + this.city = city; + return this; + } + + /** + * City or locality. + * @return city + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_CITY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getCity() { + return city; + } + + + @JsonProperty(JSON_PROPERTY_CITY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setCity(@jakarta.annotation.Nullable String city) { + this.city = city; + } + + + public PhysicalAddress state(@jakarta.annotation.Nullable String state) { + this.state = state; + return this; + } + + /** + * State, province, or region. + * @return state + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_STATE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getState() { + return state; + } + + + @JsonProperty(JSON_PROPERTY_STATE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setState(@jakarta.annotation.Nullable String state) { + this.state = state; + } + + + public PhysicalAddress postCode(@jakarta.annotation.Nullable String postCode) { + this.postCode = postCode; + return this; + } + + /** + * Postal or ZIP code. + * @return postCode + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_POST_CODE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getPostCode() { + return postCode; + } + + + @JsonProperty(JSON_PROPERTY_POST_CODE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setPostCode(@jakarta.annotation.Nullable String postCode) { + this.postCode = postCode; + } + + + public PhysicalAddress countryCode(@jakarta.annotation.Nullable String countryCode) { + this.countryCode = countryCode; + return this; + } + + /** + * ISO 3166-1 alpha-2 country code (2 characters). See https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes. + * @return countryCode + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_COUNTRY_CODE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getCountryCode() { + return countryCode; + } + + + @JsonProperty(JSON_PROPERTY_COUNTRY_CODE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setCountryCode(@jakarta.annotation.Nullable String countryCode) { + this.countryCode = countryCode; + } + + + /** + * Return true if this PhysicalAddress object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + PhysicalAddress physicalAddress = (PhysicalAddress) o; + return Objects.equals(this.line1, physicalAddress.line1) && + Objects.equals(this.line2, physicalAddress.line2) && + Objects.equals(this.city, physicalAddress.city) && + Objects.equals(this.state, physicalAddress.state) && + Objects.equals(this.postCode, physicalAddress.postCode) && + Objects.equals(this.countryCode, physicalAddress.countryCode); + } + + @Override + public int hashCode() { + return Objects.hash(line1, line2, city, state, postCode, countryCode); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class PhysicalAddress {\n"); + sb.append(" line1: ").append(toIndentedString(line1)).append("\n"); + sb.append(" line2: ").append(toIndentedString(line2)).append("\n"); + sb.append(" city: ").append(toIndentedString(city)).append("\n"); + sb.append(" state: ").append(toIndentedString(state)).append("\n"); + sb.append(" postCode: ").append(toIndentedString(postCode)).append("\n"); + sb.append(" countryCode: ").append(toIndentedString(countryCode)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `line1` to the URL query string + if (getLine1() != null) { + joiner.add(String.format("%sline1%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getLine1()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `line2` to the URL query string + if (getLine2() != null) { + joiner.add(String.format("%sline2%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getLine2()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `city` to the URL query string + if (getCity() != null) { + joiner.add(String.format("%scity%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getCity()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `state` to the URL query string + if (getState() != null) { + joiner.add(String.format("%sstate%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getState()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `postCode` to the URL query string + if (getPostCode() != null) { + joiner.add(String.format("%spostCode%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getPostCode()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `countryCode` to the URL query string + if (getCountryCode() != null) { + joiner.add(String.format("%scountryCode%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getCountryCode()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private PhysicalAddress instance; + + public Builder() { + this(new PhysicalAddress()); + } + + protected Builder(PhysicalAddress instance) { + this.instance = instance; + } + + public PhysicalAddress.Builder line1(String line1) { + this.instance.line1 = line1; + return this; + } + public PhysicalAddress.Builder line2(String line2) { + this.instance.line2 = line2; + return this; + } + public PhysicalAddress.Builder city(String city) { + this.instance.city = city; + return this; + } + public PhysicalAddress.Builder state(String state) { + this.instance.state = state; + return this; + } + public PhysicalAddress.Builder postCode(String postCode) { + this.instance.postCode = postCode; + return this; + } + public PhysicalAddress.Builder countryCode(String countryCode) { + this.instance.countryCode = countryCode; + return this; + } + + + /** + * returns a built PhysicalAddress instance. + * + * The builder is not reusable. + */ + public PhysicalAddress build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static PhysicalAddress.Builder builder() { + return new PhysicalAddress.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public PhysicalAddress.Builder toBuilder() { + return new PhysicalAddress.Builder() + .line1(getLine1()) + .line2(getLine2()) + .city(getCity()) + .state(getState()) + .postCode(getPostCode()) + .countryCode(getCountryCode()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/SendEvmTransaction200Response.java b/java/src/main/java/com/coinbase/cdp/openapi/model/SendEvmTransaction200Response.java new file mode 100644 index 000000000..2b782bd17 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/SendEvmTransaction200Response.java @@ -0,0 +1,205 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * SendEvmTransaction200Response + */ +@JsonPropertyOrder({ + SendEvmTransaction200Response.JSON_PROPERTY_TRANSACTION_HASH +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class SendEvmTransaction200Response { + public static final String JSON_PROPERTY_TRANSACTION_HASH = "transactionHash"; + @jakarta.annotation.Nonnull + private String transactionHash; + + public SendEvmTransaction200Response() { + } + + public SendEvmTransaction200Response transactionHash(@jakarta.annotation.Nonnull String transactionHash) { + this.transactionHash = transactionHash; + return this; + } + + /** + * The hash of the transaction, as a 0x-prefixed hex string. + * @return transactionHash + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_TRANSACTION_HASH) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getTransactionHash() { + return transactionHash; + } + + + @JsonProperty(JSON_PROPERTY_TRANSACTION_HASH) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTransactionHash(@jakarta.annotation.Nonnull String transactionHash) { + this.transactionHash = transactionHash; + } + + + /** + * Return true if this sendEvmTransaction_200_response object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SendEvmTransaction200Response sendEvmTransaction200Response = (SendEvmTransaction200Response) o; + return Objects.equals(this.transactionHash, sendEvmTransaction200Response.transactionHash); + } + + @Override + public int hashCode() { + return Objects.hash(transactionHash); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SendEvmTransaction200Response {\n"); + sb.append(" transactionHash: ").append(toIndentedString(transactionHash)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `transactionHash` to the URL query string + if (getTransactionHash() != null) { + joiner.add(String.format("%stransactionHash%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getTransactionHash()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private SendEvmTransaction200Response instance; + + public Builder() { + this(new SendEvmTransaction200Response()); + } + + protected Builder(SendEvmTransaction200Response instance) { + this.instance = instance; + } + + public SendEvmTransaction200Response.Builder transactionHash(String transactionHash) { + this.instance.transactionHash = transactionHash; + return this; + } + + + /** + * returns a built SendEvmTransaction200Response instance. + * + * The builder is not reusable. + */ + public SendEvmTransaction200Response build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static SendEvmTransaction200Response.Builder builder() { + return new SendEvmTransaction200Response.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public SendEvmTransaction200Response.Builder toBuilder() { + return new SendEvmTransaction200Response.Builder() + .transactionHash(getTransactionHash()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/SendSolanaTransaction200Response.java b/java/src/main/java/com/coinbase/cdp/openapi/model/SendSolanaTransaction200Response.java new file mode 100644 index 000000000..4e5bcee1b --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/SendSolanaTransaction200Response.java @@ -0,0 +1,205 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * SendSolanaTransaction200Response + */ +@JsonPropertyOrder({ + SendSolanaTransaction200Response.JSON_PROPERTY_TRANSACTION_SIGNATURE +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class SendSolanaTransaction200Response { + public static final String JSON_PROPERTY_TRANSACTION_SIGNATURE = "transactionSignature"; + @jakarta.annotation.Nonnull + private String transactionSignature; + + public SendSolanaTransaction200Response() { + } + + public SendSolanaTransaction200Response transactionSignature(@jakarta.annotation.Nonnull String transactionSignature) { + this.transactionSignature = transactionSignature; + return this; + } + + /** + * The base58 encoded transaction signature. + * @return transactionSignature + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_TRANSACTION_SIGNATURE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getTransactionSignature() { + return transactionSignature; + } + + + @JsonProperty(JSON_PROPERTY_TRANSACTION_SIGNATURE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTransactionSignature(@jakarta.annotation.Nonnull String transactionSignature) { + this.transactionSignature = transactionSignature; + } + + + /** + * Return true if this sendSolanaTransaction_200_response object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SendSolanaTransaction200Response sendSolanaTransaction200Response = (SendSolanaTransaction200Response) o; + return Objects.equals(this.transactionSignature, sendSolanaTransaction200Response.transactionSignature); + } + + @Override + public int hashCode() { + return Objects.hash(transactionSignature); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SendSolanaTransaction200Response {\n"); + sb.append(" transactionSignature: ").append(toIndentedString(transactionSignature)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `transactionSignature` to the URL query string + if (getTransactionSignature() != null) { + joiner.add(String.format("%stransactionSignature%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getTransactionSignature()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private SendSolanaTransaction200Response instance; + + public Builder() { + this(new SendSolanaTransaction200Response()); + } + + protected Builder(SendSolanaTransaction200Response instance) { + this.instance = instance; + } + + public SendSolanaTransaction200Response.Builder transactionSignature(String transactionSignature) { + this.instance.transactionSignature = transactionSignature; + return this; + } + + + /** + * returns a built SendSolanaTransaction200Response instance. + * + * The builder is not reusable. + */ + public SendSolanaTransaction200Response build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static SendSolanaTransaction200Response.Builder builder() { + return new SendSolanaTransaction200Response.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public SendSolanaTransaction200Response.Builder toBuilder() { + return new SendSolanaTransaction200Response.Builder() + .transactionSignature(getTransactionSignature()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/SendUserOperationCriteria.java b/java/src/main/java/com/coinbase/cdp/openapi/model/SendUserOperationCriteria.java index 4c3dd00c0..18fcb48a1 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/model/SendUserOperationCriteria.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/SendUserOperationCriteria.java @@ -19,7 +19,7 @@ import java.util.Objects; import java.util.Map; import java.util.HashMap; -import com.coinbase.cdp.openapi.model.SignEvmTransactionCriteriaInner; +import com.coinbase.cdp.openapi.model.SendEvmTransactionCriteriaInner; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @@ -32,7 +32,7 @@ @JsonPropertyOrder({ }) @jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") -public class SendUserOperationCriteria extends ArrayList { +public class SendUserOperationCriteria extends ArrayList { public SendUserOperationCriteria() { } diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/SepaDetails.java b/java/src/main/java/com/coinbase/cdp/openapi/model/SepaDetails.java new file mode 100644 index 000000000..1809c06b2 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/SepaDetails.java @@ -0,0 +1,328 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * Details specific to SEPA (Single Euro Payments Area) payment methods. + */ +@JsonPropertyOrder({ + SepaDetails.JSON_PROPERTY_ASSET, + SepaDetails.JSON_PROPERTY_BANK_NAME, + SepaDetails.JSON_PROPERTY_IBAN_LAST4, + SepaDetails.JSON_PROPERTY_BIC +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class SepaDetails { + public static final String JSON_PROPERTY_ASSET = "asset"; + @jakarta.annotation.Nonnull + private String asset; + + public static final String JSON_PROPERTY_BANK_NAME = "bankName"; + @jakarta.annotation.Nonnull + private String bankName; + + public static final String JSON_PROPERTY_IBAN_LAST4 = "ibanLast4"; + @jakarta.annotation.Nonnull + private String ibanLast4; + + public static final String JSON_PROPERTY_BIC = "bic"; + @jakarta.annotation.Nonnull + private String bic; + + public SepaDetails() { + } + + public SepaDetails asset(@jakarta.annotation.Nonnull String asset) { + this.asset = asset; + return this; + } + + /** + * The asset for this payment method. Always `eur` for SEPA. + * @return asset + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAsset() { + return asset; + } + + + @JsonProperty(JSON_PROPERTY_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAsset(@jakarta.annotation.Nonnull String asset) { + this.asset = asset; + } + + + public SepaDetails bankName(@jakarta.annotation.Nonnull String bankName) { + this.bankName = bankName; + return this; + } + + /** + * The name of the bank. + * @return bankName + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_BANK_NAME) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getBankName() { + return bankName; + } + + + @JsonProperty(JSON_PROPERTY_BANK_NAME) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBankName(@jakarta.annotation.Nonnull String bankName) { + this.bankName = bankName; + } + + + public SepaDetails ibanLast4(@jakarta.annotation.Nonnull String ibanLast4) { + this.ibanLast4 = ibanLast4; + return this; + } + + /** + * The last 4 characters of the IBAN. + * @return ibanLast4 + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_IBAN_LAST4) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getIbanLast4() { + return ibanLast4; + } + + + @JsonProperty(JSON_PROPERTY_IBAN_LAST4) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setIbanLast4(@jakarta.annotation.Nonnull String ibanLast4) { + this.ibanLast4 = ibanLast4; + } + + + public SepaDetails bic(@jakarta.annotation.Nonnull String bic) { + this.bic = bic; + return this; + } + + /** + * The Bank Identifier Code (BIC) / SWIFT code. + * @return bic + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_BIC) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getBic() { + return bic; + } + + + @JsonProperty(JSON_PROPERTY_BIC) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBic(@jakarta.annotation.Nonnull String bic) { + this.bic = bic; + } + + + /** + * Return true if this SepaDetails object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SepaDetails sepaDetails = (SepaDetails) o; + return Objects.equals(this.asset, sepaDetails.asset) && + Objects.equals(this.bankName, sepaDetails.bankName) && + Objects.equals(this.ibanLast4, sepaDetails.ibanLast4) && + Objects.equals(this.bic, sepaDetails.bic); + } + + @Override + public int hashCode() { + return Objects.hash(asset, bankName, ibanLast4, bic); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SepaDetails {\n"); + sb.append(" asset: ").append(toIndentedString(asset)).append("\n"); + sb.append(" bankName: ").append(toIndentedString(bankName)).append("\n"); + sb.append(" ibanLast4: ").append(toIndentedString(ibanLast4)).append("\n"); + sb.append(" bic: ").append(toIndentedString(bic)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `asset` to the URL query string + if (getAsset() != null) { + joiner.add(String.format("%sasset%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAsset()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `bankName` to the URL query string + if (getBankName() != null) { + joiner.add(String.format("%sbankName%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getBankName()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `ibanLast4` to the URL query string + if (getIbanLast4() != null) { + joiner.add(String.format("%sibanLast4%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getIbanLast4()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `bic` to the URL query string + if (getBic() != null) { + joiner.add(String.format("%sbic%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getBic()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private SepaDetails instance; + + public Builder() { + this(new SepaDetails()); + } + + protected Builder(SepaDetails instance) { + this.instance = instance; + } + + public SepaDetails.Builder asset(String asset) { + this.instance.asset = asset; + return this; + } + public SepaDetails.Builder bankName(String bankName) { + this.instance.bankName = bankName; + return this; + } + public SepaDetails.Builder ibanLast4(String ibanLast4) { + this.instance.ibanLast4 = ibanLast4; + return this; + } + public SepaDetails.Builder bic(String bic) { + this.instance.bic = bic; + return this; + } + + + /** + * returns a built SepaDetails instance. + * + * The builder is not reusable. + */ + public SepaDetails build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static SepaDetails.Builder builder() { + return new SepaDetails.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public SepaDetails.Builder toBuilder() { + return new SepaDetails.Builder() + .asset(getAsset()) + .bankName(getBankName()) + .ibanLast4(getIbanLast4()) + .bic(getBic()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/SepaPaymentMethod.java b/java/src/main/java/com/coinbase/cdp/openapi/model/SepaPaymentMethod.java new file mode 100644 index 000000000..c21cd9060 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/SepaPaymentMethod.java @@ -0,0 +1,445 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.SepaDetails; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * A SEPA (Single Euro Payments Area) payment method linked to your entity. + */ +@JsonPropertyOrder({ + SepaPaymentMethod.JSON_PROPERTY_PAYMENT_METHOD_ID, + SepaPaymentMethod.JSON_PROPERTY_ACTIVE, + SepaPaymentMethod.JSON_PROPERTY_CREATED_AT, + SepaPaymentMethod.JSON_PROPERTY_UPDATED_AT, + SepaPaymentMethod.JSON_PROPERTY_PAYMENT_RAIL, + SepaPaymentMethod.JSON_PROPERTY_SEPA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class SepaPaymentMethod { + public static final String JSON_PROPERTY_PAYMENT_METHOD_ID = "paymentMethodId"; + @jakarta.annotation.Nonnull + private String paymentMethodId; + + public static final String JSON_PROPERTY_ACTIVE = "active"; + @jakarta.annotation.Nonnull + private Boolean active; + + public static final String JSON_PROPERTY_CREATED_AT = "createdAt"; + @jakarta.annotation.Nonnull + private OffsetDateTime createdAt; + + public static final String JSON_PROPERTY_UPDATED_AT = "updatedAt"; + @jakarta.annotation.Nonnull + private OffsetDateTime updatedAt; + + /** + * The payment rail for this payment method. + */ + public enum PaymentRailEnum { + SEPA(String.valueOf("sepa")); + + private String value; + + PaymentRailEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static PaymentRailEnum fromValue(String value) { + for (PaymentRailEnum b : PaymentRailEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + public static final String JSON_PROPERTY_PAYMENT_RAIL = "paymentRail"; + @jakarta.annotation.Nonnull + private PaymentRailEnum paymentRail; + + public static final String JSON_PROPERTY_SEPA = "sepa"; + @jakarta.annotation.Nonnull + private SepaDetails sepa; + + public SepaPaymentMethod() { + } + + public SepaPaymentMethod paymentMethodId(@jakarta.annotation.Nonnull String paymentMethodId) { + this.paymentMethodId = paymentMethodId; + return this; + } + + /** + * The ID of the Payment Method, which is a UUID prefixed by the string `paymentMethod_`. + * @return paymentMethodId + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_PAYMENT_METHOD_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getPaymentMethodId() { + return paymentMethodId; + } + + + @JsonProperty(JSON_PROPERTY_PAYMENT_METHOD_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setPaymentMethodId(@jakarta.annotation.Nonnull String paymentMethodId) { + this.paymentMethodId = paymentMethodId; + } + + + public SepaPaymentMethod active(@jakarta.annotation.Nonnull Boolean active) { + this.active = active; + return this; + } + + /** + * Whether the payment method is active and can be used in transfers. A payment method may be inactive due to verification requirements or entity-level restrictions. + * @return active + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ACTIVE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public Boolean getActive() { + return active; + } + + + @JsonProperty(JSON_PROPERTY_ACTIVE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setActive(@jakarta.annotation.Nonnull Boolean active) { + this.active = active; + } + + + public SepaPaymentMethod createdAt(@jakarta.annotation.Nonnull OffsetDateTime createdAt) { + this.createdAt = createdAt; + return this; + } + + /** + * The timestamp when the payment method was created. + * @return createdAt + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_CREATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public OffsetDateTime getCreatedAt() { + return createdAt; + } + + + @JsonProperty(JSON_PROPERTY_CREATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCreatedAt(@jakarta.annotation.Nonnull OffsetDateTime createdAt) { + this.createdAt = createdAt; + } + + + public SepaPaymentMethod updatedAt(@jakarta.annotation.Nonnull OffsetDateTime updatedAt) { + this.updatedAt = updatedAt; + return this; + } + + /** + * The timestamp when the payment method was last updated. + * @return updatedAt + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_UPDATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public OffsetDateTime getUpdatedAt() { + return updatedAt; + } + + + @JsonProperty(JSON_PROPERTY_UPDATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUpdatedAt(@jakarta.annotation.Nonnull OffsetDateTime updatedAt) { + this.updatedAt = updatedAt; + } + + + public SepaPaymentMethod paymentRail(@jakarta.annotation.Nonnull PaymentRailEnum paymentRail) { + this.paymentRail = paymentRail; + return this; + } + + /** + * The payment rail for this payment method. + * @return paymentRail + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_PAYMENT_RAIL) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public PaymentRailEnum getPaymentRail() { + return paymentRail; + } + + + @JsonProperty(JSON_PROPERTY_PAYMENT_RAIL) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setPaymentRail(@jakarta.annotation.Nonnull PaymentRailEnum paymentRail) { + this.paymentRail = paymentRail; + } + + + public SepaPaymentMethod sepa(@jakarta.annotation.Nonnull SepaDetails sepa) { + this.sepa = sepa; + return this; + } + + /** + * SEPA (Single Euro Payments Area) details. + * @return sepa + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_SEPA) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public SepaDetails getSepa() { + return sepa; + } + + + @JsonProperty(JSON_PROPERTY_SEPA) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setSepa(@jakarta.annotation.Nonnull SepaDetails sepa) { + this.sepa = sepa; + } + + + /** + * Return true if this SepaPaymentMethod object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SepaPaymentMethod sepaPaymentMethod = (SepaPaymentMethod) o; + return Objects.equals(this.paymentMethodId, sepaPaymentMethod.paymentMethodId) && + Objects.equals(this.active, sepaPaymentMethod.active) && + Objects.equals(this.createdAt, sepaPaymentMethod.createdAt) && + Objects.equals(this.updatedAt, sepaPaymentMethod.updatedAt) && + Objects.equals(this.paymentRail, sepaPaymentMethod.paymentRail) && + Objects.equals(this.sepa, sepaPaymentMethod.sepa); + } + + @Override + public int hashCode() { + return Objects.hash(paymentMethodId, active, createdAt, updatedAt, paymentRail, sepa); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SepaPaymentMethod {\n"); + sb.append(" paymentMethodId: ").append(toIndentedString(paymentMethodId)).append("\n"); + sb.append(" active: ").append(toIndentedString(active)).append("\n"); + sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); + sb.append(" updatedAt: ").append(toIndentedString(updatedAt)).append("\n"); + sb.append(" paymentRail: ").append(toIndentedString(paymentRail)).append("\n"); + sb.append(" sepa: ").append(toIndentedString(sepa)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `paymentMethodId` to the URL query string + if (getPaymentMethodId() != null) { + joiner.add(String.format("%spaymentMethodId%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getPaymentMethodId()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `active` to the URL query string + if (getActive() != null) { + joiner.add(String.format("%sactive%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getActive()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `createdAt` to the URL query string + if (getCreatedAt() != null) { + joiner.add(String.format("%screatedAt%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getCreatedAt()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `updatedAt` to the URL query string + if (getUpdatedAt() != null) { + joiner.add(String.format("%supdatedAt%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getUpdatedAt()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `paymentRail` to the URL query string + if (getPaymentRail() != null) { + joiner.add(String.format("%spaymentRail%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getPaymentRail()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `sepa` to the URL query string + if (getSepa() != null) { + joiner.add(getSepa().toUrlQueryString(prefix + "sepa" + suffix)); + } + + return joiner.toString(); + } + + public static class Builder { + + private SepaPaymentMethod instance; + + public Builder() { + this(new SepaPaymentMethod()); + } + + protected Builder(SepaPaymentMethod instance) { + this.instance = instance; + } + + public SepaPaymentMethod.Builder paymentMethodId(String paymentMethodId) { + this.instance.paymentMethodId = paymentMethodId; + return this; + } + public SepaPaymentMethod.Builder active(Boolean active) { + this.instance.active = active; + return this; + } + public SepaPaymentMethod.Builder createdAt(OffsetDateTime createdAt) { + this.instance.createdAt = createdAt; + return this; + } + public SepaPaymentMethod.Builder updatedAt(OffsetDateTime updatedAt) { + this.instance.updatedAt = updatedAt; + return this; + } + public SepaPaymentMethod.Builder paymentRail(PaymentRailEnum paymentRail) { + this.instance.paymentRail = paymentRail; + return this; + } + public SepaPaymentMethod.Builder sepa(SepaDetails sepa) { + this.instance.sepa = sepa; + return this; + } + + + /** + * returns a built SepaPaymentMethod instance. + * + * The builder is not reusable. + */ + public SepaPaymentMethod build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static SepaPaymentMethod.Builder builder() { + return new SepaPaymentMethod.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public SepaPaymentMethod.Builder toBuilder() { + return new SepaPaymentMethod.Builder() + .paymentMethodId(getPaymentMethodId()) + .active(getActive()) + .createdAt(getCreatedAt()) + .updatedAt(getUpdatedAt()) + .paymentRail(getPaymentRail()) + .sepa(getSepa()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/SignEvmMessage200Response.java b/java/src/main/java/com/coinbase/cdp/openapi/model/SignEvmMessage200Response.java new file mode 100644 index 000000000..c2445d405 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/SignEvmMessage200Response.java @@ -0,0 +1,205 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * SignEvmMessage200Response + */ +@JsonPropertyOrder({ + SignEvmMessage200Response.JSON_PROPERTY_SIGNATURE +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class SignEvmMessage200Response { + public static final String JSON_PROPERTY_SIGNATURE = "signature"; + @jakarta.annotation.Nonnull + private String signature; + + public SignEvmMessage200Response() { + } + + public SignEvmMessage200Response signature(@jakarta.annotation.Nonnull String signature) { + this.signature = signature; + return this; + } + + /** + * The signature of the message, as a 0x-prefixed hex string. + * @return signature + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_SIGNATURE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getSignature() { + return signature; + } + + + @JsonProperty(JSON_PROPERTY_SIGNATURE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setSignature(@jakarta.annotation.Nonnull String signature) { + this.signature = signature; + } + + + /** + * Return true if this signEvmMessage_200_response object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SignEvmMessage200Response signEvmMessage200Response = (SignEvmMessage200Response) o; + return Objects.equals(this.signature, signEvmMessage200Response.signature); + } + + @Override + public int hashCode() { + return Objects.hash(signature); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SignEvmMessage200Response {\n"); + sb.append(" signature: ").append(toIndentedString(signature)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `signature` to the URL query string + if (getSignature() != null) { + joiner.add(String.format("%ssignature%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getSignature()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private SignEvmMessage200Response instance; + + public Builder() { + this(new SignEvmMessage200Response()); + } + + protected Builder(SignEvmMessage200Response instance) { + this.instance = instance; + } + + public SignEvmMessage200Response.Builder signature(String signature) { + this.instance.signature = signature; + return this; + } + + + /** + * returns a built SignEvmMessage200Response instance. + * + * The builder is not reusable. + */ + public SignEvmMessage200Response build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static SignEvmMessage200Response.Builder builder() { + return new SignEvmMessage200Response.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public SignEvmMessage200Response.Builder toBuilder() { + return new SignEvmMessage200Response.Builder() + .signature(getSignature()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/SignEvmTransaction200Response.java b/java/src/main/java/com/coinbase/cdp/openapi/model/SignEvmTransaction200Response.java new file mode 100644 index 000000000..c63ca48fe --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/SignEvmTransaction200Response.java @@ -0,0 +1,205 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * SignEvmTransaction200Response + */ +@JsonPropertyOrder({ + SignEvmTransaction200Response.JSON_PROPERTY_SIGNED_TRANSACTION +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class SignEvmTransaction200Response { + public static final String JSON_PROPERTY_SIGNED_TRANSACTION = "signedTransaction"; + @jakarta.annotation.Nonnull + private String signedTransaction; + + public SignEvmTransaction200Response() { + } + + public SignEvmTransaction200Response signedTransaction(@jakarta.annotation.Nonnull String signedTransaction) { + this.signedTransaction = signedTransaction; + return this; + } + + /** + * The RLP-encoded signed transaction, as a 0x-prefixed hex string. + * @return signedTransaction + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_SIGNED_TRANSACTION) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getSignedTransaction() { + return signedTransaction; + } + + + @JsonProperty(JSON_PROPERTY_SIGNED_TRANSACTION) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setSignedTransaction(@jakarta.annotation.Nonnull String signedTransaction) { + this.signedTransaction = signedTransaction; + } + + + /** + * Return true if this signEvmTransaction_200_response object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SignEvmTransaction200Response signEvmTransaction200Response = (SignEvmTransaction200Response) o; + return Objects.equals(this.signedTransaction, signEvmTransaction200Response.signedTransaction); + } + + @Override + public int hashCode() { + return Objects.hash(signedTransaction); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SignEvmTransaction200Response {\n"); + sb.append(" signedTransaction: ").append(toIndentedString(signedTransaction)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `signedTransaction` to the URL query string + if (getSignedTransaction() != null) { + joiner.add(String.format("%ssignedTransaction%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getSignedTransaction()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private SignEvmTransaction200Response instance; + + public Builder() { + this(new SignEvmTransaction200Response()); + } + + protected Builder(SignEvmTransaction200Response instance) { + this.instance = instance; + } + + public SignEvmTransaction200Response.Builder signedTransaction(String signedTransaction) { + this.instance.signedTransaction = signedTransaction; + return this; + } + + + /** + * returns a built SignEvmTransaction200Response instance. + * + * The builder is not reusable. + */ + public SignEvmTransaction200Response build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static SignEvmTransaction200Response.Builder builder() { + return new SignEvmTransaction200Response.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public SignEvmTransaction200Response.Builder toBuilder() { + return new SignEvmTransaction200Response.Builder() + .signedTransaction(getSignedTransaction()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/SignEvmTypedData200Response.java b/java/src/main/java/com/coinbase/cdp/openapi/model/SignEvmTypedData200Response.java new file mode 100644 index 000000000..876ff1529 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/SignEvmTypedData200Response.java @@ -0,0 +1,205 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * SignEvmTypedData200Response + */ +@JsonPropertyOrder({ + SignEvmTypedData200Response.JSON_PROPERTY_SIGNATURE +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class SignEvmTypedData200Response { + public static final String JSON_PROPERTY_SIGNATURE = "signature"; + @jakarta.annotation.Nonnull + private String signature; + + public SignEvmTypedData200Response() { + } + + public SignEvmTypedData200Response signature(@jakarta.annotation.Nonnull String signature) { + this.signature = signature; + return this; + } + + /** + * The signature of the typed data, as a 0x-prefixed hex string. + * @return signature + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_SIGNATURE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getSignature() { + return signature; + } + + + @JsonProperty(JSON_PROPERTY_SIGNATURE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setSignature(@jakarta.annotation.Nonnull String signature) { + this.signature = signature; + } + + + /** + * Return true if this signEvmTypedData_200_response object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SignEvmTypedData200Response signEvmTypedData200Response = (SignEvmTypedData200Response) o; + return Objects.equals(this.signature, signEvmTypedData200Response.signature); + } + + @Override + public int hashCode() { + return Objects.hash(signature); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SignEvmTypedData200Response {\n"); + sb.append(" signature: ").append(toIndentedString(signature)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `signature` to the URL query string + if (getSignature() != null) { + joiner.add(String.format("%ssignature%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getSignature()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private SignEvmTypedData200Response instance; + + public Builder() { + this(new SignEvmTypedData200Response()); + } + + protected Builder(SignEvmTypedData200Response instance) { + this.instance = instance; + } + + public SignEvmTypedData200Response.Builder signature(String signature) { + this.instance.signature = signature; + return this; + } + + + /** + * returns a built SignEvmTypedData200Response instance. + * + * The builder is not reusable. + */ + public SignEvmTypedData200Response build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static SignEvmTypedData200Response.Builder builder() { + return new SignEvmTypedData200Response.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public SignEvmTypedData200Response.Builder toBuilder() { + return new SignEvmTypedData200Response.Builder() + .signature(getSignature()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/SignSolanaMessage200Response.java b/java/src/main/java/com/coinbase/cdp/openapi/model/SignSolanaMessage200Response.java new file mode 100644 index 000000000..8f4a914d1 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/SignSolanaMessage200Response.java @@ -0,0 +1,205 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * SignSolanaMessage200Response + */ +@JsonPropertyOrder({ + SignSolanaMessage200Response.JSON_PROPERTY_SIGNATURE +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class SignSolanaMessage200Response { + public static final String JSON_PROPERTY_SIGNATURE = "signature"; + @jakarta.annotation.Nonnull + private String signature; + + public SignSolanaMessage200Response() { + } + + public SignSolanaMessage200Response signature(@jakarta.annotation.Nonnull String signature) { + this.signature = signature; + return this; + } + + /** + * The signature of the message, as a base58 encoded string. + * @return signature + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_SIGNATURE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getSignature() { + return signature; + } + + + @JsonProperty(JSON_PROPERTY_SIGNATURE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setSignature(@jakarta.annotation.Nonnull String signature) { + this.signature = signature; + } + + + /** + * Return true if this signSolanaMessage_200_response object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SignSolanaMessage200Response signSolanaMessage200Response = (SignSolanaMessage200Response) o; + return Objects.equals(this.signature, signSolanaMessage200Response.signature); + } + + @Override + public int hashCode() { + return Objects.hash(signature); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SignSolanaMessage200Response {\n"); + sb.append(" signature: ").append(toIndentedString(signature)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `signature` to the URL query string + if (getSignature() != null) { + joiner.add(String.format("%ssignature%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getSignature()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private SignSolanaMessage200Response instance; + + public Builder() { + this(new SignSolanaMessage200Response()); + } + + protected Builder(SignSolanaMessage200Response instance) { + this.instance = instance; + } + + public SignSolanaMessage200Response.Builder signature(String signature) { + this.instance.signature = signature; + return this; + } + + + /** + * returns a built SignSolanaMessage200Response instance. + * + * The builder is not reusable. + */ + public SignSolanaMessage200Response build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static SignSolanaMessage200Response.Builder builder() { + return new SignSolanaMessage200Response.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public SignSolanaMessage200Response.Builder toBuilder() { + return new SignSolanaMessage200Response.Builder() + .signature(getSignature()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/SignSolanaTransaction200Response.java b/java/src/main/java/com/coinbase/cdp/openapi/model/SignSolanaTransaction200Response.java new file mode 100644 index 000000000..637233e10 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/SignSolanaTransaction200Response.java @@ -0,0 +1,205 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * SignSolanaTransaction200Response + */ +@JsonPropertyOrder({ + SignSolanaTransaction200Response.JSON_PROPERTY_SIGNED_TRANSACTION +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class SignSolanaTransaction200Response { + public static final String JSON_PROPERTY_SIGNED_TRANSACTION = "signedTransaction"; + @jakarta.annotation.Nonnull + private String signedTransaction; + + public SignSolanaTransaction200Response() { + } + + public SignSolanaTransaction200Response signedTransaction(@jakarta.annotation.Nonnull String signedTransaction) { + this.signedTransaction = signedTransaction; + return this; + } + + /** + * The base64 encoded signed transaction. + * @return signedTransaction + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_SIGNED_TRANSACTION) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getSignedTransaction() { + return signedTransaction; + } + + + @JsonProperty(JSON_PROPERTY_SIGNED_TRANSACTION) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setSignedTransaction(@jakarta.annotation.Nonnull String signedTransaction) { + this.signedTransaction = signedTransaction; + } + + + /** + * Return true if this signSolanaTransaction_200_response object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SignSolanaTransaction200Response signSolanaTransaction200Response = (SignSolanaTransaction200Response) o; + return Objects.equals(this.signedTransaction, signSolanaTransaction200Response.signedTransaction); + } + + @Override + public int hashCode() { + return Objects.hash(signedTransaction); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SignSolanaTransaction200Response {\n"); + sb.append(" signedTransaction: ").append(toIndentedString(signedTransaction)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `signedTransaction` to the URL query string + if (getSignedTransaction() != null) { + joiner.add(String.format("%ssignedTransaction%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getSignedTransaction()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private SignSolanaTransaction200Response instance; + + public Builder() { + this(new SignSolanaTransaction200Response()); + } + + protected Builder(SignSolanaTransaction200Response instance) { + this.instance = instance; + } + + public SignSolanaTransaction200Response.Builder signedTransaction(String signedTransaction) { + this.instance.signedTransaction = signedTransaction; + return this; + } + + + /** + * returns a built SignSolanaTransaction200Response instance. + * + * The builder is not reusable. + */ + public SignSolanaTransaction200Response build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static SignSolanaTransaction200Response.Builder builder() { + return new SignSolanaTransaction200Response.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public SignSolanaTransaction200Response.Builder toBuilder() { + return new SignSolanaTransaction200Response.Builder() + .signedTransaction(getSignedTransaction()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/SwiftDetails.java b/java/src/main/java/com/coinbase/cdp/openapi/model/SwiftDetails.java new file mode 100644 index 000000000..729a66cfc --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/SwiftDetails.java @@ -0,0 +1,371 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * Details specific to SWIFT (international wire) payment methods. + */ +@JsonPropertyOrder({ + SwiftDetails.JSON_PROPERTY_ASSET, + SwiftDetails.JSON_PROPERTY_BANK_NAME, + SwiftDetails.JSON_PROPERTY_ACCOUNT_LAST4, + SwiftDetails.JSON_PROPERTY_IBAN_LAST4, + SwiftDetails.JSON_PROPERTY_BIC +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class SwiftDetails { + public static final String JSON_PROPERTY_ASSET = "asset"; + @jakarta.annotation.Nonnull + private String asset; + + public static final String JSON_PROPERTY_BANK_NAME = "bankName"; + @jakarta.annotation.Nonnull + private String bankName; + + public static final String JSON_PROPERTY_ACCOUNT_LAST4 = "accountLast4"; + @jakarta.annotation.Nonnull + private String accountLast4; + + public static final String JSON_PROPERTY_IBAN_LAST4 = "ibanLast4"; + @jakarta.annotation.Nullable + private String ibanLast4; + + public static final String JSON_PROPERTY_BIC = "bic"; + @jakarta.annotation.Nonnull + private String bic; + + public SwiftDetails() { + } + + public SwiftDetails asset(@jakarta.annotation.Nonnull String asset) { + this.asset = asset; + return this; + } + + /** + * The asset for this payment method (e.g., `eur`, `gbp`). + * @return asset + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAsset() { + return asset; + } + + + @JsonProperty(JSON_PROPERTY_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAsset(@jakarta.annotation.Nonnull String asset) { + this.asset = asset; + } + + + public SwiftDetails bankName(@jakarta.annotation.Nonnull String bankName) { + this.bankName = bankName; + return this; + } + + /** + * The name of the bank. + * @return bankName + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_BANK_NAME) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getBankName() { + return bankName; + } + + + @JsonProperty(JSON_PROPERTY_BANK_NAME) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBankName(@jakarta.annotation.Nonnull String bankName) { + this.bankName = bankName; + } + + + public SwiftDetails accountLast4(@jakarta.annotation.Nonnull String accountLast4) { + this.accountLast4 = accountLast4; + return this; + } + + /** + * The last 4 characters of the account identifier. For IBAN-based accounts (e.g., EU), this is the last 4 characters of the IBAN. For account number-based accounts (e.g., US), this is the last 4 digits of the account number. + * @return accountLast4 + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ACCOUNT_LAST4) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAccountLast4() { + return accountLast4; + } + + + @JsonProperty(JSON_PROPERTY_ACCOUNT_LAST4) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAccountLast4(@jakarta.annotation.Nonnull String accountLast4) { + this.accountLast4 = accountLast4; + } + + + public SwiftDetails ibanLast4(@jakarta.annotation.Nullable String ibanLast4) { + this.ibanLast4 = ibanLast4; + return this; + } + + /** + * Deprecated: use `accountLast4` instead. The last 4 characters of the account identifier. + * @return ibanLast4 + * @deprecated + */ + @Deprecated + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_IBAN_LAST4) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getIbanLast4() { + return ibanLast4; + } + + + @JsonProperty(JSON_PROPERTY_IBAN_LAST4) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setIbanLast4(@jakarta.annotation.Nullable String ibanLast4) { + this.ibanLast4 = ibanLast4; + } + + + public SwiftDetails bic(@jakarta.annotation.Nonnull String bic) { + this.bic = bic; + return this; + } + + /** + * The Bank Identifier Code (BIC) / SWIFT code. + * @return bic + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_BIC) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getBic() { + return bic; + } + + + @JsonProperty(JSON_PROPERTY_BIC) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBic(@jakarta.annotation.Nonnull String bic) { + this.bic = bic; + } + + + /** + * Return true if this SwiftDetails object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SwiftDetails swiftDetails = (SwiftDetails) o; + return Objects.equals(this.asset, swiftDetails.asset) && + Objects.equals(this.bankName, swiftDetails.bankName) && + Objects.equals(this.accountLast4, swiftDetails.accountLast4) && + Objects.equals(this.ibanLast4, swiftDetails.ibanLast4) && + Objects.equals(this.bic, swiftDetails.bic); + } + + @Override + public int hashCode() { + return Objects.hash(asset, bankName, accountLast4, ibanLast4, bic); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SwiftDetails {\n"); + sb.append(" asset: ").append(toIndentedString(asset)).append("\n"); + sb.append(" bankName: ").append(toIndentedString(bankName)).append("\n"); + sb.append(" accountLast4: ").append(toIndentedString(accountLast4)).append("\n"); + sb.append(" ibanLast4: ").append(toIndentedString(ibanLast4)).append("\n"); + sb.append(" bic: ").append(toIndentedString(bic)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `asset` to the URL query string + if (getAsset() != null) { + joiner.add(String.format("%sasset%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAsset()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `bankName` to the URL query string + if (getBankName() != null) { + joiner.add(String.format("%sbankName%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getBankName()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `accountLast4` to the URL query string + if (getAccountLast4() != null) { + joiner.add(String.format("%saccountLast4%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAccountLast4()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `ibanLast4` to the URL query string + if (getIbanLast4() != null) { + joiner.add(String.format("%sibanLast4%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getIbanLast4()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `bic` to the URL query string + if (getBic() != null) { + joiner.add(String.format("%sbic%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getBic()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private SwiftDetails instance; + + public Builder() { + this(new SwiftDetails()); + } + + protected Builder(SwiftDetails instance) { + this.instance = instance; + } + + public SwiftDetails.Builder asset(String asset) { + this.instance.asset = asset; + return this; + } + public SwiftDetails.Builder bankName(String bankName) { + this.instance.bankName = bankName; + return this; + } + public SwiftDetails.Builder accountLast4(String accountLast4) { + this.instance.accountLast4 = accountLast4; + return this; + } + public SwiftDetails.Builder ibanLast4(String ibanLast4) { + this.instance.ibanLast4 = ibanLast4; + return this; + } + public SwiftDetails.Builder bic(String bic) { + this.instance.bic = bic; + return this; + } + + + /** + * returns a built SwiftDetails instance. + * + * The builder is not reusable. + */ + public SwiftDetails build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static SwiftDetails.Builder builder() { + return new SwiftDetails.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public SwiftDetails.Builder toBuilder() { + return new SwiftDetails.Builder() + .asset(getAsset()) + .bankName(getBankName()) + .accountLast4(getAccountLast4()) + .ibanLast4(getIbanLast4()) + .bic(getBic()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/SwiftPaymentMethod.java b/java/src/main/java/com/coinbase/cdp/openapi/model/SwiftPaymentMethod.java new file mode 100644 index 000000000..80b83a19c --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/SwiftPaymentMethod.java @@ -0,0 +1,445 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.SwiftDetails; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * A SWIFT (international wire) payment method linked to your entity. + */ +@JsonPropertyOrder({ + SwiftPaymentMethod.JSON_PROPERTY_PAYMENT_METHOD_ID, + SwiftPaymentMethod.JSON_PROPERTY_ACTIVE, + SwiftPaymentMethod.JSON_PROPERTY_CREATED_AT, + SwiftPaymentMethod.JSON_PROPERTY_UPDATED_AT, + SwiftPaymentMethod.JSON_PROPERTY_PAYMENT_RAIL, + SwiftPaymentMethod.JSON_PROPERTY_SWIFT +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class SwiftPaymentMethod { + public static final String JSON_PROPERTY_PAYMENT_METHOD_ID = "paymentMethodId"; + @jakarta.annotation.Nonnull + private String paymentMethodId; + + public static final String JSON_PROPERTY_ACTIVE = "active"; + @jakarta.annotation.Nonnull + private Boolean active; + + public static final String JSON_PROPERTY_CREATED_AT = "createdAt"; + @jakarta.annotation.Nonnull + private OffsetDateTime createdAt; + + public static final String JSON_PROPERTY_UPDATED_AT = "updatedAt"; + @jakarta.annotation.Nonnull + private OffsetDateTime updatedAt; + + /** + * The payment rail for this payment method. + */ + public enum PaymentRailEnum { + SWIFT(String.valueOf("swift")); + + private String value; + + PaymentRailEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static PaymentRailEnum fromValue(String value) { + for (PaymentRailEnum b : PaymentRailEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + public static final String JSON_PROPERTY_PAYMENT_RAIL = "paymentRail"; + @jakarta.annotation.Nonnull + private PaymentRailEnum paymentRail; + + public static final String JSON_PROPERTY_SWIFT = "swift"; + @jakarta.annotation.Nonnull + private SwiftDetails swift; + + public SwiftPaymentMethod() { + } + + public SwiftPaymentMethod paymentMethodId(@jakarta.annotation.Nonnull String paymentMethodId) { + this.paymentMethodId = paymentMethodId; + return this; + } + + /** + * The ID of the Payment Method, which is a UUID prefixed by the string `paymentMethod_`. + * @return paymentMethodId + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_PAYMENT_METHOD_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getPaymentMethodId() { + return paymentMethodId; + } + + + @JsonProperty(JSON_PROPERTY_PAYMENT_METHOD_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setPaymentMethodId(@jakarta.annotation.Nonnull String paymentMethodId) { + this.paymentMethodId = paymentMethodId; + } + + + public SwiftPaymentMethod active(@jakarta.annotation.Nonnull Boolean active) { + this.active = active; + return this; + } + + /** + * Whether the payment method is active and can be used in transfers. A payment method may be inactive due to verification requirements or entity-level restrictions. + * @return active + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ACTIVE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public Boolean getActive() { + return active; + } + + + @JsonProperty(JSON_PROPERTY_ACTIVE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setActive(@jakarta.annotation.Nonnull Boolean active) { + this.active = active; + } + + + public SwiftPaymentMethod createdAt(@jakarta.annotation.Nonnull OffsetDateTime createdAt) { + this.createdAt = createdAt; + return this; + } + + /** + * The timestamp when the payment method was created. + * @return createdAt + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_CREATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public OffsetDateTime getCreatedAt() { + return createdAt; + } + + + @JsonProperty(JSON_PROPERTY_CREATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCreatedAt(@jakarta.annotation.Nonnull OffsetDateTime createdAt) { + this.createdAt = createdAt; + } + + + public SwiftPaymentMethod updatedAt(@jakarta.annotation.Nonnull OffsetDateTime updatedAt) { + this.updatedAt = updatedAt; + return this; + } + + /** + * The timestamp when the payment method was last updated. + * @return updatedAt + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_UPDATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public OffsetDateTime getUpdatedAt() { + return updatedAt; + } + + + @JsonProperty(JSON_PROPERTY_UPDATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUpdatedAt(@jakarta.annotation.Nonnull OffsetDateTime updatedAt) { + this.updatedAt = updatedAt; + } + + + public SwiftPaymentMethod paymentRail(@jakarta.annotation.Nonnull PaymentRailEnum paymentRail) { + this.paymentRail = paymentRail; + return this; + } + + /** + * The payment rail for this payment method. + * @return paymentRail + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_PAYMENT_RAIL) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public PaymentRailEnum getPaymentRail() { + return paymentRail; + } + + + @JsonProperty(JSON_PROPERTY_PAYMENT_RAIL) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setPaymentRail(@jakarta.annotation.Nonnull PaymentRailEnum paymentRail) { + this.paymentRail = paymentRail; + } + + + public SwiftPaymentMethod swift(@jakarta.annotation.Nonnull SwiftDetails swift) { + this.swift = swift; + return this; + } + + /** + * SWIFT (international wire) details. + * @return swift + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_SWIFT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public SwiftDetails getSwift() { + return swift; + } + + + @JsonProperty(JSON_PROPERTY_SWIFT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setSwift(@jakarta.annotation.Nonnull SwiftDetails swift) { + this.swift = swift; + } + + + /** + * Return true if this SwiftPaymentMethod object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SwiftPaymentMethod swiftPaymentMethod = (SwiftPaymentMethod) o; + return Objects.equals(this.paymentMethodId, swiftPaymentMethod.paymentMethodId) && + Objects.equals(this.active, swiftPaymentMethod.active) && + Objects.equals(this.createdAt, swiftPaymentMethod.createdAt) && + Objects.equals(this.updatedAt, swiftPaymentMethod.updatedAt) && + Objects.equals(this.paymentRail, swiftPaymentMethod.paymentRail) && + Objects.equals(this.swift, swiftPaymentMethod.swift); + } + + @Override + public int hashCode() { + return Objects.hash(paymentMethodId, active, createdAt, updatedAt, paymentRail, swift); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SwiftPaymentMethod {\n"); + sb.append(" paymentMethodId: ").append(toIndentedString(paymentMethodId)).append("\n"); + sb.append(" active: ").append(toIndentedString(active)).append("\n"); + sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); + sb.append(" updatedAt: ").append(toIndentedString(updatedAt)).append("\n"); + sb.append(" paymentRail: ").append(toIndentedString(paymentRail)).append("\n"); + sb.append(" swift: ").append(toIndentedString(swift)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `paymentMethodId` to the URL query string + if (getPaymentMethodId() != null) { + joiner.add(String.format("%spaymentMethodId%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getPaymentMethodId()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `active` to the URL query string + if (getActive() != null) { + joiner.add(String.format("%sactive%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getActive()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `createdAt` to the URL query string + if (getCreatedAt() != null) { + joiner.add(String.format("%screatedAt%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getCreatedAt()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `updatedAt` to the URL query string + if (getUpdatedAt() != null) { + joiner.add(String.format("%supdatedAt%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getUpdatedAt()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `paymentRail` to the URL query string + if (getPaymentRail() != null) { + joiner.add(String.format("%spaymentRail%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getPaymentRail()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `swift` to the URL query string + if (getSwift() != null) { + joiner.add(getSwift().toUrlQueryString(prefix + "swift" + suffix)); + } + + return joiner.toString(); + } + + public static class Builder { + + private SwiftPaymentMethod instance; + + public Builder() { + this(new SwiftPaymentMethod()); + } + + protected Builder(SwiftPaymentMethod instance) { + this.instance = instance; + } + + public SwiftPaymentMethod.Builder paymentMethodId(String paymentMethodId) { + this.instance.paymentMethodId = paymentMethodId; + return this; + } + public SwiftPaymentMethod.Builder active(Boolean active) { + this.instance.active = active; + return this; + } + public SwiftPaymentMethod.Builder createdAt(OffsetDateTime createdAt) { + this.instance.createdAt = createdAt; + return this; + } + public SwiftPaymentMethod.Builder updatedAt(OffsetDateTime updatedAt) { + this.instance.updatedAt = updatedAt; + return this; + } + public SwiftPaymentMethod.Builder paymentRail(PaymentRailEnum paymentRail) { + this.instance.paymentRail = paymentRail; + return this; + } + public SwiftPaymentMethod.Builder swift(SwiftDetails swift) { + this.instance.swift = swift; + return this; + } + + + /** + * returns a built SwiftPaymentMethod instance. + * + * The builder is not reusable. + */ + public SwiftPaymentMethod build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static SwiftPaymentMethod.Builder builder() { + return new SwiftPaymentMethod.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public SwiftPaymentMethod.Builder toBuilder() { + return new SwiftPaymentMethod.Builder() + .paymentMethodId(getPaymentMethodId()) + .active(getActive()) + .createdAt(getCreatedAt()) + .updatedAt(getUpdatedAt()) + .paymentRail(getPaymentRail()) + .swift(getSwift()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/Transfer.java b/java/src/main/java/com/coinbase/cdp/openapi/model/Transfer.java new file mode 100644 index 000000000..6a282d427 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/Transfer.java @@ -0,0 +1,952 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.Metadata; +import com.coinbase.cdp.openapi.model.TransferDetails; +import com.coinbase.cdp.openapi.model.TransferEstimate; +import com.coinbase.cdp.openapi.model.TransferExchangeRate; +import com.coinbase.cdp.openapi.model.TransferFees; +import com.coinbase.cdp.openapi.model.TransferSource; +import com.coinbase.cdp.openapi.model.TransferStatus; +import com.coinbase.cdp.openapi.model.TransferTarget; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * A Transfer represents all the information needed to execute a transfer and tracks the lifecycle of a transfer from initiation through completion or failure. + */ +@JsonPropertyOrder({ + Transfer.JSON_PROPERTY_TRANSFER_ID, + Transfer.JSON_PROPERTY_STATUS, + Transfer.JSON_PROPERTY_SOURCE, + Transfer.JSON_PROPERTY_TARGET, + Transfer.JSON_PROPERTY_SOURCE_AMOUNT, + Transfer.JSON_PROPERTY_SOURCE_ASSET, + Transfer.JSON_PROPERTY_TARGET_AMOUNT, + Transfer.JSON_PROPERTY_TARGET_ASSET, + Transfer.JSON_PROPERTY_EXCHANGE_RATE, + Transfer.JSON_PROPERTY_FEES, + Transfer.JSON_PROPERTY_ESTIMATE, + Transfer.JSON_PROPERTY_COMPLETED_AT, + Transfer.JSON_PROPERTY_FAILURE_REASON, + Transfer.JSON_PROPERTY_EXPIRES_AT, + Transfer.JSON_PROPERTY_EXECUTED_AT, + Transfer.JSON_PROPERTY_CREATED_AT, + Transfer.JSON_PROPERTY_UPDATED_AT, + Transfer.JSON_PROPERTY_METADATA, + Transfer.JSON_PROPERTY_DETAILS +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class Transfer { + public static final String JSON_PROPERTY_TRANSFER_ID = "transferId"; + @jakarta.annotation.Nullable + private String transferId; + + public static final String JSON_PROPERTY_STATUS = "status"; + @jakarta.annotation.Nullable + private TransferStatus status; + + public static final String JSON_PROPERTY_SOURCE = "source"; + @jakarta.annotation.Nonnull + private TransferSource source; + + public static final String JSON_PROPERTY_TARGET = "target"; + @jakarta.annotation.Nonnull + private TransferTarget target; + + public static final String JSON_PROPERTY_SOURCE_AMOUNT = "sourceAmount"; + @jakarta.annotation.Nullable + private String sourceAmount; + + public static final String JSON_PROPERTY_SOURCE_ASSET = "sourceAsset"; + @jakarta.annotation.Nullable + private String sourceAsset; + + public static final String JSON_PROPERTY_TARGET_AMOUNT = "targetAmount"; + @jakarta.annotation.Nullable + private String targetAmount; + + public static final String JSON_PROPERTY_TARGET_ASSET = "targetAsset"; + @jakarta.annotation.Nullable + private String targetAsset; + + public static final String JSON_PROPERTY_EXCHANGE_RATE = "exchangeRate"; + @jakarta.annotation.Nullable + private TransferExchangeRate exchangeRate; + + public static final String JSON_PROPERTY_FEES = "fees"; + @jakarta.annotation.Nullable + private TransferFees fees = new TransferFees(); + + public static final String JSON_PROPERTY_ESTIMATE = "estimate"; + @jakarta.annotation.Nullable + private TransferEstimate estimate; + + public static final String JSON_PROPERTY_COMPLETED_AT = "completedAt"; + @jakarta.annotation.Nullable + private OffsetDateTime completedAt; + + public static final String JSON_PROPERTY_FAILURE_REASON = "failureReason"; + @jakarta.annotation.Nullable + private String failureReason; + + public static final String JSON_PROPERTY_EXPIRES_AT = "expiresAt"; + @jakarta.annotation.Nullable + private OffsetDateTime expiresAt; + + public static final String JSON_PROPERTY_EXECUTED_AT = "executedAt"; + @jakarta.annotation.Nullable + private OffsetDateTime executedAt; + + public static final String JSON_PROPERTY_CREATED_AT = "createdAt"; + @jakarta.annotation.Nullable + private OffsetDateTime createdAt; + + public static final String JSON_PROPERTY_UPDATED_AT = "updatedAt"; + @jakarta.annotation.Nullable + private OffsetDateTime updatedAt; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private Metadata metadata = new Metadata(); + + public static final String JSON_PROPERTY_DETAILS = "details"; + @jakarta.annotation.Nullable + private TransferDetails details; + + public Transfer() { + } + + public Transfer transferId(@jakarta.annotation.Nullable String transferId) { + this.transferId = transferId; + return this; + } + + /** + * The ID of the transfer. Required when validateOnly is false. + * @return transferId + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_TRANSFER_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getTransferId() { + return transferId; + } + + + @JsonProperty(JSON_PROPERTY_TRANSFER_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setTransferId(@jakarta.annotation.Nullable String transferId) { + this.transferId = transferId; + } + + + public Transfer status(@jakarta.annotation.Nullable TransferStatus status) { + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_STATUS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public TransferStatus getStatus() { + return status; + } + + + @JsonProperty(JSON_PROPERTY_STATUS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setStatus(@jakarta.annotation.Nullable TransferStatus status) { + this.status = status; + } + + + public Transfer source(@jakarta.annotation.Nonnull TransferSource source) { + this.source = source; + return this; + } + + /** + * Get source + * @return source + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_SOURCE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public TransferSource getSource() { + return source; + } + + + @JsonProperty(JSON_PROPERTY_SOURCE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setSource(@jakarta.annotation.Nonnull TransferSource source) { + this.source = source; + } + + + public Transfer target(@jakarta.annotation.Nonnull TransferTarget target) { + this.target = target; + return this; + } + + /** + * Get target + * @return target + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_TARGET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public TransferTarget getTarget() { + return target; + } + + + @JsonProperty(JSON_PROPERTY_TARGET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTarget(@jakarta.annotation.Nonnull TransferTarget target) { + this.target = target; + } + + + public Transfer sourceAmount(@jakarta.annotation.Nullable String sourceAmount) { + this.sourceAmount = sourceAmount; + return this; + } + + /** + * The amount of the source asset that will be transferred out, as a decimal string in standard unit denomination. + * @return sourceAmount + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_SOURCE_AMOUNT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getSourceAmount() { + return sourceAmount; + } + + + @JsonProperty(JSON_PROPERTY_SOURCE_AMOUNT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setSourceAmount(@jakarta.annotation.Nullable String sourceAmount) { + this.sourceAmount = sourceAmount; + } + + + public Transfer sourceAsset(@jakarta.annotation.Nullable String sourceAsset) { + this.sourceAsset = sourceAsset; + return this; + } + + /** + * The asset symbol of the source amount. + * @return sourceAsset + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_SOURCE_ASSET) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getSourceAsset() { + return sourceAsset; + } + + + @JsonProperty(JSON_PROPERTY_SOURCE_ASSET) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setSourceAsset(@jakarta.annotation.Nullable String sourceAsset) { + this.sourceAsset = sourceAsset; + } + + + public Transfer targetAmount(@jakarta.annotation.Nullable String targetAmount) { + this.targetAmount = targetAmount; + return this; + } + + /** + * The amount of the target asset that will be received, as a decimal string in standard unit denomination. + * @return targetAmount + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_TARGET_AMOUNT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getTargetAmount() { + return targetAmount; + } + + + @JsonProperty(JSON_PROPERTY_TARGET_AMOUNT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setTargetAmount(@jakarta.annotation.Nullable String targetAmount) { + this.targetAmount = targetAmount; + } + + + public Transfer targetAsset(@jakarta.annotation.Nullable String targetAsset) { + this.targetAsset = targetAsset; + return this; + } + + /** + * The asset symbol of the target amount. + * @return targetAsset + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_TARGET_ASSET) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getTargetAsset() { + return targetAsset; + } + + + @JsonProperty(JSON_PROPERTY_TARGET_ASSET) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setTargetAsset(@jakarta.annotation.Nullable String targetAsset) { + this.targetAsset = targetAsset; + } + + + public Transfer exchangeRate(@jakarta.annotation.Nullable TransferExchangeRate exchangeRate) { + this.exchangeRate = exchangeRate; + return this; + } + + /** + * Get exchangeRate + * @return exchangeRate + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_EXCHANGE_RATE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public TransferExchangeRate getExchangeRate() { + return exchangeRate; + } + + + @JsonProperty(JSON_PROPERTY_EXCHANGE_RATE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setExchangeRate(@jakarta.annotation.Nullable TransferExchangeRate exchangeRate) { + this.exchangeRate = exchangeRate; + } + + + public Transfer fees(@jakarta.annotation.Nullable TransferFees fees) { + this.fees = fees; + return this; + } + + /** + * Get fees + * @return fees + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_FEES) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public TransferFees getFees() { + return fees; + } + + + @JsonProperty(JSON_PROPERTY_FEES) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setFees(@jakarta.annotation.Nullable TransferFees fees) { + this.fees = fees; + } + + + public Transfer estimate(@jakarta.annotation.Nullable TransferEstimate estimate) { + this.estimate = estimate; + return this; + } + + /** + * Get estimate + * @return estimate + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ESTIMATE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public TransferEstimate getEstimate() { + return estimate; + } + + + @JsonProperty(JSON_PROPERTY_ESTIMATE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setEstimate(@jakarta.annotation.Nullable TransferEstimate estimate) { + this.estimate = estimate; + } + + + public Transfer completedAt(@jakarta.annotation.Nullable OffsetDateTime completedAt) { + this.completedAt = completedAt; + return this; + } + + /** + * The date and time the transfer was completed. + * @return completedAt + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_COMPLETED_AT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public OffsetDateTime getCompletedAt() { + return completedAt; + } + + + @JsonProperty(JSON_PROPERTY_COMPLETED_AT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setCompletedAt(@jakarta.annotation.Nullable OffsetDateTime completedAt) { + this.completedAt = completedAt; + } + + + public Transfer failureReason(@jakarta.annotation.Nullable String failureReason) { + this.failureReason = failureReason; + return this; + } + + /** + * The reason for failure, if the transfer failed. Only present when status is `failed`. + * @return failureReason + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_FAILURE_REASON) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getFailureReason() { + return failureReason; + } + + + @JsonProperty(JSON_PROPERTY_FAILURE_REASON) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setFailureReason(@jakarta.annotation.Nullable String failureReason) { + this.failureReason = failureReason; + } + + + public Transfer expiresAt(@jakarta.annotation.Nullable OffsetDateTime expiresAt) { + this.expiresAt = expiresAt; + return this; + } + + /** + * The date and time when this transfer will expire if not executed. Only present for `quoted` status. A new transfer must be created to obtain an updated quote after expiration. Required when validateOnly is false. + * @return expiresAt + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_EXPIRES_AT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public OffsetDateTime getExpiresAt() { + return expiresAt; + } + + + @JsonProperty(JSON_PROPERTY_EXPIRES_AT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setExpiresAt(@jakarta.annotation.Nullable OffsetDateTime expiresAt) { + this.expiresAt = expiresAt; + } + + + public Transfer executedAt(@jakarta.annotation.Nullable OffsetDateTime executedAt) { + this.executedAt = executedAt; + return this; + } + + /** + * The date and time the transfer was executed and moved to processing. Only present when status has progressed beyond `quoted`. + * @return executedAt + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_EXECUTED_AT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public OffsetDateTime getExecutedAt() { + return executedAt; + } + + + @JsonProperty(JSON_PROPERTY_EXECUTED_AT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setExecutedAt(@jakarta.annotation.Nullable OffsetDateTime executedAt) { + this.executedAt = executedAt; + } + + + public Transfer createdAt(@jakarta.annotation.Nullable OffsetDateTime createdAt) { + this.createdAt = createdAt; + return this; + } + + /** + * The date and time the transfer was created. Required when validateOnly is false. + * @return createdAt + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_CREATED_AT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public OffsetDateTime getCreatedAt() { + return createdAt; + } + + + @JsonProperty(JSON_PROPERTY_CREATED_AT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setCreatedAt(@jakarta.annotation.Nullable OffsetDateTime createdAt) { + this.createdAt = createdAt; + } + + + public Transfer updatedAt(@jakarta.annotation.Nullable OffsetDateTime updatedAt) { + this.updatedAt = updatedAt; + return this; + } + + /** + * The date and time the transfer was last updated. Required when validateOnly is false. + * @return updatedAt + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_UPDATED_AT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public OffsetDateTime getUpdatedAt() { + return updatedAt; + } + + + @JsonProperty(JSON_PROPERTY_UPDATED_AT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setUpdatedAt(@jakarta.annotation.Nullable OffsetDateTime updatedAt) { + this.updatedAt = updatedAt; + } + + + public Transfer metadata(@jakarta.annotation.Nullable Metadata metadata) { + this.metadata = metadata; + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_METADATA) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public Metadata getMetadata() { + return metadata; + } + + + @JsonProperty(JSON_PROPERTY_METADATA) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setMetadata(@jakarta.annotation.Nullable Metadata metadata) { + this.metadata = metadata; + } + + + public Transfer details(@jakarta.annotation.Nullable TransferDetails details) { + this.details = details; + return this; + } + + /** + * Get details + * @return details + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_DETAILS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public TransferDetails getDetails() { + return details; + } + + + @JsonProperty(JSON_PROPERTY_DETAILS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setDetails(@jakarta.annotation.Nullable TransferDetails details) { + this.details = details; + } + + + /** + * Return true if this Transfer object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Transfer transfer = (Transfer) o; + return Objects.equals(this.transferId, transfer.transferId) && + Objects.equals(this.status, transfer.status) && + Objects.equals(this.source, transfer.source) && + Objects.equals(this.target, transfer.target) && + Objects.equals(this.sourceAmount, transfer.sourceAmount) && + Objects.equals(this.sourceAsset, transfer.sourceAsset) && + Objects.equals(this.targetAmount, transfer.targetAmount) && + Objects.equals(this.targetAsset, transfer.targetAsset) && + Objects.equals(this.exchangeRate, transfer.exchangeRate) && + Objects.equals(this.fees, transfer.fees) && + Objects.equals(this.estimate, transfer.estimate) && + Objects.equals(this.completedAt, transfer.completedAt) && + Objects.equals(this.failureReason, transfer.failureReason) && + Objects.equals(this.expiresAt, transfer.expiresAt) && + Objects.equals(this.executedAt, transfer.executedAt) && + Objects.equals(this.createdAt, transfer.createdAt) && + Objects.equals(this.updatedAt, transfer.updatedAt) && + Objects.equals(this.metadata, transfer.metadata) && + Objects.equals(this.details, transfer.details); + } + + @Override + public int hashCode() { + return Objects.hash(transferId, status, source, target, sourceAmount, sourceAsset, targetAmount, targetAsset, exchangeRate, fees, estimate, completedAt, failureReason, expiresAt, executedAt, createdAt, updatedAt, metadata, details); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Transfer {\n"); + sb.append(" transferId: ").append(toIndentedString(transferId)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" source: ").append(toIndentedString(source)).append("\n"); + sb.append(" target: ").append(toIndentedString(target)).append("\n"); + sb.append(" sourceAmount: ").append(toIndentedString(sourceAmount)).append("\n"); + sb.append(" sourceAsset: ").append(toIndentedString(sourceAsset)).append("\n"); + sb.append(" targetAmount: ").append(toIndentedString(targetAmount)).append("\n"); + sb.append(" targetAsset: ").append(toIndentedString(targetAsset)).append("\n"); + sb.append(" exchangeRate: ").append(toIndentedString(exchangeRate)).append("\n"); + sb.append(" fees: ").append(toIndentedString(fees)).append("\n"); + sb.append(" estimate: ").append(toIndentedString(estimate)).append("\n"); + sb.append(" completedAt: ").append(toIndentedString(completedAt)).append("\n"); + sb.append(" failureReason: ").append(toIndentedString(failureReason)).append("\n"); + sb.append(" expiresAt: ").append(toIndentedString(expiresAt)).append("\n"); + sb.append(" executedAt: ").append(toIndentedString(executedAt)).append("\n"); + sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); + sb.append(" updatedAt: ").append(toIndentedString(updatedAt)).append("\n"); + sb.append(" metadata: ").append(toIndentedString(metadata)).append("\n"); + sb.append(" details: ").append(toIndentedString(details)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `transferId` to the URL query string + if (getTransferId() != null) { + joiner.add(String.format("%stransferId%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getTransferId()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `status` to the URL query string + if (getStatus() != null) { + joiner.add(String.format("%sstatus%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getStatus()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `source` to the URL query string + if (getSource() != null) { + joiner.add(getSource().toUrlQueryString(prefix + "source" + suffix)); + } + + // add `target` to the URL query string + if (getTarget() != null) { + joiner.add(getTarget().toUrlQueryString(prefix + "target" + suffix)); + } + + // add `sourceAmount` to the URL query string + if (getSourceAmount() != null) { + joiner.add(String.format("%ssourceAmount%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getSourceAmount()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `sourceAsset` to the URL query string + if (getSourceAsset() != null) { + joiner.add(String.format("%ssourceAsset%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getSourceAsset()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `targetAmount` to the URL query string + if (getTargetAmount() != null) { + joiner.add(String.format("%stargetAmount%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getTargetAmount()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `targetAsset` to the URL query string + if (getTargetAsset() != null) { + joiner.add(String.format("%stargetAsset%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getTargetAsset()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `exchangeRate` to the URL query string + if (getExchangeRate() != null) { + joiner.add(getExchangeRate().toUrlQueryString(prefix + "exchangeRate" + suffix)); + } + + // add `fees` to the URL query string + if (getFees() != null) { + joiner.add(String.format("%sfees%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getFees()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `estimate` to the URL query string + if (getEstimate() != null) { + joiner.add(getEstimate().toUrlQueryString(prefix + "estimate" + suffix)); + } + + // add `completedAt` to the URL query string + if (getCompletedAt() != null) { + joiner.add(String.format("%scompletedAt%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getCompletedAt()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `failureReason` to the URL query string + if (getFailureReason() != null) { + joiner.add(String.format("%sfailureReason%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getFailureReason()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `expiresAt` to the URL query string + if (getExpiresAt() != null) { + joiner.add(String.format("%sexpiresAt%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getExpiresAt()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `executedAt` to the URL query string + if (getExecutedAt() != null) { + joiner.add(String.format("%sexecutedAt%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getExecutedAt()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `createdAt` to the URL query string + if (getCreatedAt() != null) { + joiner.add(String.format("%screatedAt%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getCreatedAt()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `updatedAt` to the URL query string + if (getUpdatedAt() != null) { + joiner.add(String.format("%supdatedAt%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getUpdatedAt()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `metadata` to the URL query string + if (getMetadata() != null) { + joiner.add(String.format("%smetadata%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getMetadata()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `details` to the URL query string + if (getDetails() != null) { + joiner.add(getDetails().toUrlQueryString(prefix + "details" + suffix)); + } + + return joiner.toString(); + } + + public static class Builder { + + private Transfer instance; + + public Builder() { + this(new Transfer()); + } + + protected Builder(Transfer instance) { + this.instance = instance; + } + + public Transfer.Builder transferId(String transferId) { + this.instance.transferId = transferId; + return this; + } + public Transfer.Builder status(TransferStatus status) { + this.instance.status = status; + return this; + } + public Transfer.Builder source(TransferSource source) { + this.instance.source = source; + return this; + } + public Transfer.Builder target(TransferTarget target) { + this.instance.target = target; + return this; + } + public Transfer.Builder sourceAmount(String sourceAmount) { + this.instance.sourceAmount = sourceAmount; + return this; + } + public Transfer.Builder sourceAsset(String sourceAsset) { + this.instance.sourceAsset = sourceAsset; + return this; + } + public Transfer.Builder targetAmount(String targetAmount) { + this.instance.targetAmount = targetAmount; + return this; + } + public Transfer.Builder targetAsset(String targetAsset) { + this.instance.targetAsset = targetAsset; + return this; + } + public Transfer.Builder exchangeRate(TransferExchangeRate exchangeRate) { + this.instance.exchangeRate = exchangeRate; + return this; + } + public Transfer.Builder fees(TransferFees fees) { + this.instance.fees = fees; + return this; + } + public Transfer.Builder estimate(TransferEstimate estimate) { + this.instance.estimate = estimate; + return this; + } + public Transfer.Builder completedAt(OffsetDateTime completedAt) { + this.instance.completedAt = completedAt; + return this; + } + public Transfer.Builder failureReason(String failureReason) { + this.instance.failureReason = failureReason; + return this; + } + public Transfer.Builder expiresAt(OffsetDateTime expiresAt) { + this.instance.expiresAt = expiresAt; + return this; + } + public Transfer.Builder executedAt(OffsetDateTime executedAt) { + this.instance.executedAt = executedAt; + return this; + } + public Transfer.Builder createdAt(OffsetDateTime createdAt) { + this.instance.createdAt = createdAt; + return this; + } + public Transfer.Builder updatedAt(OffsetDateTime updatedAt) { + this.instance.updatedAt = updatedAt; + return this; + } + public Transfer.Builder metadata(Metadata metadata) { + this.instance.metadata = metadata; + return this; + } + public Transfer.Builder details(TransferDetails details) { + this.instance.details = details; + return this; + } + + + /** + * returns a built Transfer instance. + * + * The builder is not reusable. + */ + public Transfer build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static Transfer.Builder builder() { + return new Transfer.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public Transfer.Builder toBuilder() { + return new Transfer.Builder() + .transferId(getTransferId()) + .status(getStatus()) + .source(getSource()) + .target(getTarget()) + .sourceAmount(getSourceAmount()) + .sourceAsset(getSourceAsset()) + .targetAmount(getTargetAmount()) + .targetAsset(getTargetAsset()) + .exchangeRate(getExchangeRate()) + .fees(getFees()) + .estimate(getEstimate()) + .completedAt(getCompletedAt()) + .failureReason(getFailureReason()) + .expiresAt(getExpiresAt()) + .executedAt(getExecutedAt()) + .createdAt(getCreatedAt()) + .updatedAt(getUpdatedAt()) + .metadata(getMetadata()) + .details(getDetails()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/TransferDetails.java b/java/src/main/java/com/coinbase/cdp/openapi/model/TransferDetails.java new file mode 100644 index 000000000..5444d7796 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/TransferDetails.java @@ -0,0 +1,305 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.DepositDestinationReference; +import com.coinbase.cdp.openapi.model.TransferDetailsOnchainTransactionsInner; +import com.coinbase.cdp.openapi.model.TransferDetailsTravelRule; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * Additional details about the transfer. For example, if the transfer was sent to a deposit destination, the information about that destination will be included in this field. + */ +@JsonPropertyOrder({ + TransferDetails.JSON_PROPERTY_DEPOSIT_DESTINATION, + TransferDetails.JSON_PROPERTY_ONCHAIN_TRANSACTIONS, + TransferDetails.JSON_PROPERTY_TRAVEL_RULE +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class TransferDetails { + public static final String JSON_PROPERTY_DEPOSIT_DESTINATION = "depositDestination"; + @jakarta.annotation.Nullable + private DepositDestinationReference depositDestination; + + public static final String JSON_PROPERTY_ONCHAIN_TRANSACTIONS = "onchainTransactions"; + @jakarta.annotation.Nullable + private List onchainTransactions = new ArrayList<>(); + + public static final String JSON_PROPERTY_TRAVEL_RULE = "travelRule"; + @jakarta.annotation.Nullable + private TransferDetailsTravelRule travelRule; + + public TransferDetails() { + } + + public TransferDetails depositDestination(@jakarta.annotation.Nullable DepositDestinationReference depositDestination) { + this.depositDestination = depositDestination; + return this; + } + + /** + * Get depositDestination + * @return depositDestination + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_DEPOSIT_DESTINATION) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public DepositDestinationReference getDepositDestination() { + return depositDestination; + } + + + @JsonProperty(JSON_PROPERTY_DEPOSIT_DESTINATION) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setDepositDestination(@jakarta.annotation.Nullable DepositDestinationReference depositDestination) { + this.depositDestination = depositDestination; + } + + + public TransferDetails onchainTransactions(@jakarta.annotation.Nullable List onchainTransactions) { + this.onchainTransactions = onchainTransactions; + return this; + } + + public TransferDetails addOnchainTransactionsItem(TransferDetailsOnchainTransactionsInner onchainTransactionsItem) { + if (this.onchainTransactions == null) { + this.onchainTransactions = new ArrayList<>(); + } + this.onchainTransactions.add(onchainTransactionsItem); + return this; + } + + /** + * The onchain transactions associated with the transfer. + * @return onchainTransactions + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ONCHAIN_TRANSACTIONS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public List getOnchainTransactions() { + return onchainTransactions; + } + + + @JsonProperty(JSON_PROPERTY_ONCHAIN_TRANSACTIONS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setOnchainTransactions(@jakarta.annotation.Nullable List onchainTransactions) { + this.onchainTransactions = onchainTransactions; + } + + + public TransferDetails travelRule(@jakarta.annotation.Nullable TransferDetailsTravelRule travelRule) { + this.travelRule = travelRule; + return this; + } + + /** + * Get travelRule + * @return travelRule + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_TRAVEL_RULE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public TransferDetailsTravelRule getTravelRule() { + return travelRule; + } + + + @JsonProperty(JSON_PROPERTY_TRAVEL_RULE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setTravelRule(@jakarta.annotation.Nullable TransferDetailsTravelRule travelRule) { + this.travelRule = travelRule; + } + + + /** + * Return true if this TransferDetails object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TransferDetails transferDetails = (TransferDetails) o; + return Objects.equals(this.depositDestination, transferDetails.depositDestination) && + Objects.equals(this.onchainTransactions, transferDetails.onchainTransactions) && + Objects.equals(this.travelRule, transferDetails.travelRule); + } + + @Override + public int hashCode() { + return Objects.hash(depositDestination, onchainTransactions, travelRule); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TransferDetails {\n"); + sb.append(" depositDestination: ").append(toIndentedString(depositDestination)).append("\n"); + sb.append(" onchainTransactions: ").append(toIndentedString(onchainTransactions)).append("\n"); + sb.append(" travelRule: ").append(toIndentedString(travelRule)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `depositDestination` to the URL query string + if (getDepositDestination() != null) { + joiner.add(getDepositDestination().toUrlQueryString(prefix + "depositDestination" + suffix)); + } + + // add `onchainTransactions` to the URL query string + if (getOnchainTransactions() != null) { + for (int i = 0; i < getOnchainTransactions().size(); i++) { + if (getOnchainTransactions().get(i) != null) { + joiner.add(getOnchainTransactions().get(i).toUrlQueryString(String.format("%sonchainTransactions%s%s", prefix, suffix, + "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, i, containerSuffix)))); + } + } + } + + // add `travelRule` to the URL query string + if (getTravelRule() != null) { + joiner.add(getTravelRule().toUrlQueryString(prefix + "travelRule" + suffix)); + } + + return joiner.toString(); + } + + public static class Builder { + + private TransferDetails instance; + + public Builder() { + this(new TransferDetails()); + } + + protected Builder(TransferDetails instance) { + this.instance = instance; + } + + public TransferDetails.Builder depositDestination(DepositDestinationReference depositDestination) { + this.instance.depositDestination = depositDestination; + return this; + } + public TransferDetails.Builder onchainTransactions(List onchainTransactions) { + this.instance.onchainTransactions = onchainTransactions; + return this; + } + public TransferDetails.Builder travelRule(TransferDetailsTravelRule travelRule) { + this.instance.travelRule = travelRule; + return this; + } + + + /** + * returns a built TransferDetails instance. + * + * The builder is not reusable. + */ + public TransferDetails build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static TransferDetails.Builder builder() { + return new TransferDetails.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public TransferDetails.Builder toBuilder() { + return new TransferDetails.Builder() + .depositDestination(getDepositDestination()) + .onchainTransactions(getOnchainTransactions()) + .travelRule(getTravelRule()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/TransferDetailsOnchainTransactionsInner.java b/java/src/main/java/com/coinbase/cdp/openapi/model/TransferDetailsOnchainTransactionsInner.java new file mode 100644 index 000000000..f0e64499d --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/TransferDetailsOnchainTransactionsInner.java @@ -0,0 +1,247 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.Network; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * An onchain transaction associated with the transfer. + */ +@JsonPropertyOrder({ + TransferDetailsOnchainTransactionsInner.JSON_PROPERTY_TRANSACTION_HASH, + TransferDetailsOnchainTransactionsInner.JSON_PROPERTY_NETWORK +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class TransferDetailsOnchainTransactionsInner { + public static final String JSON_PROPERTY_TRANSACTION_HASH = "transactionHash"; + @jakarta.annotation.Nonnull + private String transactionHash; + + public static final String JSON_PROPERTY_NETWORK = "network"; + @jakarta.annotation.Nonnull + private Network network; + + public TransferDetailsOnchainTransactionsInner() { + } + + public TransferDetailsOnchainTransactionsInner transactionHash(@jakarta.annotation.Nonnull String transactionHash) { + this.transactionHash = transactionHash; + return this; + } + + /** + * The transaction hash. + * @return transactionHash + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_TRANSACTION_HASH) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getTransactionHash() { + return transactionHash; + } + + + @JsonProperty(JSON_PROPERTY_TRANSACTION_HASH) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTransactionHash(@jakarta.annotation.Nonnull String transactionHash) { + this.transactionHash = transactionHash; + } + + + public TransferDetailsOnchainTransactionsInner network(@jakarta.annotation.Nonnull Network network) { + this.network = network; + return this; + } + + /** + * Get network + * @return network + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_NETWORK) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public Network getNetwork() { + return network; + } + + + @JsonProperty(JSON_PROPERTY_NETWORK) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNetwork(@jakarta.annotation.Nonnull Network network) { + this.network = network; + } + + + /** + * Return true if this TransferDetails_onchainTransactions_inner object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TransferDetailsOnchainTransactionsInner transferDetailsOnchainTransactionsInner = (TransferDetailsOnchainTransactionsInner) o; + return Objects.equals(this.transactionHash, transferDetailsOnchainTransactionsInner.transactionHash) && + Objects.equals(this.network, transferDetailsOnchainTransactionsInner.network); + } + + @Override + public int hashCode() { + return Objects.hash(transactionHash, network); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TransferDetailsOnchainTransactionsInner {\n"); + sb.append(" transactionHash: ").append(toIndentedString(transactionHash)).append("\n"); + sb.append(" network: ").append(toIndentedString(network)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `transactionHash` to the URL query string + if (getTransactionHash() != null) { + joiner.add(String.format("%stransactionHash%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getTransactionHash()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `network` to the URL query string + if (getNetwork() != null) { + joiner.add(String.format("%snetwork%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getNetwork()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private TransferDetailsOnchainTransactionsInner instance; + + public Builder() { + this(new TransferDetailsOnchainTransactionsInner()); + } + + protected Builder(TransferDetailsOnchainTransactionsInner instance) { + this.instance = instance; + } + + public TransferDetailsOnchainTransactionsInner.Builder transactionHash(String transactionHash) { + this.instance.transactionHash = transactionHash; + return this; + } + public TransferDetailsOnchainTransactionsInner.Builder network(Network network) { + this.instance.network = network; + return this; + } + + + /** + * returns a built TransferDetailsOnchainTransactionsInner instance. + * + * The builder is not reusable. + */ + public TransferDetailsOnchainTransactionsInner build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static TransferDetailsOnchainTransactionsInner.Builder builder() { + return new TransferDetailsOnchainTransactionsInner.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public TransferDetailsOnchainTransactionsInner.Builder toBuilder() { + return new TransferDetailsOnchainTransactionsInner.Builder() + .transactionHash(getTransactionHash()) + .network(getNetwork()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/TransferDetailsTravelRule.java b/java/src/main/java/com/coinbase/cdp/openapi/model/TransferDetailsTravelRule.java new file mode 100644 index 000000000..6a8d7cafa --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/TransferDetailsTravelRule.java @@ -0,0 +1,247 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.TravelRuleStatus; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * Travel rule compliance status for deposit transfers. Present when the transfer requires travel rule information. + */ +@JsonPropertyOrder({ + TransferDetailsTravelRule.JSON_PROPERTY_STATUS, + TransferDetailsTravelRule.JSON_PROPERTY_STATUS_MESSAGE +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class TransferDetailsTravelRule { + public static final String JSON_PROPERTY_STATUS = "status"; + @jakarta.annotation.Nullable + private TravelRuleStatus status; + + public static final String JSON_PROPERTY_STATUS_MESSAGE = "statusMessage"; + @jakarta.annotation.Nullable + private String statusMessage; + + public TransferDetailsTravelRule() { + } + + public TransferDetailsTravelRule status(@jakarta.annotation.Nullable TravelRuleStatus status) { + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_STATUS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public TravelRuleStatus getStatus() { + return status; + } + + + @JsonProperty(JSON_PROPERTY_STATUS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setStatus(@jakarta.annotation.Nullable TravelRuleStatus status) { + this.status = status; + } + + + public TransferDetailsTravelRule statusMessage(@jakarta.annotation.Nullable String statusMessage) { + this.statusMessage = statusMessage; + return this; + } + + /** + * Additional details about the current travel rule status. For example, when status is `incomplete`, this may indicate the specific missing information required to proceed. + * @return statusMessage + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_STATUS_MESSAGE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getStatusMessage() { + return statusMessage; + } + + + @JsonProperty(JSON_PROPERTY_STATUS_MESSAGE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setStatusMessage(@jakarta.annotation.Nullable String statusMessage) { + this.statusMessage = statusMessage; + } + + + /** + * Return true if this TransferDetails_travelRule object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TransferDetailsTravelRule transferDetailsTravelRule = (TransferDetailsTravelRule) o; + return Objects.equals(this.status, transferDetailsTravelRule.status) && + Objects.equals(this.statusMessage, transferDetailsTravelRule.statusMessage); + } + + @Override + public int hashCode() { + return Objects.hash(status, statusMessage); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TransferDetailsTravelRule {\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" statusMessage: ").append(toIndentedString(statusMessage)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `status` to the URL query string + if (getStatus() != null) { + joiner.add(String.format("%sstatus%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getStatus()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `statusMessage` to the URL query string + if (getStatusMessage() != null) { + joiner.add(String.format("%sstatusMessage%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getStatusMessage()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private TransferDetailsTravelRule instance; + + public Builder() { + this(new TransferDetailsTravelRule()); + } + + protected Builder(TransferDetailsTravelRule instance) { + this.instance = instance; + } + + public TransferDetailsTravelRule.Builder status(TravelRuleStatus status) { + this.instance.status = status; + return this; + } + public TransferDetailsTravelRule.Builder statusMessage(String statusMessage) { + this.instance.statusMessage = statusMessage; + return this; + } + + + /** + * returns a built TransferDetailsTravelRule instance. + * + * The builder is not reusable. + */ + public TransferDetailsTravelRule build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static TransferDetailsTravelRule.Builder builder() { + return new TransferDetailsTravelRule.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public TransferDetailsTravelRule.Builder toBuilder() { + return new TransferDetailsTravelRule.Builder() + .status(getStatus()) + .statusMessage(getStatusMessage()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/TransferEstimate.java b/java/src/main/java/com/coinbase/cdp/openapi/model/TransferEstimate.java new file mode 100644 index 000000000..544175f72 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/TransferEstimate.java @@ -0,0 +1,372 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.TransferExchangeRate; +import com.coinbase.cdp.openapi.model.TransferFees; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * A point-in-time snapshot of estimated values for a transfer where exact amounts cannot be locked in at quote time (e.g., when the executed rate is determined at execution time and moves with the market). Present in both pre-execution and post-execution states: * **Quoted state:** top-level fields whose values cannot be guaranteed are absent; `estimate` holds their estimated values. * **Completed state:** top-level fields contain the actual executed values; `estimate` is retained as an immutable audit snapshot of the pre-execution estimate. + */ +@JsonPropertyOrder({ + TransferEstimate.JSON_PROPERTY_EXCHANGE_RATE, + TransferEstimate.JSON_PROPERTY_TARGET_AMOUNT, + TransferEstimate.JSON_PROPERTY_TARGET_ASSET, + TransferEstimate.JSON_PROPERTY_FEES, + TransferEstimate.JSON_PROPERTY_ESTIMATED_AT +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class TransferEstimate { + public static final String JSON_PROPERTY_EXCHANGE_RATE = "exchangeRate"; + @jakarta.annotation.Nullable + private TransferExchangeRate exchangeRate; + + public static final String JSON_PROPERTY_TARGET_AMOUNT = "targetAmount"; + @jakarta.annotation.Nullable + private String targetAmount; + + public static final String JSON_PROPERTY_TARGET_ASSET = "targetAsset"; + @jakarta.annotation.Nullable + private String targetAsset; + + public static final String JSON_PROPERTY_FEES = "fees"; + @jakarta.annotation.Nullable + private TransferFees fees = new TransferFees(); + + public static final String JSON_PROPERTY_ESTIMATED_AT = "estimatedAt"; + @jakarta.annotation.Nonnull + private OffsetDateTime estimatedAt; + + public TransferEstimate() { + } + + public TransferEstimate exchangeRate(@jakarta.annotation.Nullable TransferExchangeRate exchangeRate) { + this.exchangeRate = exchangeRate; + return this; + } + + /** + * Get exchangeRate + * @return exchangeRate + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_EXCHANGE_RATE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public TransferExchangeRate getExchangeRate() { + return exchangeRate; + } + + + @JsonProperty(JSON_PROPERTY_EXCHANGE_RATE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setExchangeRate(@jakarta.annotation.Nullable TransferExchangeRate exchangeRate) { + this.exchangeRate = exchangeRate; + } + + + public TransferEstimate targetAmount(@jakarta.annotation.Nullable String targetAmount) { + this.targetAmount = targetAmount; + return this; + } + + /** + * Estimated amount of the target asset that will be received, as a decimal string in standard unit denomination. + * @return targetAmount + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_TARGET_AMOUNT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getTargetAmount() { + return targetAmount; + } + + + @JsonProperty(JSON_PROPERTY_TARGET_AMOUNT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setTargetAmount(@jakarta.annotation.Nullable String targetAmount) { + this.targetAmount = targetAmount; + } + + + public TransferEstimate targetAsset(@jakarta.annotation.Nullable String targetAsset) { + this.targetAsset = targetAsset; + return this; + } + + /** + * The asset symbol of the estimated target amount. + * @return targetAsset + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_TARGET_ASSET) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getTargetAsset() { + return targetAsset; + } + + + @JsonProperty(JSON_PROPERTY_TARGET_ASSET) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setTargetAsset(@jakarta.annotation.Nullable String targetAsset) { + this.targetAsset = targetAsset; + } + + + public TransferEstimate fees(@jakarta.annotation.Nullable TransferFees fees) { + this.fees = fees; + return this; + } + + /** + * Get fees + * @return fees + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_FEES) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public TransferFees getFees() { + return fees; + } + + + @JsonProperty(JSON_PROPERTY_FEES) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setFees(@jakarta.annotation.Nullable TransferFees fees) { + this.fees = fees; + } + + + public TransferEstimate estimatedAt(@jakarta.annotation.Nonnull OffsetDateTime estimatedAt) { + this.estimatedAt = estimatedAt; + return this; + } + + /** + * The date and time when this estimate was captured. + * @return estimatedAt + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ESTIMATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public OffsetDateTime getEstimatedAt() { + return estimatedAt; + } + + + @JsonProperty(JSON_PROPERTY_ESTIMATED_AT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEstimatedAt(@jakarta.annotation.Nonnull OffsetDateTime estimatedAt) { + this.estimatedAt = estimatedAt; + } + + + /** + * Return true if this TransferEstimate object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TransferEstimate transferEstimate = (TransferEstimate) o; + return Objects.equals(this.exchangeRate, transferEstimate.exchangeRate) && + Objects.equals(this.targetAmount, transferEstimate.targetAmount) && + Objects.equals(this.targetAsset, transferEstimate.targetAsset) && + Objects.equals(this.fees, transferEstimate.fees) && + Objects.equals(this.estimatedAt, transferEstimate.estimatedAt); + } + + @Override + public int hashCode() { + return Objects.hash(exchangeRate, targetAmount, targetAsset, fees, estimatedAt); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TransferEstimate {\n"); + sb.append(" exchangeRate: ").append(toIndentedString(exchangeRate)).append("\n"); + sb.append(" targetAmount: ").append(toIndentedString(targetAmount)).append("\n"); + sb.append(" targetAsset: ").append(toIndentedString(targetAsset)).append("\n"); + sb.append(" fees: ").append(toIndentedString(fees)).append("\n"); + sb.append(" estimatedAt: ").append(toIndentedString(estimatedAt)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `exchangeRate` to the URL query string + if (getExchangeRate() != null) { + joiner.add(getExchangeRate().toUrlQueryString(prefix + "exchangeRate" + suffix)); + } + + // add `targetAmount` to the URL query string + if (getTargetAmount() != null) { + joiner.add(String.format("%stargetAmount%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getTargetAmount()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `targetAsset` to the URL query string + if (getTargetAsset() != null) { + joiner.add(String.format("%stargetAsset%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getTargetAsset()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `fees` to the URL query string + if (getFees() != null) { + joiner.add(String.format("%sfees%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getFees()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `estimatedAt` to the URL query string + if (getEstimatedAt() != null) { + joiner.add(String.format("%sestimatedAt%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getEstimatedAt()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private TransferEstimate instance; + + public Builder() { + this(new TransferEstimate()); + } + + protected Builder(TransferEstimate instance) { + this.instance = instance; + } + + public TransferEstimate.Builder exchangeRate(TransferExchangeRate exchangeRate) { + this.instance.exchangeRate = exchangeRate; + return this; + } + public TransferEstimate.Builder targetAmount(String targetAmount) { + this.instance.targetAmount = targetAmount; + return this; + } + public TransferEstimate.Builder targetAsset(String targetAsset) { + this.instance.targetAsset = targetAsset; + return this; + } + public TransferEstimate.Builder fees(TransferFees fees) { + this.instance.fees = fees; + return this; + } + public TransferEstimate.Builder estimatedAt(OffsetDateTime estimatedAt) { + this.instance.estimatedAt = estimatedAt; + return this; + } + + + /** + * returns a built TransferEstimate instance. + * + * The builder is not reusable. + */ + public TransferEstimate build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static TransferEstimate.Builder builder() { + return new TransferEstimate.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public TransferEstimate.Builder toBuilder() { + return new TransferEstimate.Builder() + .exchangeRate(getExchangeRate()) + .targetAmount(getTargetAmount()) + .targetAsset(getTargetAsset()) + .fees(getFees()) + .estimatedAt(getEstimatedAt()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/TransferExchangeRate.java b/java/src/main/java/com/coinbase/cdp/openapi/model/TransferExchangeRate.java new file mode 100644 index 000000000..6d4073fbb --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/TransferExchangeRate.java @@ -0,0 +1,287 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * Exchange rate information for currency conversion. The rate indicates how much of the target asset is equivalent to one unit of the source asset. + */ +@JsonPropertyOrder({ + TransferExchangeRate.JSON_PROPERTY_SOURCE_ASSET, + TransferExchangeRate.JSON_PROPERTY_TARGET_ASSET, + TransferExchangeRate.JSON_PROPERTY_RATE +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class TransferExchangeRate { + public static final String JSON_PROPERTY_SOURCE_ASSET = "sourceAsset"; + @jakarta.annotation.Nonnull + private String sourceAsset; + + public static final String JSON_PROPERTY_TARGET_ASSET = "targetAsset"; + @jakarta.annotation.Nonnull + private String targetAsset; + + public static final String JSON_PROPERTY_RATE = "rate"; + @jakarta.annotation.Nonnull + private String rate; + + public TransferExchangeRate() { + } + + public TransferExchangeRate sourceAsset(@jakarta.annotation.Nonnull String sourceAsset) { + this.sourceAsset = sourceAsset; + return this; + } + + /** + * The asset being converted from. + * @return sourceAsset + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_SOURCE_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getSourceAsset() { + return sourceAsset; + } + + + @JsonProperty(JSON_PROPERTY_SOURCE_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setSourceAsset(@jakarta.annotation.Nonnull String sourceAsset) { + this.sourceAsset = sourceAsset; + } + + + public TransferExchangeRate targetAsset(@jakarta.annotation.Nonnull String targetAsset) { + this.targetAsset = targetAsset; + return this; + } + + /** + * The asset being converted to. + * @return targetAsset + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_TARGET_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getTargetAsset() { + return targetAsset; + } + + + @JsonProperty(JSON_PROPERTY_TARGET_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTargetAsset(@jakarta.annotation.Nonnull String targetAsset) { + this.targetAsset = targetAsset; + } + + + public TransferExchangeRate rate(@jakarta.annotation.Nonnull String rate) { + this.rate = rate; + return this; + } + + /** + * The exchange rate value as a decimal string. Indicates how many units of the target asset equal one unit of the source asset. + * @return rate + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_RATE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getRate() { + return rate; + } + + + @JsonProperty(JSON_PROPERTY_RATE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setRate(@jakarta.annotation.Nonnull String rate) { + this.rate = rate; + } + + + /** + * Return true if this TransferExchangeRate object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TransferExchangeRate transferExchangeRate = (TransferExchangeRate) o; + return Objects.equals(this.sourceAsset, transferExchangeRate.sourceAsset) && + Objects.equals(this.targetAsset, transferExchangeRate.targetAsset) && + Objects.equals(this.rate, transferExchangeRate.rate); + } + + @Override + public int hashCode() { + return Objects.hash(sourceAsset, targetAsset, rate); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TransferExchangeRate {\n"); + sb.append(" sourceAsset: ").append(toIndentedString(sourceAsset)).append("\n"); + sb.append(" targetAsset: ").append(toIndentedString(targetAsset)).append("\n"); + sb.append(" rate: ").append(toIndentedString(rate)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `sourceAsset` to the URL query string + if (getSourceAsset() != null) { + joiner.add(String.format("%ssourceAsset%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getSourceAsset()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `targetAsset` to the URL query string + if (getTargetAsset() != null) { + joiner.add(String.format("%stargetAsset%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getTargetAsset()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `rate` to the URL query string + if (getRate() != null) { + joiner.add(String.format("%srate%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getRate()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private TransferExchangeRate instance; + + public Builder() { + this(new TransferExchangeRate()); + } + + protected Builder(TransferExchangeRate instance) { + this.instance = instance; + } + + public TransferExchangeRate.Builder sourceAsset(String sourceAsset) { + this.instance.sourceAsset = sourceAsset; + return this; + } + public TransferExchangeRate.Builder targetAsset(String targetAsset) { + this.instance.targetAsset = targetAsset; + return this; + } + public TransferExchangeRate.Builder rate(String rate) { + this.instance.rate = rate; + return this; + } + + + /** + * returns a built TransferExchangeRate instance. + * + * The builder is not reusable. + */ + public TransferExchangeRate build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static TransferExchangeRate.Builder builder() { + return new TransferExchangeRate.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public TransferExchangeRate.Builder toBuilder() { + return new TransferExchangeRate.Builder() + .sourceAsset(getSourceAsset()) + .targetAsset(getTargetAsset()) + .rate(getRate()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/TransferFee.java b/java/src/main/java/com/coinbase/cdp/openapi/model/TransferFee.java new file mode 100644 index 000000000..c05b49639 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/TransferFee.java @@ -0,0 +1,326 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * A single fee for a transfer. + */ +@JsonPropertyOrder({ + TransferFee.JSON_PROPERTY_TYPE, + TransferFee.JSON_PROPERTY_AMOUNT, + TransferFee.JSON_PROPERTY_ASSET +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class TransferFee { + /** + * The type of the fee, indicating its purpose. + */ + public enum TypeEnum { + BankFee(String.valueOf("bank")), + + ConversionFee(String.valueOf("conversion")), + + NetworkFee(String.valueOf("network")), + + OtherFee(String.valueOf("other")); + + private String value; + + TypeEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static TypeEnum fromValue(String value) { + for (TypeEnum b : TypeEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + public static final String JSON_PROPERTY_TYPE = "type"; + @jakarta.annotation.Nonnull + private TypeEnum type; + + public static final String JSON_PROPERTY_AMOUNT = "amount"; + @jakarta.annotation.Nonnull + private String amount; + + public static final String JSON_PROPERTY_ASSET = "asset"; + @jakarta.annotation.Nonnull + private String asset; + + public TransferFee() { + } + + public TransferFee type(@jakarta.annotation.Nonnull TypeEnum type) { + this.type = type; + return this; + } + + /** + * The type of the fee, indicating its purpose. + * @return type + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_TYPE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public TypeEnum getType() { + return type; + } + + + @JsonProperty(JSON_PROPERTY_TYPE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setType(@jakarta.annotation.Nonnull TypeEnum type) { + this.type = type; + } + + + public TransferFee amount(@jakarta.annotation.Nonnull String amount) { + this.amount = amount; + return this; + } + + /** + * The amount of the fee in units of the asset specified by `asset`. + * @return amount + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_AMOUNT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAmount() { + return amount; + } + + + @JsonProperty(JSON_PROPERTY_AMOUNT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAmount(@jakarta.annotation.Nonnull String amount) { + this.amount = amount; + } + + + public TransferFee asset(@jakarta.annotation.Nonnull String asset) { + this.asset = asset; + return this; + } + + /** + * The asset symbol. + * @return asset + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAsset() { + return asset; + } + + + @JsonProperty(JSON_PROPERTY_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAsset(@jakarta.annotation.Nonnull String asset) { + this.asset = asset; + } + + + /** + * Return true if this TransferFee object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TransferFee transferFee = (TransferFee) o; + return Objects.equals(this.type, transferFee.type) && + Objects.equals(this.amount, transferFee.amount) && + Objects.equals(this.asset, transferFee.asset); + } + + @Override + public int hashCode() { + return Objects.hash(type, amount, asset); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TransferFee {\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" amount: ").append(toIndentedString(amount)).append("\n"); + sb.append(" asset: ").append(toIndentedString(asset)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `type` to the URL query string + if (getType() != null) { + joiner.add(String.format("%stype%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getType()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `amount` to the URL query string + if (getAmount() != null) { + joiner.add(String.format("%samount%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAmount()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `asset` to the URL query string + if (getAsset() != null) { + joiner.add(String.format("%sasset%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAsset()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private TransferFee instance; + + public Builder() { + this(new TransferFee()); + } + + protected Builder(TransferFee instance) { + this.instance = instance; + } + + public TransferFee.Builder type(TypeEnum type) { + this.instance.type = type; + return this; + } + public TransferFee.Builder amount(String amount) { + this.instance.amount = amount; + return this; + } + public TransferFee.Builder asset(String asset) { + this.instance.asset = asset; + return this; + } + + + /** + * returns a built TransferFee instance. + * + * The builder is not reusable. + */ + public TransferFee build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static TransferFee.Builder builder() { + return new TransferFee.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public TransferFee.Builder toBuilder() { + return new TransferFee.Builder() + .type(getType()) + .amount(getAmount()) + .asset(getAsset()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/TransferFees.java b/java/src/main/java/com/coinbase/cdp/openapi/model/TransferFees.java new file mode 100644 index 000000000..f848c384a --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/TransferFees.java @@ -0,0 +1,162 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.TransferFee; +import java.util.ArrayList; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * The fees associated with this transfer. Different transfer types have different fee structures. **NOTE:** These examples are not exhaustive. Common examples: * **Crypto transfers**: Network fees (gas) paid in the native token * **Fiat conversions**: Processing fees + exchange fees in USD * **Wire transfers**: Wire fees ($15) + processing fees ($5) in USD * **Crypto conversions**: Spread fees paid in the source asset. + */ +@JsonPropertyOrder({ +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class TransferFees extends ArrayList { + public TransferFees() { + } + + /** + * Return true if this TransferFees object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TransferFees {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + return joiner.toString(); + } + + public static class Builder { + + private TransferFees instance; + + public Builder() { + this(new TransferFees()); + } + + protected Builder(TransferFees instance) { + this.instance = instance; + } + + + + /** + * returns a built TransferFees instance. + * + * The builder is not reusable. + */ + public TransferFees build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static TransferFees.Builder builder() { + return new TransferFees.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public TransferFees.Builder toBuilder() { + return new TransferFees.Builder(); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/TransferRequest.java b/java/src/main/java/com/coinbase/cdp/openapi/model/TransferRequest.java new file mode 100644 index 000000000..c2fb4e7ef --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/TransferRequest.java @@ -0,0 +1,572 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.CreateTransferSource; +import com.coinbase.cdp.openapi.model.Metadata; +import com.coinbase.cdp.openapi.model.TransferTarget; +import com.coinbase.cdp.openapi.model.TravelRule; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * A request to create a transfer. + */ +@JsonPropertyOrder({ + TransferRequest.JSON_PROPERTY_SOURCE, + TransferRequest.JSON_PROPERTY_TARGET, + TransferRequest.JSON_PROPERTY_AMOUNT, + TransferRequest.JSON_PROPERTY_ASSET, + TransferRequest.JSON_PROPERTY_AMOUNT_TYPE, + TransferRequest.JSON_PROPERTY_VALIDATE_ONLY, + TransferRequest.JSON_PROPERTY_EXECUTE, + TransferRequest.JSON_PROPERTY_METADATA, + TransferRequest.JSON_PROPERTY_TRAVEL_RULE +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class TransferRequest { + public static final String JSON_PROPERTY_SOURCE = "source"; + @jakarta.annotation.Nonnull + private CreateTransferSource source; + + public static final String JSON_PROPERTY_TARGET = "target"; + @jakarta.annotation.Nonnull + private TransferTarget target; + + public static final String JSON_PROPERTY_AMOUNT = "amount"; + @jakarta.annotation.Nonnull + private String amount; + + public static final String JSON_PROPERTY_ASSET = "asset"; + @jakarta.annotation.Nonnull + private String asset; + + /** + * Specifies whether the given amount is to be received by the target or taken from the source. - `target`: The transfer `target` receives the exact value specified in `amount`. Fees are added to the amount taken from the transfer `source`. - `source`: The transfer `target` receives the value specified in `amount`, minus any fees. + */ + public enum AmountTypeEnum { + TARGET(String.valueOf("target")), + + SOURCE(String.valueOf("source")); + + private String value; + + AmountTypeEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static AmountTypeEnum fromValue(String value) { + for (AmountTypeEnum b : AmountTypeEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + public static final String JSON_PROPERTY_AMOUNT_TYPE = "amountType"; + @jakarta.annotation.Nullable + private AmountTypeEnum amountType = AmountTypeEnum.SOURCE; + + public static final String JSON_PROPERTY_VALIDATE_ONLY = "validateOnly"; + @jakarta.annotation.Nullable + private Boolean validateOnly = false; + + public static final String JSON_PROPERTY_EXECUTE = "execute"; + @jakarta.annotation.Nonnull + private Boolean execute; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private Metadata metadata = new Metadata(); + + public static final String JSON_PROPERTY_TRAVEL_RULE = "travelRule"; + @jakarta.annotation.Nullable + private TravelRule travelRule; + + public TransferRequest() { + } + + public TransferRequest source(@jakarta.annotation.Nonnull CreateTransferSource source) { + this.source = source; + return this; + } + + /** + * Get source + * @return source + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_SOURCE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public CreateTransferSource getSource() { + return source; + } + + + @JsonProperty(JSON_PROPERTY_SOURCE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setSource(@jakarta.annotation.Nonnull CreateTransferSource source) { + this.source = source; + } + + + public TransferRequest target(@jakarta.annotation.Nonnull TransferTarget target) { + this.target = target; + return this; + } + + /** + * Get target + * @return target + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_TARGET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public TransferTarget getTarget() { + return target; + } + + + @JsonProperty(JSON_PROPERTY_TARGET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTarget(@jakarta.annotation.Nonnull TransferTarget target) { + this.target = target; + } + + + public TransferRequest amount(@jakarta.annotation.Nonnull String amount) { + this.amount = amount; + return this; + } + + /** + * The amount of the transfer, as a decimal string in standard unit denomination of the asset specified by `asset` (e.g., \"100.00\" for 100 USD, \"0.05\" for 0.05 ETH). + * @return amount + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_AMOUNT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAmount() { + return amount; + } + + + @JsonProperty(JSON_PROPERTY_AMOUNT) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAmount(@jakarta.annotation.Nonnull String amount) { + this.amount = amount; + } + + + public TransferRequest asset(@jakarta.annotation.Nonnull String asset) { + this.asset = asset; + return this; + } + + /** + * The symbol of the asset for the amount. This must be one of the assets of the source or target. + * @return asset + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAsset() { + return asset; + } + + + @JsonProperty(JSON_PROPERTY_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAsset(@jakarta.annotation.Nonnull String asset) { + this.asset = asset; + } + + + public TransferRequest amountType(@jakarta.annotation.Nullable AmountTypeEnum amountType) { + this.amountType = amountType; + return this; + } + + /** + * Specifies whether the given amount is to be received by the target or taken from the source. - `target`: The transfer `target` receives the exact value specified in `amount`. Fees are added to the amount taken from the transfer `source`. - `source`: The transfer `target` receives the value specified in `amount`, minus any fees. + * @return amountType + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_AMOUNT_TYPE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public AmountTypeEnum getAmountType() { + return amountType; + } + + + @JsonProperty(JSON_PROPERTY_AMOUNT_TYPE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setAmountType(@jakarta.annotation.Nullable AmountTypeEnum amountType) { + this.amountType = amountType; + } + + + public TransferRequest validateOnly(@jakarta.annotation.Nullable Boolean validateOnly) { + this.validateOnly = validateOnly; + return this; + } + + /** + * If true, validates the transfer without initiating it. If the request is valid, a 2xx will be returned. If the request is invalid, a 4xx error will be returned. The response will include an errorType, for e.g. invalid_target if the specified target cannot receive funds. + * @return validateOnly + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_VALIDATE_ONLY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public Boolean getValidateOnly() { + return validateOnly; + } + + + @JsonProperty(JSON_PROPERTY_VALIDATE_ONLY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setValidateOnly(@jakarta.annotation.Nullable Boolean validateOnly) { + this.validateOnly = validateOnly; + } + + + public TransferRequest execute(@jakarta.annotation.Nonnull Boolean execute) { + this.execute = execute; + return this; + } + + /** + * Whether to immediately execute the transfer. If false, the transfer will be created in quoted status and must be executed manually via the /execute endpoint. + * @return execute + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_EXECUTE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public Boolean getExecute() { + return execute; + } + + + @JsonProperty(JSON_PROPERTY_EXECUTE) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExecute(@jakarta.annotation.Nonnull Boolean execute) { + this.execute = execute; + } + + + public TransferRequest metadata(@jakarta.annotation.Nullable Metadata metadata) { + this.metadata = metadata; + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_METADATA) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public Metadata getMetadata() { + return metadata; + } + + + @JsonProperty(JSON_PROPERTY_METADATA) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setMetadata(@jakarta.annotation.Nullable Metadata metadata) { + this.metadata = metadata; + } + + + public TransferRequest travelRule(@jakarta.annotation.Nullable TravelRule travelRule) { + this.travelRule = travelRule; + return this; + } + + /** + * Get travelRule + * @return travelRule + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_TRAVEL_RULE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public TravelRule getTravelRule() { + return travelRule; + } + + + @JsonProperty(JSON_PROPERTY_TRAVEL_RULE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setTravelRule(@jakarta.annotation.Nullable TravelRule travelRule) { + this.travelRule = travelRule; + } + + + /** + * Return true if this TransferRequest object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TransferRequest transferRequest = (TransferRequest) o; + return Objects.equals(this.source, transferRequest.source) && + Objects.equals(this.target, transferRequest.target) && + Objects.equals(this.amount, transferRequest.amount) && + Objects.equals(this.asset, transferRequest.asset) && + Objects.equals(this.amountType, transferRequest.amountType) && + Objects.equals(this.validateOnly, transferRequest.validateOnly) && + Objects.equals(this.execute, transferRequest.execute) && + Objects.equals(this.metadata, transferRequest.metadata) && + Objects.equals(this.travelRule, transferRequest.travelRule); + } + + @Override + public int hashCode() { + return Objects.hash(source, target, amount, asset, amountType, validateOnly, execute, metadata, travelRule); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TransferRequest {\n"); + sb.append(" source: ").append(toIndentedString(source)).append("\n"); + sb.append(" target: ").append(toIndentedString(target)).append("\n"); + sb.append(" amount: ").append(toIndentedString(amount)).append("\n"); + sb.append(" asset: ").append(toIndentedString(asset)).append("\n"); + sb.append(" amountType: ").append(toIndentedString(amountType)).append("\n"); + sb.append(" validateOnly: ").append(toIndentedString(validateOnly)).append("\n"); + sb.append(" execute: ").append(toIndentedString(execute)).append("\n"); + sb.append(" metadata: ").append(toIndentedString(metadata)).append("\n"); + sb.append(" travelRule: ").append(toIndentedString(travelRule)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `source` to the URL query string + if (getSource() != null) { + joiner.add(getSource().toUrlQueryString(prefix + "source" + suffix)); + } + + // add `target` to the URL query string + if (getTarget() != null) { + joiner.add(getTarget().toUrlQueryString(prefix + "target" + suffix)); + } + + // add `amount` to the URL query string + if (getAmount() != null) { + joiner.add(String.format("%samount%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAmount()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `asset` to the URL query string + if (getAsset() != null) { + joiner.add(String.format("%sasset%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAsset()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `amountType` to the URL query string + if (getAmountType() != null) { + joiner.add(String.format("%samountType%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAmountType()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `validateOnly` to the URL query string + if (getValidateOnly() != null) { + joiner.add(String.format("%svalidateOnly%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getValidateOnly()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `execute` to the URL query string + if (getExecute() != null) { + joiner.add(String.format("%sexecute%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getExecute()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `metadata` to the URL query string + if (getMetadata() != null) { + joiner.add(String.format("%smetadata%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getMetadata()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `travelRule` to the URL query string + if (getTravelRule() != null) { + joiner.add(getTravelRule().toUrlQueryString(prefix + "travelRule" + suffix)); + } + + return joiner.toString(); + } + + public static class Builder { + + private TransferRequest instance; + + public Builder() { + this(new TransferRequest()); + } + + protected Builder(TransferRequest instance) { + this.instance = instance; + } + + public TransferRequest.Builder source(CreateTransferSource source) { + this.instance.source = source; + return this; + } + public TransferRequest.Builder target(TransferTarget target) { + this.instance.target = target; + return this; + } + public TransferRequest.Builder amount(String amount) { + this.instance.amount = amount; + return this; + } + public TransferRequest.Builder asset(String asset) { + this.instance.asset = asset; + return this; + } + public TransferRequest.Builder amountType(AmountTypeEnum amountType) { + this.instance.amountType = amountType; + return this; + } + public TransferRequest.Builder validateOnly(Boolean validateOnly) { + this.instance.validateOnly = validateOnly; + return this; + } + public TransferRequest.Builder execute(Boolean execute) { + this.instance.execute = execute; + return this; + } + public TransferRequest.Builder metadata(Metadata metadata) { + this.instance.metadata = metadata; + return this; + } + public TransferRequest.Builder travelRule(TravelRule travelRule) { + this.instance.travelRule = travelRule; + return this; + } + + + /** + * returns a built TransferRequest instance. + * + * The builder is not reusable. + */ + public TransferRequest build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static TransferRequest.Builder builder() { + return new TransferRequest.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public TransferRequest.Builder toBuilder() { + return new TransferRequest.Builder() + .source(getSource()) + .target(getTarget()) + .amount(getAmount()) + .asset(getAsset()) + .amountType(getAmountType()) + .validateOnly(getValidateOnly()) + .execute(getExecute()) + .metadata(getMetadata()) + .travelRule(getTravelRule()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/TransferSource.java b/java/src/main/java/com/coinbase/cdp/openapi/model/TransferSource.java new file mode 100644 index 000000000..c0000606b --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/TransferSource.java @@ -0,0 +1,407 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.Network; +import com.coinbase.cdp.openapi.model.OnchainAddress; +import com.coinbase.cdp.openapi.model.OriginatingBankAccountUS; +import com.coinbase.cdp.openapi.model.PaymentMethod; +import com.coinbase.cdp.openapi.model.TransfersAccount; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import com.fasterxml.jackson.core.type.TypeReference; + +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import com.coinbase.cdp.openapi.JSON; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +@JsonDeserialize(using = TransferSource.TransferSourceDeserializer.class) +@JsonSerialize(using = TransferSource.TransferSourceSerializer.class) +public class TransferSource extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(TransferSource.class.getName()); + + public static class TransferSourceSerializer extends StdSerializer { + public TransferSourceSerializer(Class t) { + super(t); + } + + public TransferSourceSerializer() { + this(null); + } + + @Override + public void serialize(TransferSource value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { + jgen.writeObject(value.getActualInstance()); + } + } + + public static class TransferSourceDeserializer extends StdDeserializer { + public TransferSourceDeserializer() { + this(TransferSource.class); + } + + public TransferSourceDeserializer(Class vc) { + super(vc); + } + + @Override + public TransferSource deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { + JsonNode tree = jp.readValueAsTree(); + Object deserialized = null; + boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS); + int match = 0; + JsonToken token = tree.traverse(jp.getCodec()).nextToken(); + // deserialize OnchainAddress + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if (OnchainAddress.class.equals(Integer.class) || OnchainAddress.class.equals(Long.class) || OnchainAddress.class.equals(Float.class) || OnchainAddress.class.equals(Double.class) || OnchainAddress.class.equals(Boolean.class) || OnchainAddress.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= ((OnchainAddress.class.equals(Integer.class) || OnchainAddress.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= ((OnchainAddress.class.equals(Float.class) || OnchainAddress.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= (OnchainAddress.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= (OnchainAddress.class.equals(String.class) && token == JsonToken.VALUE_STRING); + } + } + if (attemptParsing) { + deserialized = tree.traverse(jp.getCodec()).readValueAs(OnchainAddress.class); + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema 'OnchainAddress'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'OnchainAddress'", e); + } + + // deserialize OriginatingBankAccountUS + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if (OriginatingBankAccountUS.class.equals(Integer.class) || OriginatingBankAccountUS.class.equals(Long.class) || OriginatingBankAccountUS.class.equals(Float.class) || OriginatingBankAccountUS.class.equals(Double.class) || OriginatingBankAccountUS.class.equals(Boolean.class) || OriginatingBankAccountUS.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= ((OriginatingBankAccountUS.class.equals(Integer.class) || OriginatingBankAccountUS.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= ((OriginatingBankAccountUS.class.equals(Float.class) || OriginatingBankAccountUS.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= (OriginatingBankAccountUS.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= (OriginatingBankAccountUS.class.equals(String.class) && token == JsonToken.VALUE_STRING); + } + } + if (attemptParsing) { + deserialized = tree.traverse(jp.getCodec()).readValueAs(OriginatingBankAccountUS.class); + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema 'OriginatingBankAccountUS'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'OriginatingBankAccountUS'", e); + } + + // deserialize PaymentMethod + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if (PaymentMethod.class.equals(Integer.class) || PaymentMethod.class.equals(Long.class) || PaymentMethod.class.equals(Float.class) || PaymentMethod.class.equals(Double.class) || PaymentMethod.class.equals(Boolean.class) || PaymentMethod.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= ((PaymentMethod.class.equals(Integer.class) || PaymentMethod.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= ((PaymentMethod.class.equals(Float.class) || PaymentMethod.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= (PaymentMethod.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= (PaymentMethod.class.equals(String.class) && token == JsonToken.VALUE_STRING); + } + } + if (attemptParsing) { + deserialized = tree.traverse(jp.getCodec()).readValueAs(PaymentMethod.class); + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema 'PaymentMethod'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'PaymentMethod'", e); + } + + // deserialize TransfersAccount + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if (TransfersAccount.class.equals(Integer.class) || TransfersAccount.class.equals(Long.class) || TransfersAccount.class.equals(Float.class) || TransfersAccount.class.equals(Double.class) || TransfersAccount.class.equals(Boolean.class) || TransfersAccount.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= ((TransfersAccount.class.equals(Integer.class) || TransfersAccount.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= ((TransfersAccount.class.equals(Float.class) || TransfersAccount.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= (TransfersAccount.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= (TransfersAccount.class.equals(String.class) && token == JsonToken.VALUE_STRING); + } + } + if (attemptParsing) { + deserialized = tree.traverse(jp.getCodec()).readValueAs(TransfersAccount.class); + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema 'TransfersAccount'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'TransfersAccount'", e); + } + + if (match == 1) { + TransferSource ret = new TransferSource(); + ret.setActualInstance(deserialized); + return ret; + } + throw new IOException(String.format("Failed deserialization for TransferSource: %d classes match result, expected 1", match)); + } + + /** + * Handle deserialization of the 'null' value. + */ + @Override + public TransferSource getNullValue(DeserializationContext ctxt) throws JsonMappingException { + throw new JsonMappingException(ctxt.getParser(), "TransferSource cannot be null"); + } + } + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public TransferSource() { + super("oneOf", Boolean.FALSE); + } + + public TransferSource(OnchainAddress o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public TransferSource(OriginatingBankAccountUS o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public TransferSource(PaymentMethod o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public TransferSource(TransfersAccount o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("OnchainAddress", OnchainAddress.class); + schemas.put("OriginatingBankAccountUS", OriginatingBankAccountUS.class); + schemas.put("PaymentMethod", PaymentMethod.class); + schemas.put("TransfersAccount", TransfersAccount.class); + JSON.registerDescendants(TransferSource.class, Collections.unmodifiableMap(schemas)); + } + + @Override + public Map> getSchemas() { + return TransferSource.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * OnchainAddress, OriginatingBankAccountUS, PaymentMethod, TransfersAccount + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(OnchainAddress.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(OriginatingBankAccountUS.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(PaymentMethod.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(TransfersAccount.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be OnchainAddress, OriginatingBankAccountUS, PaymentMethod, TransfersAccount"); + } + + /** + * Get the actual instance, which can be the following: + * OnchainAddress, OriginatingBankAccountUS, PaymentMethod, TransfersAccount + * + * @return The actual instance (OnchainAddress, OriginatingBankAccountUS, PaymentMethod, TransfersAccount) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `OnchainAddress`. If the actual instance is not `OnchainAddress`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `OnchainAddress` + * @throws ClassCastException if the instance is not `OnchainAddress` + */ + public OnchainAddress getOnchainAddress() throws ClassCastException { + return (OnchainAddress)super.getActualInstance(); + } + + /** + * Get the actual instance of `OriginatingBankAccountUS`. If the actual instance is not `OriginatingBankAccountUS`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `OriginatingBankAccountUS` + * @throws ClassCastException if the instance is not `OriginatingBankAccountUS` + */ + public OriginatingBankAccountUS getOriginatingBankAccountUS() throws ClassCastException { + return (OriginatingBankAccountUS)super.getActualInstance(); + } + + /** + * Get the actual instance of `PaymentMethod`. If the actual instance is not `PaymentMethod`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `PaymentMethod` + * @throws ClassCastException if the instance is not `PaymentMethod` + */ + public PaymentMethod getPaymentMethod() throws ClassCastException { + return (PaymentMethod)super.getActualInstance(); + } + + /** + * Get the actual instance of `TransfersAccount`. If the actual instance is not `TransfersAccount`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `TransfersAccount` + * @throws ClassCastException if the instance is not `TransfersAccount` + */ + public TransfersAccount getTransfersAccount() throws ClassCastException { + return (TransfersAccount)super.getActualInstance(); + } + + + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + if (getActualInstance() instanceof TransfersAccount) { + if (getActualInstance() != null) { + joiner.add(((TransfersAccount)getActualInstance()).toUrlQueryString(prefix + "one_of_0" + suffix)); + } + return joiner.toString(); + } + if (getActualInstance() instanceof PaymentMethod) { + if (getActualInstance() != null) { + joiner.add(((PaymentMethod)getActualInstance()).toUrlQueryString(prefix + "one_of_1" + suffix)); + } + return joiner.toString(); + } + if (getActualInstance() instanceof OnchainAddress) { + if (getActualInstance() != null) { + joiner.add(((OnchainAddress)getActualInstance()).toUrlQueryString(prefix + "one_of_2" + suffix)); + } + return joiner.toString(); + } + if (getActualInstance() instanceof OriginatingBankAccountUS) { + if (getActualInstance() != null) { + joiner.add(((OriginatingBankAccountUS)getActualInstance()).toUrlQueryString(prefix + "one_of_3" + suffix)); + } + return joiner.toString(); + } + return null; + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/TransferStatus.java b/java/src/main/java/com/coinbase/cdp/openapi/model/TransferStatus.java new file mode 100644 index 000000000..cf9890128 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/TransferStatus.java @@ -0,0 +1,94 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * The current status of the transfer, indicating what action you need to take next. Required when validateOnly is false. + */ +public enum TransferStatus { + + /** + * Transfer was created with `execute: true`, but is momentarily being quoted before executing _or_ the transfer was created with `execute: false`. It can be executed by calling `/v2/transfers/{transferId}/execute` with `execute: true`. + */ + QUOTED("quoted"), + + /** + * Transfer is executing after being quoted. No action needed - monitor progress via the transfers webhook. + */ + PROCESSING("processing"), + + /** + * Transfer completed successfully. + */ + COMPLETED("completed"), + + /** + * Transfer failed. See `failureReason` for details. + */ + FAILED("failed"); + + private String value; + + TransferStatus(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static TransferStatus fromValue(String value) { + for (TransferStatus b : TransferStatus.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + if (prefix == null) { + prefix = ""; + } + + return String.format("%s=%s", prefix, this.toString()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/TransferTarget.java b/java/src/main/java/com/coinbase/cdp/openapi/model/TransferTarget.java new file mode 100644 index 000000000..6caed5406 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/TransferTarget.java @@ -0,0 +1,407 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.EmailInstrument; +import com.coinbase.cdp.openapi.model.Network; +import com.coinbase.cdp.openapi.model.OnchainAddress; +import com.coinbase.cdp.openapi.model.PaymentMethod; +import com.coinbase.cdp.openapi.model.TransfersAccount; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import com.fasterxml.jackson.core.type.TypeReference; + +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import com.coinbase.cdp.openapi.JSON; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +@JsonDeserialize(using = TransferTarget.TransferTargetDeserializer.class) +@JsonSerialize(using = TransferTarget.TransferTargetSerializer.class) +public class TransferTarget extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(TransferTarget.class.getName()); + + public static class TransferTargetSerializer extends StdSerializer { + public TransferTargetSerializer(Class t) { + super(t); + } + + public TransferTargetSerializer() { + this(null); + } + + @Override + public void serialize(TransferTarget value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { + jgen.writeObject(value.getActualInstance()); + } + } + + public static class TransferTargetDeserializer extends StdDeserializer { + public TransferTargetDeserializer() { + this(TransferTarget.class); + } + + public TransferTargetDeserializer(Class vc) { + super(vc); + } + + @Override + public TransferTarget deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { + JsonNode tree = jp.readValueAsTree(); + Object deserialized = null; + boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS); + int match = 0; + JsonToken token = tree.traverse(jp.getCodec()).nextToken(); + // deserialize EmailInstrument + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if (EmailInstrument.class.equals(Integer.class) || EmailInstrument.class.equals(Long.class) || EmailInstrument.class.equals(Float.class) || EmailInstrument.class.equals(Double.class) || EmailInstrument.class.equals(Boolean.class) || EmailInstrument.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= ((EmailInstrument.class.equals(Integer.class) || EmailInstrument.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= ((EmailInstrument.class.equals(Float.class) || EmailInstrument.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= (EmailInstrument.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= (EmailInstrument.class.equals(String.class) && token == JsonToken.VALUE_STRING); + } + } + if (attemptParsing) { + deserialized = tree.traverse(jp.getCodec()).readValueAs(EmailInstrument.class); + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema 'EmailInstrument'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'EmailInstrument'", e); + } + + // deserialize OnchainAddress + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if (OnchainAddress.class.equals(Integer.class) || OnchainAddress.class.equals(Long.class) || OnchainAddress.class.equals(Float.class) || OnchainAddress.class.equals(Double.class) || OnchainAddress.class.equals(Boolean.class) || OnchainAddress.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= ((OnchainAddress.class.equals(Integer.class) || OnchainAddress.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= ((OnchainAddress.class.equals(Float.class) || OnchainAddress.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= (OnchainAddress.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= (OnchainAddress.class.equals(String.class) && token == JsonToken.VALUE_STRING); + } + } + if (attemptParsing) { + deserialized = tree.traverse(jp.getCodec()).readValueAs(OnchainAddress.class); + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema 'OnchainAddress'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'OnchainAddress'", e); + } + + // deserialize PaymentMethod + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if (PaymentMethod.class.equals(Integer.class) || PaymentMethod.class.equals(Long.class) || PaymentMethod.class.equals(Float.class) || PaymentMethod.class.equals(Double.class) || PaymentMethod.class.equals(Boolean.class) || PaymentMethod.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= ((PaymentMethod.class.equals(Integer.class) || PaymentMethod.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= ((PaymentMethod.class.equals(Float.class) || PaymentMethod.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= (PaymentMethod.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= (PaymentMethod.class.equals(String.class) && token == JsonToken.VALUE_STRING); + } + } + if (attemptParsing) { + deserialized = tree.traverse(jp.getCodec()).readValueAs(PaymentMethod.class); + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema 'PaymentMethod'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'PaymentMethod'", e); + } + + // deserialize TransfersAccount + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if (TransfersAccount.class.equals(Integer.class) || TransfersAccount.class.equals(Long.class) || TransfersAccount.class.equals(Float.class) || TransfersAccount.class.equals(Double.class) || TransfersAccount.class.equals(Boolean.class) || TransfersAccount.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= ((TransfersAccount.class.equals(Integer.class) || TransfersAccount.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= ((TransfersAccount.class.equals(Float.class) || TransfersAccount.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= (TransfersAccount.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= (TransfersAccount.class.equals(String.class) && token == JsonToken.VALUE_STRING); + } + } + if (attemptParsing) { + deserialized = tree.traverse(jp.getCodec()).readValueAs(TransfersAccount.class); + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema 'TransfersAccount'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'TransfersAccount'", e); + } + + if (match == 1) { + TransferTarget ret = new TransferTarget(); + ret.setActualInstance(deserialized); + return ret; + } + throw new IOException(String.format("Failed deserialization for TransferTarget: %d classes match result, expected 1", match)); + } + + /** + * Handle deserialization of the 'null' value. + */ + @Override + public TransferTarget getNullValue(DeserializationContext ctxt) throws JsonMappingException { + throw new JsonMappingException(ctxt.getParser(), "TransferTarget cannot be null"); + } + } + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public TransferTarget() { + super("oneOf", Boolean.FALSE); + } + + public TransferTarget(EmailInstrument o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public TransferTarget(OnchainAddress o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public TransferTarget(PaymentMethod o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public TransferTarget(TransfersAccount o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("EmailInstrument", EmailInstrument.class); + schemas.put("OnchainAddress", OnchainAddress.class); + schemas.put("PaymentMethod", PaymentMethod.class); + schemas.put("TransfersAccount", TransfersAccount.class); + JSON.registerDescendants(TransferTarget.class, Collections.unmodifiableMap(schemas)); + } + + @Override + public Map> getSchemas() { + return TransferTarget.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * EmailInstrument, OnchainAddress, PaymentMethod, TransfersAccount + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(EmailInstrument.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(OnchainAddress.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(PaymentMethod.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(TransfersAccount.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be EmailInstrument, OnchainAddress, PaymentMethod, TransfersAccount"); + } + + /** + * Get the actual instance, which can be the following: + * EmailInstrument, OnchainAddress, PaymentMethod, TransfersAccount + * + * @return The actual instance (EmailInstrument, OnchainAddress, PaymentMethod, TransfersAccount) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `EmailInstrument`. If the actual instance is not `EmailInstrument`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `EmailInstrument` + * @throws ClassCastException if the instance is not `EmailInstrument` + */ + public EmailInstrument getEmailInstrument() throws ClassCastException { + return (EmailInstrument)super.getActualInstance(); + } + + /** + * Get the actual instance of `OnchainAddress`. If the actual instance is not `OnchainAddress`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `OnchainAddress` + * @throws ClassCastException if the instance is not `OnchainAddress` + */ + public OnchainAddress getOnchainAddress() throws ClassCastException { + return (OnchainAddress)super.getActualInstance(); + } + + /** + * Get the actual instance of `PaymentMethod`. If the actual instance is not `PaymentMethod`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `PaymentMethod` + * @throws ClassCastException if the instance is not `PaymentMethod` + */ + public PaymentMethod getPaymentMethod() throws ClassCastException { + return (PaymentMethod)super.getActualInstance(); + } + + /** + * Get the actual instance of `TransfersAccount`. If the actual instance is not `TransfersAccount`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `TransfersAccount` + * @throws ClassCastException if the instance is not `TransfersAccount` + */ + public TransfersAccount getTransfersAccount() throws ClassCastException { + return (TransfersAccount)super.getActualInstance(); + } + + + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + if (getActualInstance() instanceof TransfersAccount) { + if (getActualInstance() != null) { + joiner.add(((TransfersAccount)getActualInstance()).toUrlQueryString(prefix + "one_of_0" + suffix)); + } + return joiner.toString(); + } + if (getActualInstance() instanceof PaymentMethod) { + if (getActualInstance() != null) { + joiner.add(((PaymentMethod)getActualInstance()).toUrlQueryString(prefix + "one_of_1" + suffix)); + } + return joiner.toString(); + } + if (getActualInstance() instanceof OnchainAddress) { + if (getActualInstance() != null) { + joiner.add(((OnchainAddress)getActualInstance()).toUrlQueryString(prefix + "one_of_2" + suffix)); + } + return joiner.toString(); + } + if (getActualInstance() instanceof EmailInstrument) { + if (getActualInstance() != null) { + joiner.add(((EmailInstrument)getActualInstance()).toUrlQueryString(prefix + "one_of_3" + suffix)); + } + return joiner.toString(); + } + return null; + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/TransfersAccount.java b/java/src/main/java/com/coinbase/cdp/openapi/model/TransfersAccount.java new file mode 100644 index 000000000..f8a67b334 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/TransfersAccount.java @@ -0,0 +1,246 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * The Account specific details for the transfer. + */ +@JsonPropertyOrder({ + TransfersAccount.JSON_PROPERTY_ACCOUNT_ID, + TransfersAccount.JSON_PROPERTY_ASSET +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class TransfersAccount { + public static final String JSON_PROPERTY_ACCOUNT_ID = "accountId"; + @jakarta.annotation.Nonnull + private String accountId; + + public static final String JSON_PROPERTY_ASSET = "asset"; + @jakarta.annotation.Nonnull + private String asset; + + public TransfersAccount() { + } + + public TransfersAccount accountId(@jakarta.annotation.Nonnull String accountId) { + this.accountId = accountId; + return this; + } + + /** + * The ID of the Account. + * @return accountId + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ACCOUNT_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAccountId() { + return accountId; + } + + + @JsonProperty(JSON_PROPERTY_ACCOUNT_ID) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAccountId(@jakarta.annotation.Nonnull String accountId) { + this.accountId = accountId; + } + + + public TransfersAccount asset(@jakarta.annotation.Nonnull String asset) { + this.asset = asset; + return this; + } + + /** + * The symbol of the asset (e.g., eth, usd, usdc, usdt). + * @return asset + */ + @jakarta.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public String getAsset() { + return asset; + } + + + @JsonProperty(JSON_PROPERTY_ASSET) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAsset(@jakarta.annotation.Nonnull String asset) { + this.asset = asset; + } + + + /** + * Return true if this transfers_Account object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TransfersAccount transfersAccount = (TransfersAccount) o; + return Objects.equals(this.accountId, transfersAccount.accountId) && + Objects.equals(this.asset, transfersAccount.asset); + } + + @Override + public int hashCode() { + return Objects.hash(accountId, asset); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TransfersAccount {\n"); + sb.append(" accountId: ").append(toIndentedString(accountId)).append("\n"); + sb.append(" asset: ").append(toIndentedString(asset)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `accountId` to the URL query string + if (getAccountId() != null) { + joiner.add(String.format("%saccountId%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAccountId()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `asset` to the URL query string + if (getAsset() != null) { + joiner.add(String.format("%sasset%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getAsset()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private TransfersAccount instance; + + public Builder() { + this(new TransfersAccount()); + } + + protected Builder(TransfersAccount instance) { + this.instance = instance; + } + + public TransfersAccount.Builder accountId(String accountId) { + this.instance.accountId = accountId; + return this; + } + public TransfersAccount.Builder asset(String asset) { + this.instance.asset = asset; + return this; + } + + + /** + * returns a built TransfersAccount instance. + * + * The builder is not reusable. + */ + public TransfersAccount build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static TransfersAccount.Builder builder() { + return new TransfersAccount.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public TransfersAccount.Builder toBuilder() { + return new TransfersAccount.Builder() + .accountId(getAccountId()) + .asset(getAsset()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/TravelRule.java b/java/src/main/java/com/coinbase/cdp/openapi/model/TravelRule.java new file mode 100644 index 000000000..3f85539f0 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/TravelRule.java @@ -0,0 +1,330 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.TravelRuleBeneficiary; +import com.coinbase.cdp.openapi.model.TravelRuleOriginator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * Required Travel Rule fields differ by region. These requirements are determined based on which Coinbase entity the customer has signed the service agreement for. + */ +@JsonPropertyOrder({ + TravelRule.JSON_PROPERTY_IS_SELF, + TravelRule.JSON_PROPERTY_IS_INTERMEDIARY, + TravelRule.JSON_PROPERTY_ORIGINATOR, + TravelRule.JSON_PROPERTY_BENEFICIARY +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class TravelRule { + public static final String JSON_PROPERTY_IS_SELF = "isSelf"; + @jakarta.annotation.Nullable + private Boolean isSelf; + + public static final String JSON_PROPERTY_IS_INTERMEDIARY = "isIntermediary"; + @jakarta.annotation.Nullable + private Boolean isIntermediary; + + public static final String JSON_PROPERTY_ORIGINATOR = "originator"; + @jakarta.annotation.Nullable + private TravelRuleOriginator originator; + + public static final String JSON_PROPERTY_BENEFICIARY = "beneficiary"; + @jakarta.annotation.Nullable + private TravelRuleBeneficiary beneficiary; + + public TravelRule() { + } + + public TravelRule isSelf(@jakarta.annotation.Nullable Boolean isSelf) { + this.isSelf = isSelf; + return this; + } + + /** + * Indicates whether the user attests that the receiving wallet belongs to them. + * @return isSelf + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_IS_SELF) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public Boolean getIsSelf() { + return isSelf; + } + + + @JsonProperty(JSON_PROPERTY_IS_SELF) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setIsSelf(@jakarta.annotation.Nullable Boolean isSelf) { + this.isSelf = isSelf; + } + + + public TravelRule isIntermediary(@jakarta.annotation.Nullable Boolean isIntermediary) { + this.isIntermediary = isIntermediary; + return this; + } + + /** + * Indicates whether Coinbase is being used as an intermediary Virtual Asset Service Provider (VASP) to send crypto on behalf of your customer. **Background:** The Travel Rule (FATF Recommendation 16) requires VASPs to share originator and beneficiary information for virtual asset transfers. When Coinbase acts as an intermediary, additional Travel Rule data must be provided to satisfy compliance requirements. **Set to `true` when:** - Your organization is a VASP using Coinbase to send crypto **on behalf of your end customer** - In this scenario, Coinbase acts as an intermediary in the transfer chain and handles Travel Rule data exchange with the beneficiary VASP **Set to `false` (or omit) when:** - You are transferring funds directly from your own Coinbase account, where **Coinbase is your primary VASP** rather than an intermediary for another institution **Impact on required fields:** When `isIntermediary` is `true`, you must provide the `originator` object with details about the original sender, including: - Originator name - Originator address - Your VASP information (`virtualAssetServiceProvider` object with `name`, `address`, and `identifier`) + * @return isIntermediary + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_IS_INTERMEDIARY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public Boolean getIsIntermediary() { + return isIntermediary; + } + + + @JsonProperty(JSON_PROPERTY_IS_INTERMEDIARY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setIsIntermediary(@jakarta.annotation.Nullable Boolean isIntermediary) { + this.isIntermediary = isIntermediary; + } + + + public TravelRule originator(@jakarta.annotation.Nullable TravelRuleOriginator originator) { + this.originator = originator; + return this; + } + + /** + * Get originator + * @return originator + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ORIGINATOR) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public TravelRuleOriginator getOriginator() { + return originator; + } + + + @JsonProperty(JSON_PROPERTY_ORIGINATOR) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setOriginator(@jakarta.annotation.Nullable TravelRuleOriginator originator) { + this.originator = originator; + } + + + public TravelRule beneficiary(@jakarta.annotation.Nullable TravelRuleBeneficiary beneficiary) { + this.beneficiary = beneficiary; + return this; + } + + /** + * Get beneficiary + * @return beneficiary + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_BENEFICIARY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public TravelRuleBeneficiary getBeneficiary() { + return beneficiary; + } + + + @JsonProperty(JSON_PROPERTY_BENEFICIARY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setBeneficiary(@jakarta.annotation.Nullable TravelRuleBeneficiary beneficiary) { + this.beneficiary = beneficiary; + } + + + /** + * Return true if this TravelRule object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TravelRule travelRule = (TravelRule) o; + return Objects.equals(this.isSelf, travelRule.isSelf) && + Objects.equals(this.isIntermediary, travelRule.isIntermediary) && + Objects.equals(this.originator, travelRule.originator) && + Objects.equals(this.beneficiary, travelRule.beneficiary); + } + + @Override + public int hashCode() { + return Objects.hash(isSelf, isIntermediary, originator, beneficiary); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TravelRule {\n"); + sb.append(" isSelf: ").append(toIndentedString(isSelf)).append("\n"); + sb.append(" isIntermediary: ").append(toIndentedString(isIntermediary)).append("\n"); + sb.append(" originator: ").append(toIndentedString(originator)).append("\n"); + sb.append(" beneficiary: ").append(toIndentedString(beneficiary)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `isSelf` to the URL query string + if (getIsSelf() != null) { + joiner.add(String.format("%sisSelf%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getIsSelf()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `isIntermediary` to the URL query string + if (getIsIntermediary() != null) { + joiner.add(String.format("%sisIntermediary%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getIsIntermediary()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `originator` to the URL query string + if (getOriginator() != null) { + joiner.add(getOriginator().toUrlQueryString(prefix + "originator" + suffix)); + } + + // add `beneficiary` to the URL query string + if (getBeneficiary() != null) { + joiner.add(getBeneficiary().toUrlQueryString(prefix + "beneficiary" + suffix)); + } + + return joiner.toString(); + } + + public static class Builder { + + private TravelRule instance; + + public Builder() { + this(new TravelRule()); + } + + protected Builder(TravelRule instance) { + this.instance = instance; + } + + public TravelRule.Builder isSelf(Boolean isSelf) { + this.instance.isSelf = isSelf; + return this; + } + public TravelRule.Builder isIntermediary(Boolean isIntermediary) { + this.instance.isIntermediary = isIntermediary; + return this; + } + public TravelRule.Builder originator(TravelRuleOriginator originator) { + this.instance.originator = originator; + return this; + } + public TravelRule.Builder beneficiary(TravelRuleBeneficiary beneficiary) { + this.instance.beneficiary = beneficiary; + return this; + } + + + /** + * returns a built TravelRule instance. + * + * The builder is not reusable. + */ + public TravelRule build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static TravelRule.Builder builder() { + return new TravelRule.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public TravelRule.Builder toBuilder() { + return new TravelRule.Builder() + .isSelf(getIsSelf()) + .isIntermediary(getIsIntermediary()) + .originator(getOriginator()) + .beneficiary(getBeneficiary()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/TravelRuleBeneficiary.java b/java/src/main/java/com/coinbase/cdp/openapi/model/TravelRuleBeneficiary.java new file mode 100644 index 000000000..4167b092c --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/TravelRuleBeneficiary.java @@ -0,0 +1,364 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.PhysicalAddress; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * Beneficiary (receiver) party. + */ +@JsonPropertyOrder({ + TravelRuleBeneficiary.JSON_PROPERTY_FINANCIAL_INSTITUTION, + TravelRuleBeneficiary.JSON_PROPERTY_NAME, + TravelRuleBeneficiary.JSON_PROPERTY_ADDRESS, + TravelRuleBeneficiary.JSON_PROPERTY_WALLET_TYPE +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class TravelRuleBeneficiary { + public static final String JSON_PROPERTY_FINANCIAL_INSTITUTION = "financialInstitution"; + @jakarta.annotation.Nullable + private String financialInstitution; + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nullable + private String name; + + public static final String JSON_PROPERTY_ADDRESS = "address"; + @jakarta.annotation.Nullable + private PhysicalAddress address; + + /** + * The type of the beneficiary's wallet. + */ + public enum WalletTypeEnum { + CUSTODIAL(String.valueOf("custodial")), + + SELF_CUSTODY(String.valueOf("self_custody")); + + private String value; + + WalletTypeEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static WalletTypeEnum fromValue(String value) { + for (WalletTypeEnum b : WalletTypeEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + public static final String JSON_PROPERTY_WALLET_TYPE = "walletType"; + @jakarta.annotation.Nullable + private WalletTypeEnum walletType; + + public TravelRuleBeneficiary() { + } + + public TravelRuleBeneficiary financialInstitution(@jakarta.annotation.Nullable String financialInstitution) { + this.financialInstitution = financialInstitution; + return this; + } + + /** + * Name of the financial institution. + * @return financialInstitution + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_FINANCIAL_INSTITUTION) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getFinancialInstitution() { + return financialInstitution; + } + + + @JsonProperty(JSON_PROPERTY_FINANCIAL_INSTITUTION) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setFinancialInstitution(@jakarta.annotation.Nullable String financialInstitution) { + this.financialInstitution = financialInstitution; + } + + + public TravelRuleBeneficiary name(@jakarta.annotation.Nullable String name) { + this.name = name; + return this; + } + + /** + * Full name of the party. + * @return name + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getName() { + return name; + } + + + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setName(@jakarta.annotation.Nullable String name) { + this.name = name; + } + + + public TravelRuleBeneficiary address(@jakarta.annotation.Nullable PhysicalAddress address) { + this.address = address; + return this; + } + + /** + * Get address + * @return address + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ADDRESS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public PhysicalAddress getAddress() { + return address; + } + + + @JsonProperty(JSON_PROPERTY_ADDRESS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setAddress(@jakarta.annotation.Nullable PhysicalAddress address) { + this.address = address; + } + + + public TravelRuleBeneficiary walletType(@jakarta.annotation.Nullable WalletTypeEnum walletType) { + this.walletType = walletType; + return this; + } + + /** + * The type of the beneficiary's wallet. + * @return walletType + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_WALLET_TYPE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public WalletTypeEnum getWalletType() { + return walletType; + } + + + @JsonProperty(JSON_PROPERTY_WALLET_TYPE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setWalletType(@jakarta.annotation.Nullable WalletTypeEnum walletType) { + this.walletType = walletType; + } + + + /** + * Return true if this TravelRuleBeneficiary object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TravelRuleBeneficiary travelRuleBeneficiary = (TravelRuleBeneficiary) o; + return Objects.equals(this.financialInstitution, travelRuleBeneficiary.financialInstitution) && + Objects.equals(this.name, travelRuleBeneficiary.name) && + Objects.equals(this.address, travelRuleBeneficiary.address) && + Objects.equals(this.walletType, travelRuleBeneficiary.walletType); + } + + @Override + public int hashCode() { + return Objects.hash(financialInstitution, name, address, walletType); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TravelRuleBeneficiary {\n"); + sb.append(" financialInstitution: ").append(toIndentedString(financialInstitution)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" address: ").append(toIndentedString(address)).append("\n"); + sb.append(" walletType: ").append(toIndentedString(walletType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `financialInstitution` to the URL query string + if (getFinancialInstitution() != null) { + joiner.add(String.format("%sfinancialInstitution%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getFinancialInstitution()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `name` to the URL query string + if (getName() != null) { + joiner.add(String.format("%sname%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getName()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `address` to the URL query string + if (getAddress() != null) { + joiner.add(getAddress().toUrlQueryString(prefix + "address" + suffix)); + } + + // add `walletType` to the URL query string + if (getWalletType() != null) { + joiner.add(String.format("%swalletType%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getWalletType()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private TravelRuleBeneficiary instance; + + public Builder() { + this(new TravelRuleBeneficiary()); + } + + protected Builder(TravelRuleBeneficiary instance) { + this.instance = instance; + } + + public TravelRuleBeneficiary.Builder financialInstitution(String financialInstitution) { + this.instance.financialInstitution = financialInstitution; + return this; + } + public TravelRuleBeneficiary.Builder name(String name) { + this.instance.name = name; + return this; + } + public TravelRuleBeneficiary.Builder address(PhysicalAddress address) { + this.instance.address = address; + return this; + } + public TravelRuleBeneficiary.Builder walletType(WalletTypeEnum walletType) { + this.instance.walletType = walletType; + return this; + } + + + /** + * returns a built TravelRuleBeneficiary instance. + * + * The builder is not reusable. + */ + public TravelRuleBeneficiary build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static TravelRuleBeneficiary.Builder builder() { + return new TravelRuleBeneficiary.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public TravelRuleBeneficiary.Builder toBuilder() { + return new TravelRuleBeneficiary.Builder() + .financialInstitution(getFinancialInstitution()) + .name(getName()) + .address(getAddress()) + .walletType(getWalletType()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/TravelRuleOriginator.java b/java/src/main/java/com/coinbase/cdp/openapi/model/TravelRuleOriginator.java new file mode 100644 index 000000000..52cc4d39d --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/TravelRuleOriginator.java @@ -0,0 +1,330 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.PhysicalAddress; +import com.coinbase.cdp.openapi.model.TravelRuleOriginatorAllOfVirtualAssetServiceProvider; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * Originator (sender) party. + */ +@JsonPropertyOrder({ + TravelRuleOriginator.JSON_PROPERTY_FINANCIAL_INSTITUTION, + TravelRuleOriginator.JSON_PROPERTY_NAME, + TravelRuleOriginator.JSON_PROPERTY_ADDRESS, + TravelRuleOriginator.JSON_PROPERTY_VIRTUAL_ASSET_SERVICE_PROVIDER +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class TravelRuleOriginator { + public static final String JSON_PROPERTY_FINANCIAL_INSTITUTION = "financialInstitution"; + @jakarta.annotation.Nullable + private String financialInstitution; + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nullable + private String name; + + public static final String JSON_PROPERTY_ADDRESS = "address"; + @jakarta.annotation.Nullable + private PhysicalAddress address; + + public static final String JSON_PROPERTY_VIRTUAL_ASSET_SERVICE_PROVIDER = "virtualAssetServiceProvider"; + @jakarta.annotation.Nullable + private TravelRuleOriginatorAllOfVirtualAssetServiceProvider virtualAssetServiceProvider; + + public TravelRuleOriginator() { + } + + public TravelRuleOriginator financialInstitution(@jakarta.annotation.Nullable String financialInstitution) { + this.financialInstitution = financialInstitution; + return this; + } + + /** + * Name of the financial institution. + * @return financialInstitution + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_FINANCIAL_INSTITUTION) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getFinancialInstitution() { + return financialInstitution; + } + + + @JsonProperty(JSON_PROPERTY_FINANCIAL_INSTITUTION) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setFinancialInstitution(@jakarta.annotation.Nullable String financialInstitution) { + this.financialInstitution = financialInstitution; + } + + + public TravelRuleOriginator name(@jakarta.annotation.Nullable String name) { + this.name = name; + return this; + } + + /** + * Full name of the party. + * @return name + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getName() { + return name; + } + + + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setName(@jakarta.annotation.Nullable String name) { + this.name = name; + } + + + public TravelRuleOriginator address(@jakarta.annotation.Nullable PhysicalAddress address) { + this.address = address; + return this; + } + + /** + * Get address + * @return address + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ADDRESS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public PhysicalAddress getAddress() { + return address; + } + + + @JsonProperty(JSON_PROPERTY_ADDRESS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setAddress(@jakarta.annotation.Nullable PhysicalAddress address) { + this.address = address; + } + + + public TravelRuleOriginator virtualAssetServiceProvider(@jakarta.annotation.Nullable TravelRuleOriginatorAllOfVirtualAssetServiceProvider virtualAssetServiceProvider) { + this.virtualAssetServiceProvider = virtualAssetServiceProvider; + return this; + } + + /** + * Get virtualAssetServiceProvider + * @return virtualAssetServiceProvider + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_VIRTUAL_ASSET_SERVICE_PROVIDER) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public TravelRuleOriginatorAllOfVirtualAssetServiceProvider getVirtualAssetServiceProvider() { + return virtualAssetServiceProvider; + } + + + @JsonProperty(JSON_PROPERTY_VIRTUAL_ASSET_SERVICE_PROVIDER) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setVirtualAssetServiceProvider(@jakarta.annotation.Nullable TravelRuleOriginatorAllOfVirtualAssetServiceProvider virtualAssetServiceProvider) { + this.virtualAssetServiceProvider = virtualAssetServiceProvider; + } + + + /** + * Return true if this TravelRuleOriginator object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TravelRuleOriginator travelRuleOriginator = (TravelRuleOriginator) o; + return Objects.equals(this.financialInstitution, travelRuleOriginator.financialInstitution) && + Objects.equals(this.name, travelRuleOriginator.name) && + Objects.equals(this.address, travelRuleOriginator.address) && + Objects.equals(this.virtualAssetServiceProvider, travelRuleOriginator.virtualAssetServiceProvider); + } + + @Override + public int hashCode() { + return Objects.hash(financialInstitution, name, address, virtualAssetServiceProvider); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TravelRuleOriginator {\n"); + sb.append(" financialInstitution: ").append(toIndentedString(financialInstitution)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" address: ").append(toIndentedString(address)).append("\n"); + sb.append(" virtualAssetServiceProvider: ").append(toIndentedString(virtualAssetServiceProvider)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `financialInstitution` to the URL query string + if (getFinancialInstitution() != null) { + joiner.add(String.format("%sfinancialInstitution%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getFinancialInstitution()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `name` to the URL query string + if (getName() != null) { + joiner.add(String.format("%sname%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getName()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `address` to the URL query string + if (getAddress() != null) { + joiner.add(getAddress().toUrlQueryString(prefix + "address" + suffix)); + } + + // add `virtualAssetServiceProvider` to the URL query string + if (getVirtualAssetServiceProvider() != null) { + joiner.add(getVirtualAssetServiceProvider().toUrlQueryString(prefix + "virtualAssetServiceProvider" + suffix)); + } + + return joiner.toString(); + } + + public static class Builder { + + private TravelRuleOriginator instance; + + public Builder() { + this(new TravelRuleOriginator()); + } + + protected Builder(TravelRuleOriginator instance) { + this.instance = instance; + } + + public TravelRuleOriginator.Builder financialInstitution(String financialInstitution) { + this.instance.financialInstitution = financialInstitution; + return this; + } + public TravelRuleOriginator.Builder name(String name) { + this.instance.name = name; + return this; + } + public TravelRuleOriginator.Builder address(PhysicalAddress address) { + this.instance.address = address; + return this; + } + public TravelRuleOriginator.Builder virtualAssetServiceProvider(TravelRuleOriginatorAllOfVirtualAssetServiceProvider virtualAssetServiceProvider) { + this.instance.virtualAssetServiceProvider = virtualAssetServiceProvider; + return this; + } + + + /** + * returns a built TravelRuleOriginator instance. + * + * The builder is not reusable. + */ + public TravelRuleOriginator build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static TravelRuleOriginator.Builder builder() { + return new TravelRuleOriginator.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public TravelRuleOriginator.Builder toBuilder() { + return new TravelRuleOriginator.Builder() + .financialInstitution(getFinancialInstitution()) + .name(getName()) + .address(getAddress()) + .virtualAssetServiceProvider(getVirtualAssetServiceProvider()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/TravelRuleOriginatorAllOfVirtualAssetServiceProvider.java b/java/src/main/java/com/coinbase/cdp/openapi/model/TravelRuleOriginatorAllOfVirtualAssetServiceProvider.java new file mode 100644 index 000000000..ce8e5a8bc --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/TravelRuleOriginatorAllOfVirtualAssetServiceProvider.java @@ -0,0 +1,288 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.PhysicalAddress; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * Information about the originating Virtual Asset Service Provider (VASP) that handles cryptocurrency or other virtual assets on behalf of customers. + */ +@JsonPropertyOrder({ + TravelRuleOriginatorAllOfVirtualAssetServiceProvider.JSON_PROPERTY_NAME, + TravelRuleOriginatorAllOfVirtualAssetServiceProvider.JSON_PROPERTY_ADDRESS, + TravelRuleOriginatorAllOfVirtualAssetServiceProvider.JSON_PROPERTY_IDENTIFIER +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class TravelRuleOriginatorAllOfVirtualAssetServiceProvider { + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nullable + private String name; + + public static final String JSON_PROPERTY_ADDRESS = "address"; + @jakarta.annotation.Nullable + private PhysicalAddress address; + + public static final String JSON_PROPERTY_IDENTIFIER = "identifier"; + @jakarta.annotation.Nullable + private String identifier; + + public TravelRuleOriginatorAllOfVirtualAssetServiceProvider() { + } + + public TravelRuleOriginatorAllOfVirtualAssetServiceProvider name(@jakarta.annotation.Nullable String name) { + this.name = name; + return this; + } + + /** + * The name of the originating Virtual Asset Service Provider (VASP). + * @return name + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getName() { + return name; + } + + + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setName(@jakarta.annotation.Nullable String name) { + this.name = name; + } + + + public TravelRuleOriginatorAllOfVirtualAssetServiceProvider address(@jakarta.annotation.Nullable PhysicalAddress address) { + this.address = address; + return this; + } + + /** + * The address of the originating Virtual Asset Service Provider (VASP). + * @return address + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ADDRESS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public PhysicalAddress getAddress() { + return address; + } + + + @JsonProperty(JSON_PROPERTY_ADDRESS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setAddress(@jakarta.annotation.Nullable PhysicalAddress address) { + this.address = address; + } + + + public TravelRuleOriginatorAllOfVirtualAssetServiceProvider identifier(@jakarta.annotation.Nullable String identifier) { + this.identifier = identifier; + return this; + } + + /** + * The Legal Entity Identifier of the originating Virtual Asset Service Provider (VASP). + * @return identifier + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_IDENTIFIER) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getIdentifier() { + return identifier; + } + + + @JsonProperty(JSON_PROPERTY_IDENTIFIER) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setIdentifier(@jakarta.annotation.Nullable String identifier) { + this.identifier = identifier; + } + + + /** + * Return true if this TravelRuleOriginator_allOf_virtualAssetServiceProvider object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TravelRuleOriginatorAllOfVirtualAssetServiceProvider travelRuleOriginatorAllOfVirtualAssetServiceProvider = (TravelRuleOriginatorAllOfVirtualAssetServiceProvider) o; + return Objects.equals(this.name, travelRuleOriginatorAllOfVirtualAssetServiceProvider.name) && + Objects.equals(this.address, travelRuleOriginatorAllOfVirtualAssetServiceProvider.address) && + Objects.equals(this.identifier, travelRuleOriginatorAllOfVirtualAssetServiceProvider.identifier); + } + + @Override + public int hashCode() { + return Objects.hash(name, address, identifier); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TravelRuleOriginatorAllOfVirtualAssetServiceProvider {\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" address: ").append(toIndentedString(address)).append("\n"); + sb.append(" identifier: ").append(toIndentedString(identifier)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `name` to the URL query string + if (getName() != null) { + joiner.add(String.format("%sname%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getName()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `address` to the URL query string + if (getAddress() != null) { + joiner.add(getAddress().toUrlQueryString(prefix + "address" + suffix)); + } + + // add `identifier` to the URL query string + if (getIdentifier() != null) { + joiner.add(String.format("%sidentifier%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getIdentifier()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + return joiner.toString(); + } + + public static class Builder { + + private TravelRuleOriginatorAllOfVirtualAssetServiceProvider instance; + + public Builder() { + this(new TravelRuleOriginatorAllOfVirtualAssetServiceProvider()); + } + + protected Builder(TravelRuleOriginatorAllOfVirtualAssetServiceProvider instance) { + this.instance = instance; + } + + public TravelRuleOriginatorAllOfVirtualAssetServiceProvider.Builder name(String name) { + this.instance.name = name; + return this; + } + public TravelRuleOriginatorAllOfVirtualAssetServiceProvider.Builder address(PhysicalAddress address) { + this.instance.address = address; + return this; + } + public TravelRuleOriginatorAllOfVirtualAssetServiceProvider.Builder identifier(String identifier) { + this.instance.identifier = identifier; + return this; + } + + + /** + * returns a built TravelRuleOriginatorAllOfVirtualAssetServiceProvider instance. + * + * The builder is not reusable. + */ + public TravelRuleOriginatorAllOfVirtualAssetServiceProvider build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static TravelRuleOriginatorAllOfVirtualAssetServiceProvider.Builder builder() { + return new TravelRuleOriginatorAllOfVirtualAssetServiceProvider.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public TravelRuleOriginatorAllOfVirtualAssetServiceProvider.Builder toBuilder() { + return new TravelRuleOriginatorAllOfVirtualAssetServiceProvider.Builder() + .name(getName()) + .address(getAddress()) + .identifier(getIdentifier()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/TravelRuleParty.java b/java/src/main/java/com/coinbase/cdp/openapi/model/TravelRuleParty.java new file mode 100644 index 000000000..88e81b9de --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/TravelRuleParty.java @@ -0,0 +1,288 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.coinbase.cdp.openapi.model.PhysicalAddress; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.coinbase.cdp.openapi.ApiClient; +/** + * Information about a party (originator or beneficiary) for travel rule compliance. + */ +@JsonPropertyOrder({ + TravelRuleParty.JSON_PROPERTY_FINANCIAL_INSTITUTION, + TravelRuleParty.JSON_PROPERTY_NAME, + TravelRuleParty.JSON_PROPERTY_ADDRESS +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") +public class TravelRuleParty { + public static final String JSON_PROPERTY_FINANCIAL_INSTITUTION = "financialInstitution"; + @jakarta.annotation.Nullable + private String financialInstitution; + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nullable + private String name; + + public static final String JSON_PROPERTY_ADDRESS = "address"; + @jakarta.annotation.Nullable + private PhysicalAddress address; + + public TravelRuleParty() { + } + + public TravelRuleParty financialInstitution(@jakarta.annotation.Nullable String financialInstitution) { + this.financialInstitution = financialInstitution; + return this; + } + + /** + * Name of the financial institution. + * @return financialInstitution + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_FINANCIAL_INSTITUTION) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getFinancialInstitution() { + return financialInstitution; + } + + + @JsonProperty(JSON_PROPERTY_FINANCIAL_INSTITUTION) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setFinancialInstitution(@jakarta.annotation.Nullable String financialInstitution) { + this.financialInstitution = financialInstitution; + } + + + public TravelRuleParty name(@jakarta.annotation.Nullable String name) { + this.name = name; + return this; + } + + /** + * Full name of the party. + * @return name + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getName() { + return name; + } + + + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setName(@jakarta.annotation.Nullable String name) { + this.name = name; + } + + + public TravelRuleParty address(@jakarta.annotation.Nullable PhysicalAddress address) { + this.address = address; + return this; + } + + /** + * Get address + * @return address + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ADDRESS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public PhysicalAddress getAddress() { + return address; + } + + + @JsonProperty(JSON_PROPERTY_ADDRESS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setAddress(@jakarta.annotation.Nullable PhysicalAddress address) { + this.address = address; + } + + + /** + * Return true if this TravelRuleParty object is equal to o. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TravelRuleParty travelRuleParty = (TravelRuleParty) o; + return Objects.equals(this.financialInstitution, travelRuleParty.financialInstitution) && + Objects.equals(this.name, travelRuleParty.name) && + Objects.equals(this.address, travelRuleParty.address); + } + + @Override + public int hashCode() { + return Objects.hash(financialInstitution, name, address); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TravelRuleParty {\n"); + sb.append(" financialInstitution: ").append(toIndentedString(financialInstitution)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" address: ").append(toIndentedString(address)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + // add `financialInstitution` to the URL query string + if (getFinancialInstitution() != null) { + joiner.add(String.format("%sfinancialInstitution%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getFinancialInstitution()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `name` to the URL query string + if (getName() != null) { + joiner.add(String.format("%sname%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getName()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `address` to the URL query string + if (getAddress() != null) { + joiner.add(getAddress().toUrlQueryString(prefix + "address" + suffix)); + } + + return joiner.toString(); + } + + public static class Builder { + + private TravelRuleParty instance; + + public Builder() { + this(new TravelRuleParty()); + } + + protected Builder(TravelRuleParty instance) { + this.instance = instance; + } + + public TravelRuleParty.Builder financialInstitution(String financialInstitution) { + this.instance.financialInstitution = financialInstitution; + return this; + } + public TravelRuleParty.Builder name(String name) { + this.instance.name = name; + return this; + } + public TravelRuleParty.Builder address(PhysicalAddress address) { + this.instance.address = address; + return this; + } + + + /** + * returns a built TravelRuleParty instance. + * + * The builder is not reusable. + */ + public TravelRuleParty build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static TravelRuleParty.Builder builder() { + return new TravelRuleParty.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public TravelRuleParty.Builder toBuilder() { + return new TravelRuleParty.Builder() + .financialInstitution(getFinancialInstitution()) + .name(getName()) + .address(getAddress()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/TravelRuleStatus.java b/java/src/main/java/com/coinbase/cdp/openapi/model/TravelRuleStatus.java new file mode 100644 index 000000000..9b7d4e781 --- /dev/null +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/TravelRuleStatus.java @@ -0,0 +1,84 @@ +/* + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * + * The version of the OpenAPI document: 2.0.0 + * Contact: cdp@coinbase.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.coinbase.cdp.openapi.model; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.StringJoiner; +import java.util.Objects; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * The status of a travel rule submission. + */ +public enum TravelRuleStatus { + + /** + * Additional fields are required before the transfer can proceed. + */ + TravelRuleStatusIncomplete("incomplete"), + + /** + * All requirements are satisfied and the transfer will proceed. + */ + TravelRuleStatusCompleted("completed"); + + private String value; + + TravelRuleStatus(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static TravelRuleStatus fromValue(String value) { + for (TravelRuleStatus b : TravelRuleStatus.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + if (prefix == null) { + prefix = ""; + } + + return String.format("%s=%s", prefix, this.toString()); + } + +} + diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/X402DiscoveryResource.java b/java/src/main/java/com/coinbase/cdp/openapi/model/X402DiscoveryResource.java index dd67652e1..43f6abb2c 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/model/X402DiscoveryResource.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/X402DiscoveryResource.java @@ -27,12 +27,11 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; +import java.net.URI; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; import java.util.List; -import java.util.Map; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @@ -48,7 +47,10 @@ X402DiscoveryResource.JSON_PROPERTY_LAST_UPDATED, X402DiscoveryResource.JSON_PROPERTY_ACCEPTS, X402DiscoveryResource.JSON_PROPERTY_EXTENSIONS, - X402DiscoveryResource.JSON_PROPERTY_QUALITY + X402DiscoveryResource.JSON_PROPERTY_QUALITY, + X402DiscoveryResource.JSON_PROPERTY_SERVICE_NAME, + X402DiscoveryResource.JSON_PROPERTY_TAGS, + X402DiscoveryResource.JSON_PROPERTY_ICON_URL }) @jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.11.0") public class X402DiscoveryResource { @@ -113,12 +115,24 @@ public static TypeEnum fromValue(String value) { public static final String JSON_PROPERTY_EXTENSIONS = "extensions"; @jakarta.annotation.Nullable - private Map extensions = new HashMap<>(); + private Object extensions; public static final String JSON_PROPERTY_QUALITY = "quality"; @jakarta.annotation.Nullable private X402ResourceQuality quality; + public static final String JSON_PROPERTY_SERVICE_NAME = "serviceName"; + @jakarta.annotation.Nullable + private String serviceName; + + public static final String JSON_PROPERTY_TAGS = "tags"; + @jakarta.annotation.Nullable + private List tags = new ArrayList<>(); + + public static final String JSON_PROPERTY_ICON_URL = "iconUrl"; + @jakarta.annotation.Nullable + private URI iconUrl; + public X402DiscoveryResource() { } @@ -274,34 +288,26 @@ public void setAccepts(@jakarta.annotation.Nullable List extensions) { + public X402DiscoveryResource extensions(@jakarta.annotation.Nullable Object extensions) { this.extensions = extensions; return this; } - public X402DiscoveryResource putExtensionsItem(String key, Object extensionsItem) { - if (this.extensions == null) { - this.extensions = new HashMap<>(); - } - this.extensions.put(key, extensionsItem); - return this; - } - /** * Map of x402 protocol extensions supported by the resource, keyed by extension name. * @return extensions */ @jakarta.annotation.Nullable @JsonProperty(JSON_PROPERTY_EXTENSIONS) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - public Map getExtensions() { + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public Object getExtensions() { return extensions; } @JsonProperty(JSON_PROPERTY_EXTENSIONS) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - public void setExtensions(@jakarta.annotation.Nullable Map extensions) { + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setExtensions(@jakarta.annotation.Nullable Object extensions) { this.extensions = extensions; } @@ -330,6 +336,86 @@ public void setQuality(@jakarta.annotation.Nullable X402ResourceQuality quality) } + public X402DiscoveryResource serviceName(@jakarta.annotation.Nullable String serviceName) { + this.serviceName = serviceName; + return this; + } + + /** + * Provider-supplied display name of the service this resource belongs to. This is a free-form label for grouping and presentation only — it is not a stable identifier, and two resources sharing the same `serviceName` are not guaranteed to belong to the same logical service. + * @return serviceName + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_SERVICE_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public String getServiceName() { + return serviceName; + } + + + @JsonProperty(JSON_PROPERTY_SERVICE_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setServiceName(@jakarta.annotation.Nullable String serviceName) { + this.serviceName = serviceName; + } + + + public X402DiscoveryResource tags(@jakarta.annotation.Nullable List tags) { + this.tags = tags; + return this; + } + + public X402DiscoveryResource addTagsItem(String tagsItem) { + if (this.tags == null) { + this.tags = new ArrayList<>(); + } + this.tags.add(tagsItem); + return this; + } + + /** + * Provider-supplied, low-cardinality string labels associated with the resource for client-side filtering and display. Values are free-form (no controlled vocabulary) and case-sensitive. Order is not significant and duplicates are not expected. + * @return tags + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_TAGS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public List getTags() { + return tags; + } + + + @JsonProperty(JSON_PROPERTY_TAGS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setTags(@jakarta.annotation.Nullable List tags) { + this.tags = tags; + } + + + public X402DiscoveryResource iconUrl(@jakarta.annotation.Nullable URI iconUrl) { + this.iconUrl = iconUrl; + return this; + } + + /** + * URL of a square icon representing the service this resource belongs to. Distinct from a brand logo: this is intended for compact, list-view rendering (favicon-style) and is normalized to a square aspect ratio at ingestion. The image is moderated and re-hosted by Coinbase, so the URL is stable and safe to render directly in clients. Omitted when the provider did not supply an icon, when the supplied icon failed moderation, or when image processing was unavailable at ingestion time. + * @return iconUrl + */ + @jakarta.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ICON_URL) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public URI getIconUrl() { + return iconUrl; + } + + + @JsonProperty(JSON_PROPERTY_ICON_URL) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setIconUrl(@jakarta.annotation.Nullable URI iconUrl) { + this.iconUrl = iconUrl; + } + + /** * Return true if this x402DiscoveryResource object is equal to o. */ @@ -349,12 +435,15 @@ public boolean equals(Object o) { Objects.equals(this.lastUpdated, x402DiscoveryResource.lastUpdated) && Objects.equals(this.accepts, x402DiscoveryResource.accepts) && Objects.equals(this.extensions, x402DiscoveryResource.extensions) && - Objects.equals(this.quality, x402DiscoveryResource.quality); + Objects.equals(this.quality, x402DiscoveryResource.quality) && + Objects.equals(this.serviceName, x402DiscoveryResource.serviceName) && + Objects.equals(this.tags, x402DiscoveryResource.tags) && + Objects.equals(this.iconUrl, x402DiscoveryResource.iconUrl); } @Override public int hashCode() { - return Objects.hash(resource, description, type, x402Version, lastUpdated, accepts, extensions, quality); + return Objects.hash(resource, description, type, x402Version, lastUpdated, accepts, extensions, quality, serviceName, tags, iconUrl); } @Override @@ -369,6 +458,9 @@ public String toString() { sb.append(" accepts: ").append(toIndentedString(accepts)).append("\n"); sb.append(" extensions: ").append(toIndentedString(extensions)).append("\n"); sb.append(" quality: ").append(toIndentedString(quality)).append("\n"); + sb.append(" serviceName: ").append(toIndentedString(serviceName)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" iconUrl: ").append(toIndentedString(iconUrl)).append("\n"); sb.append("}"); return sb.toString(); } @@ -453,11 +545,7 @@ public String toUrlQueryString(String prefix) { // add `extensions` to the URL query string if (getExtensions() != null) { - for (String _key : getExtensions().keySet()) { - joiner.add(String.format("%sextensions%s%s=%s", prefix, suffix, - "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, _key, containerSuffix), - getExtensions().get(_key), URLEncoder.encode(ApiClient.valueToString(getExtensions().get(_key)), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); - } + joiner.add(String.format("%sextensions%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getExtensions()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); } // add `quality` to the URL query string @@ -465,6 +553,25 @@ public String toUrlQueryString(String prefix) { joiner.add(getQuality().toUrlQueryString(prefix + "quality" + suffix)); } + // add `serviceName` to the URL query string + if (getServiceName() != null) { + joiner.add(String.format("%sserviceName%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getServiceName()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + + // add `tags` to the URL query string + if (getTags() != null) { + for (int i = 0; i < getTags().size(); i++) { + joiner.add(String.format("%stags%s%s=%s", prefix, suffix, + "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, i, containerSuffix), + URLEncoder.encode(ApiClient.valueToString(getTags().get(i)), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + } + + // add `iconUrl` to the URL query string + if (getIconUrl() != null) { + joiner.add(String.format("%siconUrl%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getIconUrl()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); + } + return joiner.toString(); } @@ -504,7 +611,7 @@ public X402DiscoveryResource.Builder accepts(List accep this.instance.accepts = accepts; return this; } - public X402DiscoveryResource.Builder extensions(Map extensions) { + public X402DiscoveryResource.Builder extensions(Object extensions) { this.instance.extensions = extensions; return this; } @@ -512,6 +619,18 @@ public X402DiscoveryResource.Builder quality(X402ResourceQuality quality) { this.instance.quality = quality; return this; } + public X402DiscoveryResource.Builder serviceName(String serviceName) { + this.instance.serviceName = serviceName; + return this; + } + public X402DiscoveryResource.Builder tags(List tags) { + this.instance.tags = tags; + return this; + } + public X402DiscoveryResource.Builder iconUrl(URI iconUrl) { + this.instance.iconUrl = iconUrl; + return this; + } /** @@ -553,7 +672,10 @@ public X402DiscoveryResource.Builder toBuilder() { .lastUpdated(getLastUpdated()) .accepts(getAccepts()) .extensions(getExtensions()) - .quality(getQuality()); + .quality(getQuality()) + .serviceName(getServiceName()) + .tags(getTags()) + .iconUrl(getIconUrl()); } } diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/X402McpError.java b/java/src/main/java/com/coinbase/cdp/openapi/model/X402McpError.java index 9bb0085f5..b91f2bcb8 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/model/X402McpError.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/X402McpError.java @@ -25,8 +25,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @@ -51,7 +49,7 @@ public class X402McpError { public static final String JSON_PROPERTY_DATA = "data"; @jakarta.annotation.Nullable - private Map data = new HashMap<>(); + private Object data; public X402McpError() { } @@ -104,34 +102,26 @@ public void setMessage(@jakarta.annotation.Nonnull String message) { } - public X402McpError data(@jakarta.annotation.Nullable Map data) { + public X402McpError data(@jakarta.annotation.Nullable Object data) { this.data = data; return this; } - public X402McpError putDataItem(String key, Object dataItem) { - if (this.data == null) { - this.data = new HashMap<>(); - } - this.data.put(key, dataItem); - return this; - } - /** * Additional error data. * @return data */ @jakarta.annotation.Nullable @JsonProperty(JSON_PROPERTY_DATA) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - public Map getData() { + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public Object getData() { return data; } @JsonProperty(JSON_PROPERTY_DATA) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - public void setData(@jakarta.annotation.Nullable Map data) { + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setData(@jakarta.annotation.Nullable Object data) { this.data = data; } @@ -224,11 +214,7 @@ public String toUrlQueryString(String prefix) { // add `data` to the URL query string if (getData() != null) { - for (String _key : getData().keySet()) { - joiner.add(String.format("%sdata%s%s=%s", prefix, suffix, - "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, _key, containerSuffix), - getData().get(_key), URLEncoder.encode(ApiClient.valueToString(getData().get(_key)), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); - } + joiner.add(String.format("%sdata%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getData()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); } return joiner.toString(); @@ -254,7 +240,7 @@ public X402McpError.Builder message(String message) { this.instance.message = message; return this; } - public X402McpError.Builder data(Map data) { + public X402McpError.Builder data(Object data) { this.instance.data = data; return this; } diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/X402McpRequest.java b/java/src/main/java/com/coinbase/cdp/openapi/model/X402McpRequest.java index 03fad0179..f29aada75 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/model/X402McpRequest.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/X402McpRequest.java @@ -26,8 +26,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @@ -90,7 +88,7 @@ public static JsonrpcEnum fromValue(String value) { public static final String JSON_PROPERTY_PARAMS = "params"; @jakarta.annotation.Nullable - private Map params = new HashMap<>(); + private Object params; public X402McpRequest() { } @@ -167,34 +165,26 @@ public void setMethod(@jakarta.annotation.Nonnull String method) { } - public X402McpRequest params(@jakarta.annotation.Nullable Map params) { + public X402McpRequest params(@jakarta.annotation.Nullable Object params) { this.params = params; return this; } - public X402McpRequest putParamsItem(String key, Object paramsItem) { - if (this.params == null) { - this.params = new HashMap<>(); - } - this.params.put(key, paramsItem); - return this; - } - /** * Optional parameters for the method. * @return params */ @jakarta.annotation.Nullable @JsonProperty(JSON_PROPERTY_PARAMS) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - public Map getParams() { + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public Object getParams() { return params; } @JsonProperty(JSON_PROPERTY_PARAMS) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - public void setParams(@jakarta.annotation.Nullable Map params) { + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setParams(@jakarta.annotation.Nullable Object params) { this.params = params; } @@ -294,11 +284,7 @@ public String toUrlQueryString(String prefix) { // add `params` to the URL query string if (getParams() != null) { - for (String _key : getParams().keySet()) { - joiner.add(String.format("%sparams%s%s=%s", prefix, suffix, - "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, _key, containerSuffix), - getParams().get(_key), URLEncoder.encode(ApiClient.valueToString(getParams().get(_key)), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); - } + joiner.add(String.format("%sparams%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getParams()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); } return joiner.toString(); @@ -328,7 +314,7 @@ public X402McpRequest.Builder method(String method) { this.instance.method = method; return this; } - public X402McpRequest.Builder params(Map params) { + public X402McpRequest.Builder params(Object params) { this.instance.params = params; return this; } diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/X402McpResponse.java b/java/src/main/java/com/coinbase/cdp/openapi/model/X402McpResponse.java index 32c711da8..f6b0422de 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/model/X402McpResponse.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/X402McpResponse.java @@ -27,8 +27,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @@ -87,7 +85,7 @@ public static JsonrpcEnum fromValue(String value) { public static final String JSON_PROPERTY_RESULT = "result"; @jakarta.annotation.Nullable - private Map result = new HashMap<>(); + private Object result; public static final String JSON_PROPERTY_ERROR = "error"; @jakarta.annotation.Nullable @@ -144,34 +142,26 @@ public void setId(@jakarta.annotation.Nullable X402McpResponseId id) { } - public X402McpResponse result(@jakarta.annotation.Nullable Map result) { + public X402McpResponse result(@jakarta.annotation.Nullable Object result) { this.result = result; return this; } - public X402McpResponse putResultItem(String key, Object resultItem) { - if (this.result == null) { - this.result = new HashMap<>(); - } - this.result.put(key, resultItem); - return this; - } - /** * The result of the method call (present on success). * @return result */ @jakarta.annotation.Nullable @JsonProperty(JSON_PROPERTY_RESULT) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - public Map getResult() { + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public Object getResult() { return result; } @JsonProperty(JSON_PROPERTY_RESULT) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - public void setResult(@jakarta.annotation.Nullable Map result) { + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setResult(@jakarta.annotation.Nullable Object result) { this.result = result; } @@ -290,11 +280,7 @@ public String toUrlQueryString(String prefix) { // add `result` to the URL query string if (getResult() != null) { - for (String _key : getResult().keySet()) { - joiner.add(String.format("%sresult%s%s=%s", prefix, suffix, - "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, _key, containerSuffix), - getResult().get(_key), URLEncoder.encode(ApiClient.valueToString(getResult().get(_key)), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); - } + joiner.add(String.format("%sresult%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getResult()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); } // add `error` to the URL query string @@ -325,7 +311,7 @@ public X402McpResponse.Builder id(X402McpResponseId id) { this.instance.id = id; return this; } - public X402McpResponse.Builder result(Map result) { + public X402McpResponse.Builder result(Object result) { this.instance.result = result; return this; } diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/X402PaymentPayload.java b/java/src/main/java/com/coinbase/cdp/openapi/model/X402PaymentPayload.java index facc76f32..9bb5070fd 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/model/X402PaymentPayload.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/X402PaymentPayload.java @@ -31,8 +31,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.core.type.TypeReference; diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/X402PaymentRequirements.java b/java/src/main/java/com/coinbase/cdp/openapi/model/X402PaymentRequirements.java index 931094467..42719a663 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/model/X402PaymentRequirements.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/X402PaymentRequirements.java @@ -27,8 +27,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.core.type.TypeReference; diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/X402SupportedPaymentKind.java b/java/src/main/java/com/coinbase/cdp/openapi/model/X402SupportedPaymentKind.java index 61d95bc64..f0e6bf04b 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/model/X402SupportedPaymentKind.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/X402SupportedPaymentKind.java @@ -26,8 +26,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @@ -153,7 +151,7 @@ public static NetworkEnum fromValue(String value) { public static final String JSON_PROPERTY_EXTRA = "extra"; @jakarta.annotation.Nullable - private Map extra = new HashMap<>(); + private Object extra; public X402SupportedPaymentKind() { } @@ -230,34 +228,26 @@ public void setNetwork(@jakarta.annotation.Nonnull NetworkEnum network) { } - public X402SupportedPaymentKind extra(@jakarta.annotation.Nullable Map extra) { + public X402SupportedPaymentKind extra(@jakarta.annotation.Nullable Object extra) { this.extra = extra; return this; } - public X402SupportedPaymentKind putExtraItem(String key, Object extraItem) { - if (this.extra == null) { - this.extra = new HashMap<>(); - } - this.extra.put(key, extraItem); - return this; - } - /** * The optional additional scheme-specific payment info. * @return extra */ @jakarta.annotation.Nullable @JsonProperty(JSON_PROPERTY_EXTRA) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - public Map getExtra() { + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public Object getExtra() { return extra; } @JsonProperty(JSON_PROPERTY_EXTRA) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - public void setExtra(@jakarta.annotation.Nullable Map extra) { + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setExtra(@jakarta.annotation.Nullable Object extra) { this.extra = extra; } @@ -357,11 +347,7 @@ public String toUrlQueryString(String prefix) { // add `extra` to the URL query string if (getExtra() != null) { - for (String _key : getExtra().keySet()) { - joiner.add(String.format("%sextra%s%s=%s", prefix, suffix, - "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, _key, containerSuffix), - getExtra().get(_key), URLEncoder.encode(ApiClient.valueToString(getExtra().get(_key)), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); - } + joiner.add(String.format("%sextra%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getExtra()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); } return joiner.toString(); @@ -391,7 +377,7 @@ public X402SupportedPaymentKind.Builder network(NetworkEnum network) { this.instance.network = network; return this; } - public X402SupportedPaymentKind.Builder extra(Map extra) { + public X402SupportedPaymentKind.Builder extra(Object extra) { this.instance.extra = extra; return this; } diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/X402V1PaymentRequirements.java b/java/src/main/java/com/coinbase/cdp/openapi/model/X402V1PaymentRequirements.java index 8767cab8c..649d95c13 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/model/X402V1PaymentRequirements.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/X402V1PaymentRequirements.java @@ -25,8 +25,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @@ -149,7 +147,7 @@ public static NetworkEnum fromValue(String value) { public static final String JSON_PROPERTY_OUTPUT_SCHEMA = "outputSchema"; @jakarta.annotation.Nullable - private Map outputSchema = new HashMap<>(); + private Object outputSchema; public static final String JSON_PROPERTY_PAY_TO = "payTo"; @jakarta.annotation.Nonnull @@ -165,7 +163,7 @@ public static NetworkEnum fromValue(String value) { public static final String JSON_PROPERTY_EXTRA = "extra"; @jakarta.annotation.Nullable - private Map extra = new HashMap<>(); + private Object extra; public X402V1PaymentRequirements() { } @@ -314,34 +312,26 @@ public void setMimeType(@jakarta.annotation.Nonnull String mimeType) { } - public X402V1PaymentRequirements outputSchema(@jakarta.annotation.Nullable Map outputSchema) { + public X402V1PaymentRequirements outputSchema(@jakarta.annotation.Nullable Object outputSchema) { this.outputSchema = outputSchema; return this; } - public X402V1PaymentRequirements putOutputSchemaItem(String key, Object outputSchemaItem) { - if (this.outputSchema == null) { - this.outputSchema = new HashMap<>(); - } - this.outputSchema.put(key, outputSchemaItem); - return this; - } - /** * The optional JSON schema describing the resource output. * @return outputSchema */ @jakarta.annotation.Nullable @JsonProperty(JSON_PROPERTY_OUTPUT_SCHEMA) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - public Map getOutputSchema() { + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public Object getOutputSchema() { return outputSchema; } @JsonProperty(JSON_PROPERTY_OUTPUT_SCHEMA) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - public void setOutputSchema(@jakarta.annotation.Nullable Map outputSchema) { + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setOutputSchema(@jakarta.annotation.Nullable Object outputSchema) { this.outputSchema = outputSchema; } @@ -418,34 +408,26 @@ public void setAsset(@jakarta.annotation.Nonnull String asset) { } - public X402V1PaymentRequirements extra(@jakarta.annotation.Nullable Map extra) { + public X402V1PaymentRequirements extra(@jakarta.annotation.Nullable Object extra) { this.extra = extra; return this; } - public X402V1PaymentRequirements putExtraItem(String key, Object extraItem) { - if (this.extra == null) { - this.extra = new HashMap<>(); - } - this.extra.put(key, extraItem); - return this; - } - /** * The optional additional scheme-specific payment info. * @return extra */ @jakarta.annotation.Nullable @JsonProperty(JSON_PROPERTY_EXTRA) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - public Map getExtra() { + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public Object getExtra() { return extra; } @JsonProperty(JSON_PROPERTY_EXTRA) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - public void setExtra(@jakarta.annotation.Nullable Map extra) { + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setExtra(@jakarta.annotation.Nullable Object extra) { this.extra = extra; } @@ -574,11 +556,7 @@ public String toUrlQueryString(String prefix) { // add `outputSchema` to the URL query string if (getOutputSchema() != null) { - for (String _key : getOutputSchema().keySet()) { - joiner.add(String.format("%soutputSchema%s%s=%s", prefix, suffix, - "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, _key, containerSuffix), - getOutputSchema().get(_key), URLEncoder.encode(ApiClient.valueToString(getOutputSchema().get(_key)), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); - } + joiner.add(String.format("%soutputSchema%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getOutputSchema()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); } // add `payTo` to the URL query string @@ -598,11 +576,7 @@ public String toUrlQueryString(String prefix) { // add `extra` to the URL query string if (getExtra() != null) { - for (String _key : getExtra().keySet()) { - joiner.add(String.format("%sextra%s%s=%s", prefix, suffix, - "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, _key, containerSuffix), - getExtra().get(_key), URLEncoder.encode(ApiClient.valueToString(getExtra().get(_key)), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); - } + joiner.add(String.format("%sextra%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getExtra()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); } return joiner.toString(); @@ -644,7 +618,7 @@ public X402V1PaymentRequirements.Builder mimeType(String mimeType) { this.instance.mimeType = mimeType; return this; } - public X402V1PaymentRequirements.Builder outputSchema(Map outputSchema) { + public X402V1PaymentRequirements.Builder outputSchema(Object outputSchema) { this.instance.outputSchema = outputSchema; return this; } @@ -660,7 +634,7 @@ public X402V1PaymentRequirements.Builder asset(String asset) { this.instance.asset = asset; return this; } - public X402V1PaymentRequirements.Builder extra(Map extra) { + public X402V1PaymentRequirements.Builder extra(Object extra) { this.instance.extra = extra; return this; } diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/X402V2PaymentPayload.java b/java/src/main/java/com/coinbase/cdp/openapi/model/X402V2PaymentPayload.java index 534621d67..d558ef97e 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/model/X402V2PaymentPayload.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/X402V2PaymentPayload.java @@ -29,8 +29,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @@ -65,7 +63,7 @@ public class X402V2PaymentPayload { public static final String JSON_PROPERTY_EXTENSIONS = "extensions"; @jakarta.annotation.Nullable - private Map extensions = new HashMap<>(); + private Object extensions; public X402V2PaymentPayload() { } @@ -166,34 +164,26 @@ public void setResource(@jakarta.annotation.Nullable X402ResourceInfo resource) } - public X402V2PaymentPayload extensions(@jakarta.annotation.Nullable Map extensions) { + public X402V2PaymentPayload extensions(@jakarta.annotation.Nullable Object extensions) { this.extensions = extensions; return this; } - public X402V2PaymentPayload putExtensionsItem(String key, Object extensionsItem) { - if (this.extensions == null) { - this.extensions = new HashMap<>(); - } - this.extensions.put(key, extensionsItem); - return this; - } - /** * Optional protocol extensions. * @return extensions */ @jakarta.annotation.Nullable @JsonProperty(JSON_PROPERTY_EXTENSIONS) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - public Map getExtensions() { + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public Object getExtensions() { return extensions; } @JsonProperty(JSON_PROPERTY_EXTENSIONS) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - public void setExtensions(@jakarta.annotation.Nullable Map extensions) { + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setExtensions(@jakarta.annotation.Nullable Object extensions) { this.extensions = extensions; } @@ -300,11 +290,7 @@ public String toUrlQueryString(String prefix) { // add `extensions` to the URL query string if (getExtensions() != null) { - for (String _key : getExtensions().keySet()) { - joiner.add(String.format("%sextensions%s%s=%s", prefix, suffix, - "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, _key, containerSuffix), - getExtensions().get(_key), URLEncoder.encode(ApiClient.valueToString(getExtensions().get(_key)), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); - } + joiner.add(String.format("%sextensions%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getExtensions()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); } return joiner.toString(); @@ -338,7 +324,7 @@ public X402V2PaymentPayload.Builder resource(X402ResourceInfo resource) { this.instance.resource = resource; return this; } - public X402V2PaymentPayload.Builder extensions(Map extensions) { + public X402V2PaymentPayload.Builder extensions(Object extensions) { this.instance.extensions = extensions; return this; } diff --git a/java/src/main/java/com/coinbase/cdp/openapi/model/X402V2PaymentRequirements.java b/java/src/main/java/com/coinbase/cdp/openapi/model/X402V2PaymentRequirements.java index 8e1962d3a..095226e13 100644 --- a/java/src/main/java/com/coinbase/cdp/openapi/model/X402V2PaymentRequirements.java +++ b/java/src/main/java/com/coinbase/cdp/openapi/model/X402V2PaymentRequirements.java @@ -25,8 +25,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @@ -106,7 +104,7 @@ public static SchemeEnum fromValue(String value) { public static final String JSON_PROPERTY_EXTRA = "extra"; @jakarta.annotation.Nullable - private Map extra = new HashMap<>(); + private Object extra; public X402V2PaymentRequirements() { } @@ -255,34 +253,26 @@ public void setMaxTimeoutSeconds(@jakarta.annotation.Nonnull Integer maxTimeoutS } - public X402V2PaymentRequirements extra(@jakarta.annotation.Nullable Map extra) { + public X402V2PaymentRequirements extra(@jakarta.annotation.Nullable Object extra) { this.extra = extra; return this; } - public X402V2PaymentRequirements putExtraItem(String key, Object extraItem) { - if (this.extra == null) { - this.extra = new HashMap<>(); - } - this.extra.put(key, extraItem); - return this; - } - /** * The optional additional scheme-specific payment info. * @return extra */ @jakarta.annotation.Nullable @JsonProperty(JSON_PROPERTY_EXTRA) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - public Map getExtra() { + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public Object getExtra() { return extra; } @JsonProperty(JSON_PROPERTY_EXTRA) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - public void setExtra(@jakarta.annotation.Nullable Map extra) { + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setExtra(@jakarta.annotation.Nullable Object extra) { this.extra = extra; } @@ -403,11 +393,7 @@ public String toUrlQueryString(String prefix) { // add `extra` to the URL query string if (getExtra() != null) { - for (String _key : getExtra().keySet()) { - joiner.add(String.format("%sextra%s%s=%s", prefix, suffix, - "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, _key, containerSuffix), - getExtra().get(_key), URLEncoder.encode(ApiClient.valueToString(getExtra().get(_key)), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); - } + joiner.add(String.format("%sextra%s=%s", prefix, suffix, URLEncoder.encode(ApiClient.valueToString(getExtra()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); } return joiner.toString(); @@ -449,7 +435,7 @@ public X402V2PaymentRequirements.Builder maxTimeoutSeconds(Integer maxTimeoutSec this.instance.maxTimeoutSeconds = maxTimeoutSeconds; return this; } - public X402V2PaymentRequirements.Builder extra(Map extra) { + public X402V2PaymentRequirements.Builder extra(Object extra) { this.instance.extra = extra; return this; } diff --git a/openapi.yaml b/openapi.yaml index 1c8e395e2..b2ea0670a 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -16,6 +16,48 @@ servers: security: - apiKeyAuth: [] tags: + - name: Accounts + x-audience: public + x-slo-tier: + tier: beta + description: The Accounts APIs enable developers to create and manage accounts for their Entity. An Account is a container that holds assets and can be used for transacting. Accounts can be of different types including entity accounts, prime accounts, and business accounts. Support for Customer-owned accounts is in development. + - name: Deposit Destinations + x-audience: public + x-slo-tier: + tier: beta + description: |- + Deposit Destinations allow you to manage where funds can be deposited into your accounts. + + ## Crypto Deposit Destinations + + Crypto deposit destinations are cryptocurrency addresses that you can generate and fetch via the API. Once created, these addresses can receive cryptocurrency payments on their specified network and will settle in your account balance. + + **Metadata:** + You can attach metadata to any deposit destination you create to track the purpose or source of deposits. + + + **Example:** + ```json + { + "depositDestinationId": "depositDestination_123", + "accountId": "account_456", + "type": "crypto", + "crypto": { + "network": "base", + "address": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + }, + "target": { + "accountId": "account_789", + "asset": "usd" + }, + "status": "active", + "metadata": { + "customer_id": "cust_789", + "reference": "order-12345" + } + } + ``` + Use the list endpoint to retrieve all deposit destinations. - name: Embedded Wallets x-audience: public x-slo-tier: @@ -179,6 +221,11 @@ tags: This use case enables you to offer a full-featured onramp experience by redirecting users to a Coinbase-hosted page where they can choose to log into their existing Coinbase account or proceed as a guest. The Onramp Session API generates secure, single-use Onramp URLs with customizable parameters, allowing you to control available payment methods, preset transaction amounts, and cryptocurrencies for a tailored user experience. Refer to our [guide](https://docs.cdp.coinbase.com/onramp-&-offramp/onramp-apis/generating-onramp-url) for implementation details and customization options for this use case. + - name: Payment Methods + x-audience: public + x-slo-tier: + tier: beta + description: The Payment Methods APIs enable you to create and manage payment methods for accounts. Payment methods represent ways to send and receive payments, such as ACH transfers and Fedwire transfers. These APIs allow you to create, list, and retrieve payment method details for use in payment transfers and transactions. - name: Policy Engine x-audience: public x-slo-tier: @@ -629,6 +676,54 @@ tags: x-slo-tier: tier: ga description: The SQL API enables you to write performant, high-freshness, and endlessly flexible SQL queries against onchain data. + - name: Transfers + x-audience: public + x-slo-tier: + tier: beta + description: |- + **Transfers** represent both the request and execution of fund transfers from a source to a target. They provide upfront fee quotes and track the complete lifecycle from initiation through completion, failure, or reversal. + ## Fee Quotes + Every transfer provides a comprehensive fee quote in the `fees` array. This allows you to show users exactly what they'll pay before any money moves. + + To review fees before execution: + 1. Create a transfer with `execute: false` + 2. Review the `fees` array in the response + 3. Call `POST /transfers/{transferId}/execute` when ready to proceed + + + For automatic execution without fee review, create a transfer with `execute: true`. + + **Fee Expiration**: Fee quotes are valid for a limited time (typically 10-15 minutes from creation). The `expiresAt` field shows exactly when the fee quote will expire. If you don't execute before this time, you'll need to create a new transfer to get updated fees. + ## Fees + Transfer fees vary by source, target, amount and transfer type: + * **Bank fees** - Traditional banking fees for depositing funds (e.g., $15.00 wire transfer fee) + * **Conversion fees** - Fees for exchanging between different assets + * **Network fees** - Onchain transaction costs to complete the transfer (e.g., ETH gas fees) + + All fees are disclosed upfront in the `fees` array when you create a transfer. + ## Transfer Lifecycle + When you create a transfer, it will be in one of these statuses that determine what action you need to take: + * **`quoted`** - Transfer is ready but requires manual execution via the `/execute` endpoint + * **`processing`** - Transfer is being executed (no action needed - poll for completion) + * **`completed`** - Transfer completed successfully + * **`failed`** - Transfer failed (see `failureReason` for details) + ## Execution Control + * **`execute: true`**: Transfer will automatically attempt to execute + * **`execute: false`**: Transfer will be created in `quoted` status and you must call the `/execute` endpoint. Use this to obtain a fee quote or validate a transfer destination before deciding whether to execute the Transfer. + ## Sources and Targets + * A **source** can be an Account or a Payment Method + * A **target** can be an Account, Payment Method, Onchain Address, or Email Address + ## Transfer Execution + When a transfer reaches `completed` status, it contains the final execution details that delivered funds to the target and completion timestamps. + ## Failure Reasons + When a transfer fails, the `failureReason` field provides a human-readable description of what went wrong. + Common failure reasons include: + * "Insufficient balance to complete this transfer." + * "The recipient address is invalid for the selected network." + * "The recipient address failed security validation checks." + * "Unable to send to this recipient." + + Failure reason is only present when the transfer's status is `failed`. - name: Webhooks x-audience: public x-slo-tier: @@ -645,218 +740,246 @@ tags: - `POST /v2/x402/verify`: Verify a payment with a supported scheme and network. - `POST /v2/x402/settle`: Settle a payment with a supported scheme and network. paths: - /v2/end-users: - post: - summary: Create an end user - description: |- - Creates an end user. An end user is an entity that can own CDP EVM accounts, EVM smart accounts, and/or Solana accounts. 1 or more authentication methods must be associated with an end user. By default, no accounts are created unless the optional `evmAccount` and/or `solanaAccount` fields are provided. - This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. - operationId: createEndUser + /v2/accounts: + get: + summary: List accounts + description: List all accounts. The API will return all accounts that the API Key has Permissions to access. You can filter the results by using query parameters, which will be treated as a single conjunction (i.e. AND). Results are sorted by creation date in descending order (newest first). + operationId: listFoundationAccounts tags: - - End User Accounts + - Accounts + security: + - apiKeyAuth: [] x-audience: public + x-required-permissions: + permissions: + - accounts:read@entity + enforcement: any + parameters: + - $ref: '#/components/parameters/PageSize' + - $ref: '#/components/parameters/PageToken' + - name: type + in: query + required: false + description: Filter accounts by account type. When omitted, accounts of any type are returned. Combined with `owner` using AND. + schema: + $ref: '#/components/schemas/AccountType' + example: prime + responses: + '200': + description: Successfully listed accounts. + content: + application/json: + schema: + allOf: + - type: object + required: + - accounts + properties: + accounts: + type: array + description: The list of accounts. + items: + $ref: '#/components/schemas/Account' + - $ref: '#/components/schemas/ListResponse' + examples: + entity_owned: + summary: Account owned by your Entity + value: + accounts: + - accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + type: prime + owner: entity_af2937b0-9846-4fe7-bfe9-ccc22d935114 + name: My Business Account + createdAt: '2023-10-08T14:30:00Z' + updatedAt: '2023-10-08T14:30:00Z' + nextPageToken: eyJsYXN0X2lkIjogImFiYzEyMyIsICJ0aW1lc3RhbXAiOiAxNzA3ODIzNzAxfQ== + '400': + description: Invalid request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + invalid_request: + value: + errorType: invalid_request + errorMessage: Invalid query parameters. + post: + summary: Create account + description: Create an account for your Entity. Support for creating Customer-owned accounts is in development. + operationId: createFoundationAccount + tags: + - Accounts security: - apiKeyAuth: [] + x-audience: public + x-required-permissions: + permissions: + - accounts:write@entity + enforcement: any parameters: - - $ref: '#/components/parameters/XWalletAuth' - $ref: '#/components/parameters/IdempotencyKey' requestBody: + required: true content: application/json: schema: - type: object - properties: - userId: - description: |- - A stable, unique identifier for the end user. The `userId` must be unique across all end users in the developer's CDP Project. It must be between 1 and 100 characters long and can only contain alphanumeric characters and hyphens. - - If `userId` is not provided in the request, the server will generate a random UUID. - type: string - pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 - authenticationMethods: - $ref: '#/components/schemas/AuthenticationMethods' - evmAccount: - type: object - description: Configuration for creating an EVM account for the end user. - properties: - createSmartAccount: - type: boolean - description: If true, creates an EVM smart account and a default EVM EOA account as the owner. If false, only a EVM EOA account is created. - default: false - example: true - enableSpendPermissions: - type: boolean - description: If true, enables spend permissions for the EVM smart account. - example: true - solanaAccount: - type: object - description: Configuration for creating a Solana account for the end user. - properties: - createSmartAccount: - type: boolean - description: Only false is a valid option since currently smart accounts on Solana are not supported. - default: false - example: false - required: - - authenticationMethods + $ref: '#/components/schemas/CreateAccountRequest' examples: - default_behavior: - summary: Default (no accounts created) - value: - authenticationMethods: - - type: email - email: user@example.com - evm_only: - summary: EVM account only - value: - authenticationMethods: - - type: email - email: user@example.com - evmAccount: {} - evm_with_smart_account: - summary: EVM only with smart account - value: - authenticationMethods: - - type: email - email: user@example.com - evmAccount: - createSmartAccount: true - solana_only: - summary: Solana account only - value: - authenticationMethods: - - type: sms - phoneNumber: '+15555551234' - solanaAccount: - createSmartAccount: false - evm_and_solana: - summary: Both EVM and Solana accounts + entity_owned: + summary: Create an account owned by your Entity value: - authenticationMethods: - - type: sms - phoneNumber: '+15555551234' - evmAccount: - createSmartAccount: true - solanaAccount: - createSmartAccount: false + name: My Business Account responses: - '201': - description: Successfully created end user. + '200': + description: Successfully created account. content: application/json: schema: - $ref: '#/components/schemas/EndUser' + $ref: '#/components/schemas/Account' examples: - default_no_accounts: - summary: Default behavior - No accounts created + entity_owned: + summary: Account owned by your Entity + value: + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + type: cdp + owner: entity_af2937b0-9846-4fe7-bfe9-ccc22d935114 + name: My Business Account + createdAt: '2023-10-08T14:30:00Z' + updatedAt: '2023-10-08T14:30:00Z' + '400': + description: Invalid request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + invalid_request: value: - userId: user-001 - authenticationMethods: - - type: email - email: user@example.com - evmAccounts: [] - evmAccountObjects: [] - evmSmartAccounts: [] - evmSmartAccountObjects: [] - solanaAccounts: [] - solanaAccountObjects: [] - createdAt: '2025-11-17T10:00:00Z' - evm_smart_account_only: - summary: EVM smart account only + errorType: invalid_request + errorMessage: Invalid account creation request. + '422': + $ref: '#/components/responses/IdempotencyError' + '503': + $ref: '#/components/responses/EndpointUnavailableError' + /v2/accounts/{accountId}: + get: + summary: Get account + description: Get an account by its ID. + operationId: getFoundationAccountById + tags: + - Accounts + security: + - apiKeyAuth: [] + x-audience: public + x-required-permissions: + permissions: + - accounts:read@entity + enforcement: any + parameters: + - name: accountId + in: path + required: true + description: The ID of the account to retrieve. + schema: + $ref: '#/components/schemas/AccountId' + example: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + responses: + '200': + description: Successfully got account. + content: + application/json: + schema: + $ref: '#/components/schemas/Account' + examples: + entity_owned: + summary: Account owned by your Entity + value: + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + type: prime + owner: entity_af2937b0-9846-4fe7-bfe9-ccc22d935114 + name: My Business Account + createdAt: '2023-10-08T14:30:00Z' + updatedAt: '2023-10-08T14:30:00Z' + '400': + description: Invalid request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + invalid_request: value: - userId: user-003 - authenticationMethods: - - type: email - email: user@example.com - evmAccounts: - - '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - evmAccountObjects: - - address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - createdAt: '2025-11-17T10:00:00Z' - evmSmartAccounts: - - '0x842d35Cc6634C0532925a3b844Bc454e4438f55f' - evmSmartAccountObjects: - - address: '0x842d35Cc6634C0532925a3b844Bc454e4438f55f' - ownerAddresses: - - '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - createdAt: '2025-11-17T10:00:00Z' - solanaAccounts: [] - solanaAccountObjects: [] - createdAt: '2025-11-17T10:00:00Z' - solana_only: - summary: Solana account only + errorType: invalid_request + errorMessage: Invalid account ID. + '404': + description: Account not found. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + not_found: value: - userId: user-004 - authenticationMethods: - - type: sms - phoneNumber: '+15555551234' - evmAccounts: [] - evmAccountObjects: [] - evmSmartAccounts: [] - evmSmartAccountObjects: [] - solanaAccounts: - - HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT - solanaAccountObjects: - - address: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT - createdAt: '2025-11-17T10:00:00Z' - createdAt: '2025-11-17T10:00:00Z' - evm_no_smart_account: - summary: EVM without smart account - value: - userId: user-004 - authenticationMethods: - - type: email - email: user@example.com - evmAccounts: - - '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - evmAccountObjects: - - address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - createdAt: '2025-11-17T10:00:00Z' - evmSmartAccounts: [] - evmSmartAccountObjects: [] - solanaAccounts: [] - solanaAccountObjects: [] - createdAt: '2025-11-17T10:00:00Z' - multiple_accounts: - summary: End user with multiple accounts created - value: - userId: user-005 - authenticationMethods: - - type: email - email: user@example.com - evmAccounts: - - '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - - '0x8F2A9B5C3D4E6F7A8B9C0D1E2F3A4B5C6D7E8F9A' - - '0xA1B2C3D4E5F6A7B8C9D0E1F2A3B4C5D6E7F8A9B0' - evmAccountObjects: - - address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - createdAt: '2025-11-17T10:00:00Z' - - address: '0x8F2A9B5C3D4E6F7A8B9C0D1E2F3A4B5C6D7E8F9A' - createdAt: '2025-11-17T10:05:00Z' - - address: '0xA1B2C3D4E5F6A7B8C9D0E1F2A3B4C5D6E7F8A9B0' - createdAt: '2025-11-17T10:10:00Z' - evmSmartAccounts: - - '0x842d35Cc6634C0532925a3b844Bc454e4438f55f' - - '0x9D3E4F5A6B7C8D9E0F1A2B3C4D5E6F7A8B9C0D1E' - evmSmartAccountObjects: - - address: '0x842d35Cc6634C0532925a3b844Bc454e4438f55f' - ownerAddresses: - - '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - createdAt: '2025-11-17T10:02:00Z' - - address: '0x9D3E4F5A6B7C8D9E0F1A2B3C4D5E6F7A8B9C0D1E' - ownerAddresses: - - '0x8F2A9B5C3D4E6F7A8B9C0D1E2F3A4B5C6D7E8F9A' - createdAt: '2025-11-17T10:07:00Z' - solanaAccounts: - - HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT - - 9ZN8wT6gKxLmJvP4rQnYt7VxKwL3mN9rT8Qx2WzJpK5s - solanaAccountObjects: - - address: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT - createdAt: '2025-11-17T10:15:00Z' - - address: 9ZN8wT6gKxLmJvP4rQnYt7VxKwL3mN9rT8Qx2WzJpK5s - createdAt: '2025-11-17T10:20:00Z' - createdAt: '2025-11-17T10:00:00Z' + errorType: not_found + errorMessage: Account not found. + /v2/accounts/{accountId}/balances: + get: + summary: List balances for account + description: List the balances for an account. Results are sorted by native-fiat equivalent balance in descending order. + operationId: listBalances + tags: + - Accounts + security: + - apiKeyAuth: [] + x-audience: public + x-required-permissions: + permissions: + - accounts:read@entity + enforcement: any + parameters: + - name: accountId + in: path + required: true + description: The unique identifier of the account. + schema: + $ref: '#/components/schemas/AccountId' + example: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + - $ref: '#/components/parameters/PageSize' + - $ref: '#/components/parameters/PageToken' + responses: + '200': + description: Successfully listed balances. + content: + application/json: + schema: + allOf: + - $ref: '#/components/schemas/Balances' + - $ref: '#/components/schemas/ListResponse' + example: + balances: + - asset: + symbol: btc + type: crypto + name: Bitcoin + decimals: 8 + amount: + btc: + available: '2.5' + total: '3.0' + usd: + available: '252705.4' + total: '303246.48' + - asset: + symbol: usd + type: fiat + name: United States Dollar + decimals: 2 + amount: + usd: + available: '90' + total: '100' + nextPageToken: eyJsYXN0X2lkIjogImFiYzEyMyIsICJ0aW1lc3RhbXAiOiAxNzA3ODIzNzAxfQ== '400': description: Invalid request. content: @@ -867,11 +990,7 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: At least one authentication method must be provided. - solana_smart_account_not_supported: - value: - errorType: invalid_request - errorMessage: The request contains one or more unsupported options. + errorMessage: Invalid account ID or query parameters. '401': description: Unauthorized. content: @@ -882,128 +1001,82 @@ paths: unauthorized: value: errorType: unauthorized - errorMessage: Wallet authentication error. - '402': - $ref: '#/components/responses/PaymentMethodRequiredError' - '422': - $ref: '#/components/responses/IdempotencyError' - '500': - $ref: '#/components/responses/InternalServerError' - get: - x-audience: public - summary: List end users - description: |- - Lists the end users belonging to the developer's CDP Project. - By default, the response is sorted by creation date in ascending order and paginated to 20 users per page. - operationId: listEndUsers - tags: - - End User Accounts - security: - - apiKeyAuth: [] - parameters: - - name: pageSize - description: The number of end users to return per page. - in: query - required: false - schema: - type: integer - default: 20 - minimum: 1 - maximum: 100 - example: 10 - - name: pageToken - description: The token for the desired page of end users. Will be empty if there are no more end users to fetch. - in: query - required: false - schema: - type: string - example: eyJsYXN0X2lkIjogImFiYzEyMyIsICJ0aW1lc3RhbXAiOiAxNzA3ODIzNzAxfQ== - - name: sort - description: Sort end users. Defaults to ascending order (oldest first). - in: query - required: false - schema: - type: array - items: - type: string - enum: - - createdAt=asc - - createdAt=desc - example: - - createdAt=asc - style: form - explode: false - responses: - '200': - description: Successfully retrieved end users. + errorMessage: Authentication required. + '404': + description: Account not found. content: application/json: schema: - allOf: - - type: object - required: - - endUsers - properties: - endUsers: - type: array - description: The list of end users. - items: - $ref: '#/components/schemas/EndUser' - - $ref: '#/components/schemas/ListResponse' - '400': - description: Invalid request. + $ref: '#/components/schemas/Error' + examples: + not_found: + value: + errorType: not_found + errorMessage: Account not found. + '500': + description: Internal server error. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - invalid_request: + internal_error: value: - errorType: invalid_request - errorMessage: Invalid project ID. - '401': - $ref: '#/components/responses/UnauthorizedError' - '500': - $ref: '#/components/responses/InternalServerError' - '502': - $ref: '#/components/responses/BadGatewayError' + errorType: internal_server_error + errorMessage: An internal server error occurred. '503': - $ref: '#/components/responses/ServiceUnavailableError' - /v2/end-users/auth/validate-token: - post: - x-audience: public - summary: Validate end user access token - description: |- - Validates the end user's access token and returns the end user's information. Returns an error if the access token is invalid or expired. - - This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. - operationId: validateEndUserAccessToken + $ref: '#/components/responses/EndpointUnavailableError' + /v2/accounts/{accountId}/balances/{asset}: + get: + summary: Get balance for account + description: Get the balance for an account by asset. + operationId: getBalanceByAsset tags: - - End User Accounts + - Accounts security: - apiKeyAuth: [] - requestBody: - content: - application/json: - schema: - type: object - description: The request body for a developer to verify an end user's access token. - properties: - accessToken: - type: string - description: The access token in JWT format to verify. - example: eyJhbGciOiJFUzI1NiIsImtpZCI6IjA1ZGNmYTU1LWY1NzktNDg5YS1iNThhLTFlMDI5Nzk0N2VlNiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJjZHAtYXBpIiwiYXV0aF90eXBlIjoiZW1haWwiLCJleHAiOjE3NTM5ODAyOTksImlhdCI6MTc1Mzk3ODQ5OSwiaXNzIjoiY2RwLWFwaSIsImp0aSI6IjA3ZWY5M2JlLTYzMDQtNGQ1YS05NmE3LWJlMGI5MWI0ZTE3NCIsInByb2plY3RfaWQiOiJjNzRkOGI4OC0wOTNiLTQyZDItOGE4Yy1kZGM1YzVlMGViNDMiLCJzdWIiOiJjYTM4YTM4ZC0xNmE5LTRkMjYtYTcxZC0zOWY2NmY5YzZiN2UifQ.1SU0pOy-WR002qUw4hd_UmZWRSLz-ZL6v7PvQvZMKVE6a51x_tqeUeRGaTGuYl1whg0eccMObmK7FqXKRH6E4g - required: - - accessToken + x-audience: public + x-required-permissions: + permissions: + - accounts:read@entity + enforcement: any + parameters: + - name: accountId + in: path + required: true + description: The unique identifier of the account. + schema: + $ref: '#/components/schemas/AccountId' + example: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + - name: asset + in: path + required: true + description: The symbol of the asset. + schema: + $ref: '#/components/schemas/Asset' + example: btc responses: '200': - description: Confirms that the access token is valid and returns the end user's information. + description: Successfully got balance. content: application/json: schema: - $ref: '#/components/schemas/EndUser' + $ref: '#/components/schemas/Balance' + example: + asset: + symbol: btc + type: crypto + name: Bitcoin + decimals: 8 + amount: + btc: + available: '2.5' + total: '3.0' + usd: + available: '252705.4' + total: '303246.48' '400': - description: Request body is invalid. + description: Invalid request. content: application/json: schema: @@ -1012,9 +1085,9 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: Missing access token + errorMessage: Invalid account ID or asset symbol. '401': - description: Request is not properly authenticated, or the access token is invalid or expired. + description: Unauthorized. content: application/json: schema: @@ -1023,9 +1096,9 @@ paths: unauthorized: value: errorType: unauthorized - errorMessage: 'Invalid JWT issuer: not-cdp-api, expected: cdp-api' + errorMessage: Authentication required. '404': - description: End user not found. + description: Account or asset not found. content: application/json: schema: @@ -1034,200 +1107,107 @@ paths: not_found: value: errorType: not_found - errorMessage: End user not found + errorMessage: Account or asset not found. '500': - $ref: '#/components/responses/InternalServerError' - /v2/end-users/{userId}: - get: - x-audience: public - summary: Get an end user - description: |- - Gets an end user by ID. - - This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. - operationId: getEndUser - tags: - - End User Accounts - security: - - apiKeyAuth: [] - parameters: - - name: userId - in: path - required: true - description: The ID of the end user to get. - schema: - type: string - pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 - responses: - '200': - description: Successfully got end user. - content: - application/json: - schema: - $ref: '#/components/schemas/EndUser' - '404': - description: Not found. + description: Internal server error. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - not_found: + internal_error: value: - errorType: not_found - errorMessage: End user with the given ID not found. - '500': - $ref: '#/components/responses/InternalServerError' - /v2/end-users/lookup: + errorType: internal_server_error + errorMessage: An internal server error occurred. + '503': + $ref: '#/components/responses/EndpointUnavailableError' + /v2/deposit-destinations: get: + summary: List deposit destinations + description: List deposit destinations. You can optionally filter the results by type, account ID, network, or cryptocurrency address. Results are sorted by creation date in descending order (newest first). + operationId: listDepositDestinations x-audience: public - summary: Look up end users by identity - description: |- - Looks up end users. Exactly one lookup type must be provided per request: - - - **email**: searches across all email-based authentication methods - (email, Google, Apple, GitHub). May return multiple end users if the - same email address appears across different auth methods. - - - **oauthProvider + oauthSubject**: looks up a user by their OAuth - provider and subject (the `sub` claim from the provider's ID token). - Both params must be provided together. - - - **phoneNumber**: looks up a user by their SMS-verified phone number. - - Returns all matching end users. If no end users match, an empty array is returned. - - This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. - operationId: lookupEndUser + x-required-permissions: + permissions: + - accounts:read@entity + - accounts:read@project + enforcement: any tags: - - End User Accounts + - Deposit Destinations security: - apiKeyAuth: [] parameters: - - name: email + - name: accountId in: query required: false - description: The email address to search for across all email-based authentication methods. + description: Filter deposit destinations by account ID. schema: - type: string - format: email - example: user@example.com - - name: oauthProvider + $ref: '#/components/schemas/AccountId' + example: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + - name: address in: query required: false - description: The OAuth provider to search by. Must be provided together with oauthSubject. + description: Filter deposit destinations by the cryptocurrency address. schema: - $ref: '#/components/schemas/OAuth2ProviderType' - example: google - - name: oauthSubject + type: string + description: The cryptocurrency address to filter by. Format depends on the network (e.g., 0x-prefixed for EVM networks, base58 for Solana). + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + - name: type in: query required: false - description: The OAuth subject (the `sub` claim from the provider's ID token). Must be provided together with oauthProvider. + description: Filter deposit destinations by type. schema: - type: string - example: '1234567890' - - name: phoneNumber + $ref: '#/components/schemas/DepositDestinationType' + example: crypto + - name: network in: query required: false - description: The E.164-formatted phone number to search for. Must be URL-encoded when passed as a query parameter (e.g. `+14155552671` → `%2B14155552671`). + description: Filter deposit destinations by network. schema: type: string - pattern: ^\+[1-9]\d{1,14}$ - example: '+14155552671' + description: The blockchain network to filter by (e.g., base, ethereum). Only applies to crypto deposit destinations. + example: base + - $ref: '#/components/parameters/PageSize' + - $ref: '#/components/parameters/PageToken' responses: '200': - description: Successfully looked up end users. + description: Successfully listed deposit destinations. content: application/json: schema: - type: object - required: - - endUsers - properties: - endUsers: - type: array - description: The list of end users matching the lookup. - items: - $ref: '#/components/schemas/EndUser' + allOf: + - type: object + required: + - depositDestinations + properties: + depositDestinations: + type: array + description: The list of deposit destinations. + items: + $ref: '#/components/schemas/DepositDestination' + - $ref: '#/components/schemas/ListResponse' examples: - email_match: - summary: End user found by email - value: - endUsers: - - userId: user-001 - authenticationMethods: - - type: email - email: user@example.com - evmAccounts: [] - evmAccountObjects: [] - evmSmartAccounts: [] - evmSmartAccountObjects: [] - solanaAccounts: [] - solanaAccountObjects: [] - createdAt: '2025-11-17T10:00:00Z' - multiple_email_matches: - summary: Multiple end users with same email across auth methods - value: - endUsers: - - userId: user-001 - authenticationMethods: - - type: email - email: user@example.com - evmAccounts: [] - evmAccountObjects: [] - evmSmartAccounts: [] - evmSmartAccountObjects: [] - solanaAccounts: [] - solanaAccountObjects: [] - createdAt: '2025-11-17T10:00:00Z' - - userId: user-002 - authenticationMethods: - - type: google - sub: google-sub-123 - email: user@example.com - evmAccounts: [] - evmAccountObjects: [] - evmSmartAccounts: [] - evmSmartAccountObjects: [] - solanaAccounts: [] - solanaAccountObjects: [] - createdAt: '2025-11-17T11:00:00Z' - oauth_match: - summary: End user found by OAuth subject - value: - endUsers: - - userId: user-003 - authenticationMethods: - - type: google - sub: '1234567890' - email: user@example.com - evmAccounts: [] - evmAccountObjects: [] - evmSmartAccounts: [] - evmSmartAccountObjects: [] - solanaAccounts: [] - solanaAccountObjects: [] - createdAt: '2025-11-17T12:00:00Z' - phone_match: - summary: End user found by phone number - value: - endUsers: - - userId: user-004 - authenticationMethods: - - type: sms - phoneNumber: '+14155552671' - evmAccounts: [] - evmAccountObjects: [] - evmSmartAccounts: [] - evmSmartAccountObjects: [] - solanaAccounts: [] - solanaAccountObjects: [] - createdAt: '2025-11-17T13:00:00Z' - no_matches: - summary: No end users found - value: - endUsers: [] + crypto: + summary: Crypto deposit destination + value: + depositDestinations: + - depositDestinationId: depositDestination_af2937b0-9846-4fe7-bfe9-ccc22d935114 + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + type: crypto + network: base + address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + crypto: + network: base + address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + target: + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + asset: usd + status: active + metadata: + customer_id: 123e4567-e89b-12d3-a456-426614174000 + reference: order-12345 + createdAt: '2023-10-08T14:30:00Z' + updatedAt: '2023-10-08T14:30:00Z' '400': description: Invalid request. content: @@ -1235,77 +1215,95 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - no_lookup_param: - summary: No lookup parameter provided - value: - errorType: invalid_request - errorMessage: 'Exactly one lookup type must be provided: email, phoneNumber, or oauthProvider+oauthSubject' - multiple_lookup_params: - summary: Multiple lookup parameters provided - value: - errorType: invalid_request - errorMessage: 'Exactly one lookup type must be provided: email, phoneNumber, or oauthProvider+oauthSubject' - oauth_missing_subject: - summary: oauthProvider provided without oauthSubject + invalid_request: value: errorType: invalid_request - errorMessage: oauthProvider and oauthSubject must be provided together + errorMessage: Invalid query parameters. '401': - $ref: '#/components/responses/UnauthorizedError' + description: Unauthorized. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + unauthorized: + value: + errorType: unauthorized + errorMessage: Authentication required. '500': - $ref: '#/components/responses/InternalServerError' - /v2/end-users/{userId}/evm: + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + internal_error: + value: + errorType: internal_server_error + errorMessage: An internal server error occurred. post: - summary: Add an EVM account to an end user - description: |- - Adds a new EVM EOA account to an existing end user. End users can have up to 10 EVM accounts. - This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. - operationId: addEndUserEvmAccount - tags: - - End User Accounts + summary: Create deposit destination + description: Create a new deposit destination for an account. A deposit destination is a cryptocurrency address that can be used to receive funds. The address will be generated for the specified network. + operationId: createDepositDestination x-audience: public + x-required-permissions: + permissions: + - accounts:write@entity + enforcement: any + tags: + - Deposit Destinations security: - apiKeyAuth: [] parameters: - - name: userId - in: path - required: true - description: The ID of the end user to add the account to. - schema: - type: string - pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 - - $ref: '#/components/parameters/XWalletAuth' - $ref: '#/components/parameters/IdempotencyKey' requestBody: - required: false + required: true content: application/json: schema: - type: object + $ref: '#/components/schemas/CreateDepositDestinationRequest' examples: - default: - summary: Create EVM EOA account - value: {} + crypto: + summary: Create a crypto deposit destination + value: + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + type: crypto + crypto: + network: base + target: + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + asset: usd + metadata: + customer_id: 123e4567-e89b-12d3-a456-426614174000 + reference: order-12345 responses: '201': - description: Successfully added EVM account to end user. + description: Successfully created deposit destination. content: application/json: schema: - type: object - required: - - evmAccount - properties: - evmAccount: - $ref: '#/components/schemas/EndUserEvmAccount' + $ref: '#/components/schemas/DepositDestination' examples: - default: - summary: EVM EOA account created + crypto: + summary: Crypto deposit destination value: - evmAccount: + depositDestinationId: depositDestination_af2937b0-9846-4fe7-bfe9-ccc22d935114 + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + type: crypto + network: base + address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + crypto: + network: base address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - createdAt: '2025-11-17T10:00:00Z' + target: + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + asset: usd + status: active + metadata: + customer_id: 123e4567-e89b-12d3-a456-426614174000 + reference: order-12345 + createdAt: '2023-10-08T14:30:00Z' + updatedAt: '2023-10-08T14:30:00Z' '400': description: Invalid request. content: @@ -1313,10 +1311,10 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - max_accounts_reached: + invalid_request: value: errorType: invalid_request - errorMessage: Maximum number of EVM accounts (10) reached for this end user. + errorMessage: Invalid network specified or missing required fields. '401': description: Unauthorized. content: @@ -1327,11 +1325,9 @@ paths: unauthorized: value: errorType: unauthorized - errorMessage: Wallet authentication error. - '402': - $ref: '#/components/responses/PaymentMethodRequiredError' + errorMessage: Authentication required. '404': - description: End user not found. + description: Account not found. content: application/json: schema: @@ -1340,79 +1336,73 @@ paths: not_found: value: errorType: not_found - errorMessage: End user with the given ID not found. + errorMessage: Account not found. '422': $ref: '#/components/responses/IdempotencyError' '500': - $ref: '#/components/responses/InternalServerError' - '502': - $ref: '#/components/responses/BadGatewayError' + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + internal_error: + value: + errorType: internal_server_error + errorMessage: An internal server error occurred. '503': - $ref: '#/components/responses/ServiceUnavailableError' - /v2/end-users/{userId}/evm-smart-account: - post: - summary: Add an EVM smart account to an end user - description: |- - Creates an EVM smart account for an existing end user. The backend will create a new EVM EOA account to serve as the owner of the smart account. - This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. - operationId: addEndUserEvmSmartAccount - tags: - - End User Accounts + $ref: '#/components/responses/EndpointUnavailableError' + /v2/deposit-destinations/{depositDestinationId}: + get: + summary: Get deposit destination + description: Get a specific deposit destination by its ID. + operationId: getDepositDestinationById x-audience: public + x-required-permissions: + permissions: + - accounts:read@entity + - accounts:read@project + enforcement: any + tags: + - Deposit Destinations security: - apiKeyAuth: [] parameters: - - name: userId + - name: depositDestinationId in: path required: true - description: The ID of the end user to add the smart account to. + description: The ID of the deposit address to retrieve. schema: - type: string - pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 - - $ref: '#/components/parameters/XWalletAuth' - - $ref: '#/components/parameters/IdempotencyKey' - requestBody: - required: false - content: - application/json: - schema: - type: object - properties: - enableSpendPermissions: - type: boolean - description: If true, enables spend permissions for the EVM smart account. - default: false - example: true - examples: - default: - summary: Create smart account - value: {} - with_spend_permissions: - summary: Create smart account with spend permissions - value: - enableSpendPermissions: true + $ref: '#/components/schemas/DepositDestinationId' + example: depositDestination_af2937b0-9846-4fe7-bfe9-ccc22d935114 responses: - '201': - description: Successfully added EVM smart account to end user. + '200': + description: Successfully retrieved deposit destination. content: application/json: schema: - type: object - required: - - evmSmartAccount - properties: - evmSmartAccount: - $ref: '#/components/schemas/EndUserEvmSmartAccount' + $ref: '#/components/schemas/DepositDestination' examples: - default: - summary: EVM smart account created + crypto: + summary: Crypto deposit destination value: - evmSmartAccount: - address: '0x842d35Cc6634C0532925a3b844Bc454e4438f55f' - ownerAddresses: - - '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - createdAt: '2025-11-17T10:00:00Z' + depositDestinationId: depositDestination_af2937b0-9846-4fe7-bfe9-ccc22d935114 + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + type: crypto + network: base + address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + crypto: + network: base + address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + target: + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + asset: usd + status: active + metadata: + customer_id: 123e4567-e89b-12d3-a456-426614174000 + reference: order-12345 + createdAt: '2023-10-08T14:30:00Z' + updatedAt: '2023-10-08T14:30:00Z' '400': description: Invalid request. content: @@ -1420,10 +1410,10 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - max_accounts_reached: + invalid_request: value: errorType: invalid_request - errorMessage: Maximum number of EVM smart accounts (10) reached for this end user. + errorMessage: Invalid deposit address ID. '401': description: Unauthorized. content: @@ -1434,11 +1424,9 @@ paths: unauthorized: value: errorType: unauthorized - errorMessage: Wallet authentication error. - '402': - $ref: '#/components/responses/PaymentMethodRequiredError' + errorMessage: Authentication required. '404': - description: End user not found. + description: Deposit address not found. content: application/json: schema: @@ -1447,67 +1435,279 @@ paths: not_found: value: errorType: not_found - errorMessage: End user with the given ID not found. - '422': - $ref: '#/components/responses/IdempotencyError' + errorMessage: Deposit address not found. '500': - $ref: '#/components/responses/InternalServerError' - '502': - $ref: '#/components/responses/BadGatewayError' - '503': - $ref: '#/components/responses/ServiceUnavailableError' - /v2/end-users/{userId}/solana: + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + internal_error: + value: + errorType: internal_server_error + errorMessage: An internal server error occurred. + /v2/transfers: post: - summary: Add a Solana account to an end user + summary: Create transfer description: |- - Adds a new Solana account to an existing end user. End users can have up to 10 Solana accounts. - This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. - operationId: addEndUserSolanaAccount - tags: - - End User Accounts + Create a new transfer to move funds from a source to a target. + All transfers first transition to `quoted`. If `execute: false`, the transfer stays quoted until you call `/v2/transfers/{transferId}/execute`. + If `execute: true`, quoted status emits momentarily before the transfer moves to `processing`, where execution proceeds. Subscribe to the transfers webhook to follow progress in real time instead of polling. + operationId: createTransfer x-audience: public + x-required-permissions: + permissions: + - transfers:write@entity + enforcement: any + tags: + - Transfers security: - apiKeyAuth: [] parameters: - - name: userId - in: path - required: true - description: The ID of the end user to add the account to. - schema: - type: string - pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 - - $ref: '#/components/parameters/XWalletAuth' - $ref: '#/components/parameters/IdempotencyKey' requestBody: - required: false content: application/json: schema: - type: object - examples: - default: - summary: Create Solana account - value: {} + $ref: '#/components/schemas/TransferRequest' + example: + source: + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + asset: usd + target: + address: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' + network: base + asset: usdc + amount: '100.00' + asset: usd + execute: false + validateOnly: false + metadata: + invoiceId: '12345' + reference: 'Payment for invoice #12345' + travelRule: + isSelf: false + isIntermediary: true + originator: + name: John Doe + address: + line1: 123 Main St + line2: Unit 201 + city: Luxembourg + postCode: L-1234 + countryCode: LU + financialInstitution: PayPal, Inc. + vaspName: Fidelity Digital Asset Services, LLC + vaspAddress: + line1: 123 Market St + line2: Suite 400 + city: San Francisco + state: California + postCode: '94105' + countryCode: US + vaspIdentifier: 5493001KJTIIGC8Y1R17 + beneficiary: + name: Jane Smith + address: + line1: 456 Oak Ave + city: Paris + postCode: '75001' + countryCode: FR + walletType: custodial responses: - '201': - description: Successfully added Solana account to end user. + '200': + description: Successfully created transfer. content: application/json: schema: - type: object - required: - - solanaAccount - properties: - solanaAccount: - $ref: '#/components/schemas/EndUserSolanaAccount' + $ref: '#/components/schemas/Transfer' examples: - default: - summary: Solana account created + regular: + $ref: '#/components/examples/RegularTransferQuoted' + fx_quoted: + $ref: '#/components/examples/FxTransferQuoted' + '400': + description: Invalid request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + invalid_request: value: - solanaAccount: - address: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT - createdAt: '2025-11-17T10:00:00Z' + errorType: invalid_request + errorMessage: Invalid query parameters. + '422': + $ref: '#/components/responses/IdempotencyError' + get: + summary: List transfers + description: |- + List transfers for your organization. Use this to view and monitor your transfer activity. + + **Status Filtering**: Filter by specific status to efficiently manage transfers: + * `?status=processing` - Monitor active transfers. + * `?status=quoted` - Find transfers awaiting execution. + * `?status=failed` - Review failed transfers for troubleshooting. + * `?status=completed` - Find completed transfers. + + **Account Filtering**: Filter by account ID to find transfers involving a specific account: + * `?accountId=` - All transfers where the account is either source or target (OR semantics). + * `?sourceAccountId=` - Only transfers where the account is the source (outbound). + * `?targetAccountId=` - Only transfers where the account is the target (inbound). + Providing `accountId` together with `sourceAccountId` or `targetAccountId` is a validation error and returns HTTP 400. + + **Date Range Filtering**: Filter by creation or last-updated time for reconciliation: + * `?createdAfter=2026-01-01T00:00:00Z&createdBefore=2026-01-31T23:59:59Z` - Transfers created within a date range. + * `?updatedAfter=2026-01-01T00:00:00Z` - Transfers updated since a given time. Useful for incremental sync. + + **Asset Filtering**: Filter by source or target asset symbol: + * `?sourceAsset=usd` - Transfers funded from a USD account. + * `?targetAsset=usdc` - Transfers delivering USDC to the target. + + **Other Filters**: + * `?sourceAddress=0x...` - Transfers from a specific on-chain source address. + * `?targetAddress=0x...` - Transfers to a specific on-chain destination address. + * `?targetEmail=user@example.com` - Transfers to a specific email recipient. + * `?transferId=transfer_...` - Look up a single transfer by ID; bypasses pagination. + operationId: listTransfers + x-audience: public + x-required-permissions: + permissions: + - transfers:read@entity + - transfers:read@project + enforcement: any + tags: + - Transfers + security: + - apiKeyAuth: [] + parameters: + - name: status + in: query + required: false + description: Filter transfers by status. Useful for building dashboards, monitoring active transfers, or finding transfers needing action. + example: quoted + schema: + $ref: '#/components/schemas/TransferStatus' + - name: accountId + in: query + required: false + description: Filter transfers by account ID. Returns transfers where the specified account is either the source or target (OR semantics). Cannot be combined with `sourceAccountId` or `targetAccountId`. + schema: + $ref: '#/components/schemas/AccountId' + example: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + - name: sourceAccountId + in: query + required: false + description: Filter transfers by source account ID. Returns only transfers where the specified account is the source. Cannot be combined with `accountId`. + schema: + $ref: '#/components/schemas/AccountId' + example: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + - name: targetAccountId + in: query + required: false + description: Filter transfers by target account ID. Returns only transfers where the specified account is the target. Cannot be combined with `accountId`. + schema: + $ref: '#/components/schemas/AccountId' + example: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + - name: createdAfter + in: query + required: false + description: Filter transfers to those created at or after this datetime (inclusive). ISO 8601 format. + example: '2026-01-01T00:00:00Z' + schema: + type: string + format: date-time + - name: createdBefore + in: query + required: false + description: Filter transfers to those created at or before this datetime (inclusive). ISO 8601 format. + example: '2026-01-31T23:59:59Z' + schema: + type: string + format: date-time + - name: updatedAfter + in: query + required: false + description: Filter transfers to those updated at or after this datetime (inclusive). ISO 8601 format. Useful for incremental sync — poll for transfers that changed state since your last check. + example: '2026-01-01T00:00:00Z' + schema: + type: string + format: date-time + - name: updatedBefore + in: query + required: false + description: Filter transfers to those updated at or before this datetime (inclusive). ISO 8601 format. + example: '2026-01-31T23:59:59Z' + schema: + type: string + format: date-time + - name: sourceAsset + in: query + required: false + description: Filter transfers by source asset symbol (e.g., `usd`, `usdc`). + example: usd + schema: + type: string + - name: targetAsset + in: query + required: false + description: Filter transfers by target asset symbol (e.g., `usdc`, `eth`). + example: usdc + schema: + type: string + - name: sourceAddress + in: query + required: false + description: Filter transfers by the on-chain address of the source. + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + schema: + $ref: '#/components/schemas/BlockchainAddress' + - name: targetAddress + in: query + required: false + description: Filter transfers by the on-chain destination address of the target. + example: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' + schema: + $ref: '#/components/schemas/BlockchainAddress' + - name: targetEmail + in: query + required: false + description: Filter transfers by the email address of the target recipient. + example: recipient@example.com + schema: + type: string + format: email + - name: transferId + in: query + required: false + description: Filter to a specific transfer by ID. When provided, returns only the matching transfer and bypasses pagination. + example: transfer_af2937b0-9846-4fe7-bfe9-ccc22d935114 + schema: + type: string + pattern: ^transfer_[a-f0-9\-]{36}$ + - $ref: '#/components/parameters/PageSize' + - $ref: '#/components/parameters/PageToken' + responses: + '200': + description: Successfully listed transfers. + content: + application/json: + schema: + allOf: + - type: object + required: + - transfers + properties: + transfers: + type: array + description: The list of transfers. + items: + $ref: '#/components/schemas/Transfer' + - $ref: '#/components/schemas/ListResponse' + examples: + page: + $ref: '#/components/examples/ListTransfersResponse' '400': description: Invalid request. content: @@ -1515,10 +1715,135 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - max_accounts_reached: + invalid_request: value: errorType: invalid_request - errorMessage: Maximum number of Solana accounts (10) reached for this end user. + errorMessage: Invalid query parameters. + /v2/transfers/{transferId}: + get: + summary: Get transfer + description: Get a transfer by its ID. + operationId: getTransferById + x-audience: public + x-required-permissions: + permissions: + - transfers:read@entity + - transfers:read@project + enforcement: any + tags: + - Transfers + security: + - apiKeyAuth: [] + parameters: + - name: transferId + in: path + required: true + description: The unique identifier of the transfer. + schema: + type: string + pattern: ^transfer_[a-f0-9\-]{36}$ + example: transfer_af2937b0-9846-4fe7-bfe9-ccc22d935114 + responses: + '200': + description: Successfully got transfer. + content: + application/json: + schema: + $ref: '#/components/schemas/Transfer' + examples: + regular: + $ref: '#/components/examples/RegularTransferQuoted' + fx_quoted: + $ref: '#/components/examples/FxTransferQuoted' + fx_completed: + $ref: '#/components/examples/FxTransferCompleted' + '404': + description: Transfer not found. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + not_found: + summary: Transfer not found + value: + errorType: not_found + errorMessage: Transfer not found. + /v2/transfers/{transferId}/execute: + post: + x-audience: public + x-required-permissions: + permissions: + - transfers:write@entity + enforcement: any + summary: Execute transfer + description: Executes a transfer which was created using the Create a transfer endpoint. + operationId: executeFundTransfer + tags: + - Transfers + security: + - apiKeyAuth: [] + parameters: + - name: transferId + description: The ID of the transfer. + in: path + required: true + schema: + type: string + pattern: ^transfer_[a-f0-9\-]{36}$ + example: transfer_af2937b0-9846-4fe7-bfe9-ccc22d935114 + - $ref: '#/components/parameters/IdempotencyKey' + responses: + '200': + description: Successfully committed a transfer. + content: + application/json: + schema: + $ref: '#/components/schemas/Transfer' + example: + transferId: transfer_af2937b0-9846-4fe7-bfe9-ccc22d935114 + status: processing + source: + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + asset: usd + target: + address: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' + network: base + asset: usdc + amount: '100.00' + asset: usd + sourceAmount: '103.50' + sourceAsset: usd + targetAmount: '100.00' + targetAsset: usdc + exchangeRate: + sourceAsset: usd + targetAsset: usdc + rate: '1' + fees: + - type: bank + amount: '2.50' + asset: usd + - type: conversion + amount: '1.00' + asset: usd + executedAt: '2023-10-08T14:31:00Z' + createdAt: '2023-10-08T14:30:00Z' + updatedAt: '2023-10-08T14:31:00Z' + metadata: + invoiceId: '12345' + reference: 'Payment for invoice #12345' + '400': + description: Invalid request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + invalid_request: + value: + errorType: invalid_request + errorMessage: Invalid transfer ID. '401': description: Unauthorized. content: @@ -1529,11 +1854,9 @@ paths: unauthorized: value: errorType: unauthorized - errorMessage: Wallet authentication error. - '402': - $ref: '#/components/responses/PaymentMethodRequiredError' + errorMessage: Authentication error. '404': - description: End user not found. + description: Transfer not found. content: application/json: schema: @@ -1542,23 +1865,121 @@ paths: not_found: value: errorType: not_found - errorMessage: End user with the given ID not found. + errorMessage: Transfer with the given ID does not exist. '422': $ref: '#/components/responses/IdempotencyError' - '500': - $ref: '#/components/responses/InternalServerError' - '502': - $ref: '#/components/responses/BadGatewayError' + '429': + description: Rate limit exceeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + rate_limit_exceeded: + value: + errorType: rate_limit_exceeded + errorMessage: Rate limit exceeded. + '500': + $ref: '#/components/responses/InternalServerError' + '502': + $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/end-users/import: + /v2/transfers/{transferId}/travel-rule: post: - summary: Import a private key for an end user + summary: Submit deposit travel rule information description: |- - Imports an existing private key for an end user into the developer's CDP Project. The private key must be encrypted using the CDP SDK's encryption scheme before being sent to this endpoint. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. + Submit travel rule information for a deposit transfer held pending compliance review. - This endpoint allows developers to import existing keys for their end users, supporting both EVM and Solana key types. The end user must have at least one authentication method configured. - operationId: importEndUser + Required fields vary by jurisdiction and may include originator name, address, date of birth, personal ID, and VASP information. + + If the submitted information satisfies all jurisdictional requirements, `status` will be `completed` and the transfer will proceed. Otherwise, `status` will be `incomplete` and `missingFields` will indicate which fields still need to be provided. + operationId: submitDepositTravelRule + x-audience: public + x-required-permissions: + permissions: + - transfers:write@entity + enforcement: any + tags: + - Transfers + security: + - apiKeyAuth: [] + parameters: + - name: transferId + in: path + required: true + description: The unique identifier of the transfer. + schema: + type: string + pattern: ^transfer_[a-f0-9\-]{36}$ + example: transfer_af2937b0-9846-4fe7-bfe9-ccc22d935114 + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/DepositTravelRuleRequest' + example: + originator: + name: John Doe + address: + line1: 123 Main St + city: San Francisco + state: CA + postCode: '94105' + countryCode: US + beneficiary: + name: Jane Smith + isSelf: false + responses: + '200': + description: Successfully submitted travel rule information. + content: + application/json: + schema: + $ref: '#/components/schemas/DepositTravelRuleResponse' + examples: + incomplete: + value: + status: incomplete + missingFields: + - originator.dateOfBirth + completed: + value: + status: completed + missingFields: [] + '400': + description: Invalid request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + invalid_request: + value: + errorType: invalid_request + errorMessage: Invalid request body. + '404': + description: Transfer not found. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + not_found: + summary: Transfer not found + value: + errorType: not_found + errorMessage: Transfer not found. + '422': + $ref: '#/components/responses/IdempotencyError' + /v2/end-users: + post: + summary: Create end user + description: |- + Creates an end user. An end user is an entity that can own CDP EVM accounts, EVM smart accounts, and/or Solana accounts. 1 or more authentication methods must be associated with an end user. By default, no accounts are created unless the optional `evmAccount` and/or `solanaAccount` fields are provided. + This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. + operationId: createEndUser tags: - End User Accounts x-audience: public @@ -1574,69 +1995,105 @@ paths: type: object properties: userId: - description: A stable, unique identifier for the end user. The `userId` must be unique across all end users in the developer's CDP Project. It must be between 1 and 100 characters long and can only contain alphanumeric characters and hyphens. + description: |- + A stable, unique identifier for the end user. The `userId` must be unique across all end users in the developer's CDP Project. It must be between 1 and 100 characters long and can only contain alphanumeric characters and hyphens. + + If `userId` is not provided in the request, the server will generate a random UUID. type: string pattern: ^[a-zA-Z0-9-]{1,100}$ example: e051beeb-7163-4527-a5b6-35e301529ff2 authenticationMethods: $ref: '#/components/schemas/AuthenticationMethods' - encryptedPrivateKey: - type: string - description: The base64-encoded, encrypted private key to import. The private key must be encrypted using the CDP SDK's encryption scheme. This is a 32-byte raw private key. - example: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= - keyType: - type: string - description: The type of key being imported. Determines what type of account will be associated for the end user. - enum: - - evm - - solana - example: evm + evmAccount: + type: object + description: Configuration for creating an EVM account for the end user. + properties: + createSmartAccount: + type: boolean + description: If true, creates an EVM smart account and a default EVM EOA account as the owner. If false, only a EVM EOA account is created. + default: false + example: true + enableSpendPermissions: + type: boolean + description: If true, enables spend permissions for the EVM smart account. + example: true + solanaAccount: + type: object + description: Configuration for creating a Solana account for the end user. + properties: + createSmartAccount: + type: boolean + description: Only false is a valid option since currently smart accounts on Solana are not supported. + default: false + example: false required: - - userId - authenticationMethods - - encryptedPrivateKey - - keyType examples: - import_evm_key: - summary: Import an EVM private key + default_behavior: + summary: Default (no accounts created) value: - userId: user-001 authenticationMethods: - type: email email: user@example.com - encryptedPrivateKey: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= - keyType: evm - import_solana_key: - summary: Import a Solana private key + evm_only: + summary: EVM account only + value: + authenticationMethods: + - type: email + email: user@example.com + evmAccount: {} + evm_with_smart_account: + summary: EVM only with smart account + value: + authenticationMethods: + - type: email + email: user@example.com + evmAccount: + createSmartAccount: true + solana_only: + summary: Solana account only value: - userId: user-002 authenticationMethods: - type: sms phoneNumber: '+15555551234' - encryptedPrivateKey: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= - keyType: solana - import_evm_key_with_jwt_auth: - summary: Import an EVM private key with JWT authentication + solanaAccount: + createSmartAccount: false + evm_and_solana: + summary: Both EVM and Solana accounts value: - userId: user-003 authenticationMethods: - - type: jwt - sub: e051beeb-7163-4527-a5b6-35e301529ff2 - kid: NjVBRjY5MDlCMUIwNzU4RTA2QzZFMDQ4QzQ2MDAyQjVDNjk1RTM2Qg - encryptedPrivateKey: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= - keyType: evm + - type: sms + phoneNumber: '+15555551234' + evmAccount: + createSmartAccount: true + solanaAccount: + createSmartAccount: false responses: '201': - description: Successfully imported key and created end user with the associated account. + description: Successfully created end user. content: application/json: schema: $ref: '#/components/schemas/EndUser' examples: - evm_key_imported: - summary: End user with imported EVM account + default_no_accounts: + summary: Default behavior - No accounts created value: userId: user-001 + authenticationMethods: + - type: email + email: user@example.com + evmAccounts: [] + evmAccountObjects: [] + evmSmartAccounts: [] + evmSmartAccountObjects: [] + solanaAccounts: [] + solanaAccountObjects: [] + createdAt: '2025-11-17T10:00:00Z' + evm_smart_account_only: + summary: EVM smart account only + value: + userId: user-003 authenticationMethods: - type: email email: user@example.com @@ -1645,15 +2102,20 @@ paths: evmAccountObjects: - address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' createdAt: '2025-11-17T10:00:00Z' - evmSmartAccounts: [] - evmSmartAccountObjects: [] + evmSmartAccounts: + - '0x842d35Cc6634C0532925a3b844Bc454e4438f55f' + evmSmartAccountObjects: + - address: '0x842d35Cc6634C0532925a3b844Bc454e4438f55f' + ownerAddresses: + - '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + createdAt: '2025-11-17T10:00:00Z' solanaAccounts: [] solanaAccountObjects: [] createdAt: '2025-11-17T10:00:00Z' - solana_key_imported: - summary: End user with imported Solana account + solana_only: + summary: Solana account only value: - userId: user-002 + userId: user-004 authenticationMethods: - type: sms phoneNumber: '+15555551234' @@ -1667,6 +2129,62 @@ paths: - address: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT createdAt: '2025-11-17T10:00:00Z' createdAt: '2025-11-17T10:00:00Z' + evm_no_smart_account: + summary: EVM without smart account + value: + userId: user-004 + authenticationMethods: + - type: email + email: user@example.com + evmAccounts: + - '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + evmAccountObjects: + - address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + createdAt: '2025-11-17T10:00:00Z' + evmSmartAccounts: [] + evmSmartAccountObjects: [] + solanaAccounts: [] + solanaAccountObjects: [] + createdAt: '2025-11-17T10:00:00Z' + multiple_accounts: + summary: End user with multiple accounts created + value: + userId: user-005 + authenticationMethods: + - type: email + email: user@example.com + evmAccounts: + - '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + - '0x8F2A9B5C3D4E6F7A8B9C0D1E2F3A4B5C6D7E8F9A' + - '0xA1B2C3D4E5F6A7B8C9D0E1F2A3B4C5D6E7F8A9B0' + evmAccountObjects: + - address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + createdAt: '2025-11-17T10:00:00Z' + - address: '0x8F2A9B5C3D4E6F7A8B9C0D1E2F3A4B5C6D7E8F9A' + createdAt: '2025-11-17T10:05:00Z' + - address: '0xA1B2C3D4E5F6A7B8C9D0E1F2A3B4C5D6E7F8A9B0' + createdAt: '2025-11-17T10:10:00Z' + evmSmartAccounts: + - '0x842d35Cc6634C0532925a3b844Bc454e4438f55f' + - '0x9D3E4F5A6B7C8D9E0F1A2B3C4D5E6F7A8B9C0D1E' + evmSmartAccountObjects: + - address: '0x842d35Cc6634C0532925a3b844Bc454e4438f55f' + ownerAddresses: + - '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + createdAt: '2025-11-17T10:02:00Z' + - address: '0x9D3E4F5A6B7C8D9E0F1A2B3C4D5E6F7A8B9C0D1E' + ownerAddresses: + - '0x8F2A9B5C3D4E6F7A8B9C0D1E2F3A4B5C6D7E8F9A' + createdAt: '2025-11-17T10:07:00Z' + solanaAccounts: + - HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + - 9ZN8wT6gKxLmJvP4rQnYt7VxKwL3mN9rT8Qx2WzJpK5s + solanaAccountObjects: + - address: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + createdAt: '2025-11-17T10:15:00Z' + - address: 9ZN8wT6gKxLmJvP4rQnYt7VxKwL3mN9rT8Qx2WzJpK5s + createdAt: '2025-11-17T10:20:00Z' + createdAt: '2025-11-17T10:00:00Z' '400': description: Invalid request. content: @@ -1674,18 +2192,14 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - invalid_key: + invalid_request: value: errorType: invalid_request - errorMessage: The encrypted private key is invalid. - invalid_key_type: - value: - errorType: invalid_request - errorMessage: Invalid key type. Must be 'evm' or 'solana'. - missing_auth_methods: + errorMessage: At least one authentication method must be provided. + solana_smart_account_not_supported: value: errorType: invalid_request - errorMessage: At least one authentication method must be provided. + errorMessage: The request contains one or more unsupported options. '401': description: Unauthorized. content: @@ -1699,118 +2213,147 @@ paths: errorMessage: Wallet authentication error. '402': $ref: '#/components/responses/PaymentMethodRequiredError' - '409': - description: Resource already exists. + '422': + $ref: '#/components/responses/IdempotencyError' + '500': + $ref: '#/components/responses/InternalServerError' + get: + x-audience: public + summary: List end users + description: |- + Lists the end users belonging to the developer's CDP Project. + By default, the response is sorted by creation date in ascending order and paginated to 20 users per page. + operationId: listEndUsers + tags: + - End User Accounts + security: + - apiKeyAuth: [] + parameters: + - name: pageSize + description: The number of end users to return per page. + in: query + required: false + schema: + type: integer + default: 20 + minimum: 1 + maximum: 100 + example: 10 + - name: pageToken + description: The token for the desired page of end users. Will be empty if there are no more end users to fetch. + in: query + required: false + schema: + type: string + example: eyJsYXN0X2lkIjogImFiYzEyMyIsICJ0aW1lc3RhbXAiOiAxNzA3ODIzNzAxfQ== + - name: sort + description: Sort end users. Defaults to ascending order (oldest first). + in: query + required: false + schema: + type: array + items: + type: string + enum: + - createdAt=asc + - createdAt=desc + example: + - createdAt=asc + style: form + explode: false + responses: + '200': + description: Successfully retrieved end users. + content: + application/json: + schema: + allOf: + - type: object + required: + - endUsers + properties: + endUsers: + type: array + description: The list of end users. + items: + $ref: '#/components/schemas/EndUser' + - $ref: '#/components/schemas/ListResponse' + '400': + description: Invalid request. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - already_exists: + invalid_request: value: - errorType: already_exists - errorMessage: An account with the given address already exists. - '422': - $ref: '#/components/responses/IdempotencyError' + errorType: invalid_request + errorMessage: Invalid project ID. + '401': + $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/embedded-wallet-api/end-users/{userId}/evm/sign/transaction: + /v2/end-users/auth/validate-token: post: x-audience: public - summary: Sign a transaction with end user EVM account + summary: Validate end user access token description: |- - Signs a transaction with the given end user EVM account. - The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). + Validates the end user's access token and returns the end user's information. Returns an error if the access token is invalid or expired. - The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. - operationId: signEvmTransactionWithEndUserAccount + This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. + operationId: validateEndUserAccessToken tags: - - Embedded Wallets + - End User Accounts security: - - endUserAuth: [] - apiKeyAuth: [] - parameters: - - $ref: '#/components/parameters/XWalletAuthOptional' - - $ref: '#/components/parameters/IdempotencyKey' - - name: userId - description: The ID of the end user. - in: path - required: true - schema: - type: string - pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 - - $ref: '#/components/parameters/XDeveloperAuth' - - $ref: '#/components/parameters/ProjectIDOptional' requestBody: content: application/json: schema: type: object + description: The request body for a developer to verify an end user's access token. properties: - address: - type: string - description: The 0x-prefixed address of the EVM account belonging to the end user. - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - pattern: ^0x[0-9a-fA-F]{40}$ - transaction: - type: string - description: The RLP-encoded transaction to sign, as a 0x-prefixed hex string. - example: '0xf86b098505d21dba00830334509431415daf58e2c6b7323b4c58712fd92952145da79018080' - walletSecretId: - description: Required when not using delegated signing. The ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. + accessToken: type: string - pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 + description: The access token in JWT format to verify. + example: eyJhbGciOiJFUzI1NiIsImtpZCI6IjA1ZGNmYTU1LWY1NzktNDg5YS1iNThhLTFlMDI5Nzk0N2VlNiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJjZHAtYXBpIiwiYXV0aF90eXBlIjoiZW1haWwiLCJleHAiOjE3NTM5ODAyOTksImlhdCI6MTc1Mzk3ODQ5OSwiaXNzIjoiY2RwLWFwaSIsImp0aSI6IjA3ZWY5M2JlLTYzMDQtNGQ1YS05NmE3LWJlMGI5MWI0ZTE3NCIsInByb2plY3RfaWQiOiJjNzRkOGI4OC0wOTNiLTQyZDItOGE4Yy1kZGM1YzVlMGViNDMiLCJzdWIiOiJjYTM4YTM4ZC0xNmE5LTRkMjYtYTcxZC0zOWY2NmY5YzZiN2UifQ.1SU0pOy-WR002qUw4hd_UmZWRSLz-ZL6v7PvQvZMKVE6a51x_tqeUeRGaTGuYl1whg0eccMObmK7FqXKRH6E4g required: - - address - - transaction + - accessToken responses: '200': - description: Successfully signed transaction. + description: Confirms that the access token is valid and returns the end user's information. content: application/json: schema: - type: object - properties: - signedTransaction: - type: string - description: The RLP-encoded signed transaction, as a 0x-prefixed hex string. - example: '0x1b0c9cf8cd4554c6c6d9e7311e88f1be075d7f25b418a044f4bf2c0a42a93e212ad0a8b54de9e0b5f7e3812de3f2c6cc79aa8c3e1c02e7ad14b4a8f42012c2c01b' - required: - - signedTransaction + $ref: '#/components/schemas/EndUser' '400': - description: Invalid request. + description: Request body is invalid. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - malformed_transaction: + invalid_request: value: - errorType: malformed_transaction - errorMessage: Malformed unsigned transaction. + errorType: invalid_request + errorMessage: Missing access token. '401': - $ref: '#/components/responses/UnauthorizedError' - '402': - $ref: '#/components/responses/PaymentMethodRequiredError' - '403': - description: Access to resource forbidden. + description: Request is not properly authenticated, or the access token is invalid or expired. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - forbidden: + unauthorized: value: - errorType: forbidden - errorMessage: Unable to sign transaction for this address. + errorType: unauthorized + errorMessage: 'Invalid JWT issuer: not-cdp-api, expected: cdp-api.' '404': - description: Not found. + description: End user not found. content: application/json: schema: @@ -1819,318 +2362,278 @@ paths: not_found: value: errorType: not_found - errorMessage: EVM account with the given address not found. - '409': - $ref: '#/components/responses/AlreadyExistsError' - '422': - $ref: '#/components/responses/IdempotencyError' + errorMessage: End user not found. '500': $ref: '#/components/responses/InternalServerError' - '502': - $ref: '#/components/responses/BadGatewayError' - '503': - $ref: '#/components/responses/ServiceUnavailableError' - /v2/embedded-wallet-api/end-users/{userId}/evm/send/transaction: - post: + /v2/end-users/{userId}: + get: x-audience: public - summary: Send a transaction with end user EVM account + summary: Get end user description: |- - Signs a transaction with the given end user EVM account and sends it to the indicated supported network. This API handles nonce management and gas estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). - - The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). - - - **Transaction fields and API behavior** - - - `to` *(Required)*: The address of the contract or account to send the transaction to. - - `chainId` *(Ignored)*: The value of the `chainId` field in the transaction is ignored. - The transaction will be sent to the network indicated by the `network` field in the request body. - - - `nonce` *(Optional)*: The nonce to use for the transaction. If not provided, the API will assign - a nonce to the transaction based on the current state of the account. - - - `maxPriorityFeePerGas` *(Optional)*: The maximum priority fee per gas to use for the transaction. - If not provided, the API will estimate a value based on current network conditions. - - - `maxFeePerGas` *(Optional)*: The maximum fee per gas to use for the transaction. - If not provided, the API will estimate a value based on current network conditions. - - - `gasLimit` *(Optional)*: The gas limit to use for the transaction. If not provided, the API will estimate a value - based on the `to` and `data` fields of the transaction. + Gets an end user by ID. - - `value` *(Optional)*: The amount of ETH, in wei, to send with the transaction. - - `data` *(Optional)*: The data to send with the transaction; only used for contract calls. - - `accessList` *(Optional)*: The access list to use for the transaction. - operationId: sendEvmTransactionWithEndUserAccount + This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. + operationId: getEndUser tags: - - Embedded Wallets + - End User Accounts security: - - endUserAuth: [] - apiKeyAuth: [] parameters: - - $ref: '#/components/parameters/XWalletAuthOptional' - - $ref: '#/components/parameters/IdempotencyKey' - name: userId - description: The ID of the end user. in: path required: true + description: The ID of the end user to get. schema: type: string pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 - - $ref: '#/components/parameters/XDeveloperAuth' - - $ref: '#/components/parameters/ProjectIDOptional' - requestBody: - content: - application/json: - schema: - type: object - properties: - address: - type: string - description: The 0x-prefixed address of the EVM account belonging to the end user. - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - pattern: ^0x[0-9a-fA-F]{40}$ - network: - type: string - description: The network to send the transaction to. - enum: - - base - - base-sepolia - - ethereum - - ethereum-sepolia - - avalanche - - polygon - - optimism - - arbitrum - - arbitrum-sepolia - - world - - world-sepolia - example: base-sepolia - walletSecretId: - description: Required when not using delegated signing. The ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. - type: string - pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 - transaction: - type: string - description: The RLP-encoded transaction to sign and send, as a 0x-prefixed hex string. - example: '0xf86b098505d21dba00830334509431415daf58e2c6b7323b4c58712fd92952145da79018080' - required: - - address - - transaction - - network + example: e051beeb-7163-4527-a5b6-35e301529ff2 responses: '200': - description: Successfully signed and sent transaction. + description: Successfully got end user. content: application/json: schema: - type: object - properties: - transactionHash: - type: string - description: The hash of the transaction, as a 0x-prefixed hex string. - example: '0xf8f98fb6726fc936f24b2007df5cb20e2b8444ff3dfaa2a929335f432a9be2e7' - required: - - transactionHash - '400': - description: Invalid request. + $ref: '#/components/schemas/EndUser' + '404': + description: Not found. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - malformed_transaction: + not_found: value: - errorType: malformed_transaction - errorMessage: Malformed unsigned transaction. - '401': - $ref: '#/components/responses/UnauthorizedError' - '402': - $ref: '#/components/responses/PaymentMethodRequiredError' - '403': - description: Access to resource forbidden. + errorType: not_found + errorMessage: End user with the given ID not found. + '500': + $ref: '#/components/responses/InternalServerError' + /v2/end-users/lookup: + get: + x-audience: public + summary: Look up end users by identity + description: |- + Looks up end users. Exactly one lookup type must be provided per request: + + - **email**: searches across all email-based authentication methods + (email, Google, Apple, GitHub). May return multiple end users if the + same email address appears across different auth methods. + + - **oauthProvider + oauthSubject**: looks up a user by their OAuth + provider and subject (the `sub` claim from the provider's ID token). + Both params must be provided together. + + - **phoneNumber**: looks up a user by their SMS-verified phone number. + + Returns all matching end users. If no end users match, an empty array is returned. + + This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. + operationId: lookupEndUser + tags: + - End User Accounts + security: + - apiKeyAuth: [] + parameters: + - name: email + in: query + required: false + description: The email address to search for across all email-based authentication methods. + schema: + type: string + format: email + example: user@example.com + - name: oauthProvider + in: query + required: false + description: The OAuth provider to search by. Must be provided together with oauthSubject. + schema: + $ref: '#/components/schemas/OAuth2ProviderType' + example: google + - name: oauthSubject + in: query + required: false + description: The OAuth subject (the `sub` claim from the provider's ID token). Must be provided together with oauthProvider. + schema: + type: string + example: '1234567890' + - name: phoneNumber + in: query + required: false + description: The E.164-formatted phone number to search for. Must be URL-encoded when passed as a query parameter (e.g. `+14155552671` → `%2B14155552671`). + schema: + type: string + pattern: ^\+[1-9]\d{1,14}$ + example: '+14155552671' + responses: + '200': + description: Successfully looked up end users. content: application/json: schema: - $ref: '#/components/schemas/Error' + type: object + required: + - endUsers + properties: + endUsers: + type: array + description: The list of end users matching the lookup. + items: + $ref: '#/components/schemas/EndUser' examples: - forbidden: + email_match: + summary: End user found by email value: - errorType: forbidden - errorMessage: Unable to sign transaction for this address. - '404': - description: Not found. + endUsers: + - userId: user-001 + authenticationMethods: + - type: email + email: user@example.com + evmAccounts: [] + evmAccountObjects: [] + evmSmartAccounts: [] + evmSmartAccountObjects: [] + solanaAccounts: [] + solanaAccountObjects: [] + createdAt: '2025-11-17T10:00:00Z' + multiple_email_matches: + summary: Multiple end users with same email across auth methods + value: + endUsers: + - userId: user-001 + authenticationMethods: + - type: email + email: user@example.com + evmAccounts: [] + evmAccountObjects: [] + evmSmartAccounts: [] + evmSmartAccountObjects: [] + solanaAccounts: [] + solanaAccountObjects: [] + createdAt: '2025-11-17T10:00:00Z' + - userId: user-002 + authenticationMethods: + - type: google + sub: google-sub-123 + email: user@example.com + evmAccounts: [] + evmAccountObjects: [] + evmSmartAccounts: [] + evmSmartAccountObjects: [] + solanaAccounts: [] + solanaAccountObjects: [] + createdAt: '2025-11-17T11:00:00Z' + oauth_match: + summary: End user found by OAuth subject + value: + endUsers: + - userId: user-003 + authenticationMethods: + - type: google + sub: '1234567890' + email: user@example.com + evmAccounts: [] + evmAccountObjects: [] + evmSmartAccounts: [] + evmSmartAccountObjects: [] + solanaAccounts: [] + solanaAccountObjects: [] + createdAt: '2025-11-17T12:00:00Z' + phone_match: + summary: End user found by phone number + value: + endUsers: + - userId: user-004 + authenticationMethods: + - type: sms + phoneNumber: '+14155552671' + evmAccounts: [] + evmAccountObjects: [] + evmSmartAccounts: [] + evmSmartAccountObjects: [] + solanaAccounts: [] + solanaAccountObjects: [] + createdAt: '2025-11-17T13:00:00Z' + no_matches: + summary: No end users found + value: + endUsers: [] + '400': + description: Invalid request. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - not_found: + no_lookup_param: + summary: No lookup parameter provided value: - errorType: not_found - errorMessage: EVM account with the given address not found. - '409': - $ref: '#/components/responses/AlreadyExistsError' - '422': - $ref: '#/components/responses/IdempotencyError' + errorType: invalid_request + errorMessage: 'Exactly one lookup type must be provided: email, phoneNumber, or oauthProvider+oauthSubject.' + multiple_lookup_params: + summary: Multiple lookup parameters provided + value: + errorType: invalid_request + errorMessage: 'Exactly one lookup type must be provided: email, phoneNumber, or oauthProvider+oauthSubject.' + oauth_missing_subject: + summary: oauthProvider provided without oauthSubject + value: + errorType: invalid_request + errorMessage: oauthProvider and oauthSubject must be provided together. + '401': + $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - '502': - $ref: '#/components/responses/BadGatewayError' - '503': - $ref: '#/components/responses/ServiceUnavailableError' - /v2/embedded-wallet-api/end-users/{userId}/evm/{address}/send/{asset}: + /v2/end-users/{userId}/evm: post: - x-audience: public - summary: Send USDC on EVM + summary: Add EVM account to end user description: |- - Sends USDC from an end user's EVM account (EOA or Smart Account) to a recipient address on a supported EVM network. This endpoint simplifies USDC transfers by automatically handling contract resolution, decimal conversion, gas estimation, and transaction encoding. - The `amount` field accepts human-readable amounts as decimal strings (e.g., "1.5", "25.50"). - operationId: sendEvmAssetWithEndUserAccount + Adds a new EVM EOA account to an existing end user. End users can have up to 10 EVM accounts. + This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. + operationId: addEndUserEvmAccount tags: - - Embedded Wallets + - End User Accounts + x-audience: public security: - - endUserAuth: [] - apiKeyAuth: [] parameters: - - $ref: '#/components/parameters/XWalletAuthOptional' - - $ref: '#/components/parameters/IdempotencyKey' - name: userId in: path required: true - description: The ID of the end user. + description: The ID of the end user to add the account to. schema: type: string pattern: ^[a-zA-Z0-9-]{1,100}$ example: e051beeb-7163-4527-a5b6-35e301529ff2 - - name: address - description: The 0x-prefixed address of the EVM account (EOA or Smart Account) to send USDC from. The address does not need to be checksummed. - in: path - required: true - schema: - allOf: - - $ref: '#/components/schemas/BlockchainAddress' - pattern: ^0x[0-9a-fA-F]{40}$ - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - - name: asset - in: path - required: true - description: The asset to send. Currently only "usdc" is supported. - schema: - allOf: - - $ref: '#/components/schemas/Asset' - enum: - - usdc - example: usdc - - $ref: '#/components/parameters/XDeveloperAuth' - - $ref: '#/components/parameters/ProjectIDOptional' + - $ref: '#/components/parameters/XWalletAuth' + - $ref: '#/components/parameters/IdempotencyKey' requestBody: + required: false content: application/json: schema: type: object - properties: - to: - allOf: - - $ref: '#/components/schemas/BlockchainAddress' - pattern: ^0x[0-9a-fA-F]{40}$ - description: The 0x-prefixed address of the recipient. - example: '0x1234567890123456789012345678901234567890' - amount: - type: string - minLength: 1 - maxLength: 32 - description: The amount of USDC to send as a decimal string (e.g., "1.5" or "25.50"). - example: '1.50' - network: - type: string - description: The EVM network to send USDC on. - enum: - - base - - base-sepolia - - ethereum - - ethereum-sepolia - - avalanche - - polygon - - optimism - - arbitrum - - arbitrum-sepolia - - world - - world-sepolia - example: base-sepolia - useCdpPaymaster: - type: boolean - description: Whether to use CDP Paymaster to sponsor gas fees. Only applicable for EVM Smart Accounts. When true, the transaction gas will be paid by the Paymaster, allowing users to send USDC without holding native gas tokens. Ignored for EOA accounts. Cannot be used together with `paymasterUrl`. - example: true - paymasterUrl: - allOf: - - $ref: '#/components/schemas/Url' - description: Optional custom Paymaster URL to use for gas sponsorship. Only applicable for EVM Smart Accounts. This allows you to use your own Paymaster service instead of CDP's Paymaster. Cannot be used together with `useCdpPaymaster`. - example: https://api.developer.coinbase.com/rpc/v1/base/AbCdEf123456 - walletSecretId: - description: Required when not using delegated signing. The ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. - type: string - pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 - required: - - to - - amount - - network examples: - send_usdc_eoa: - summary: Send USDC from EOA - value: - to: '0x1234567890123456789012345678901234567890' - amount: '25.50' - network: base-sepolia - walletSecretId: e051beeb-7163-4527-a5b6-35e301529ff2 - send_usdc_smart_account_cdp_paymaster: - summary: Send USDC from Smart Account with CDP Paymaster - value: - to: '0x1234567890123456789012345678901234567890' - amount: '10.00' - network: base-sepolia - useCdpPaymaster: true - walletSecretId: e051beeb-7163-4527-a5b6-35e301529ff2 - send_usdc_smart_account_custom_paymaster: - summary: Send USDC from Smart Account with custom Paymaster - value: - to: '0x1234567890123456789012345678901234567890' - amount: '15.00' - network: base-sepolia - paymasterUrl: https://api.developer.coinbase.com/rpc/v1/base/AbCdEf123456 - walletSecretId: e051beeb-7163-4527-a5b6-35e301529ff2 + default: + summary: Create EVM EOA account + value: {} responses: - '200': - description: Successfully sent transaction. + '201': + description: Successfully added EVM account to end user. content: application/json: schema: type: object + required: + - evmAccount properties: - transactionHash: - type: string - description: The hash of the transaction, as a 0x-prefixed hex string. Populated for EOA accounts. Null for Smart Accounts (use userOpHash instead). - example: '0xf8f98fb6726fc936f24b2007df5cb20e2b8444ff3dfaa2a929335f432a9be2e7' - nullable: true - userOpHash: - type: string - description: The hash of the user operation, as a 0x-prefixed hex string. Populated for Smart Accounts. Null for EOA accounts (use transactionHash instead). - example: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' - nullable: true + evmAccount: + $ref: '#/components/schemas/EndUserEvmAccount' examples: - eoa_transfer: - summary: EOA transfer response - value: - transactionHash: '0xf8f98fb6726fc936f24b2007df5cb20e2b8444ff3dfaa2a929335f432a9be2e7' - userOpHash: null - smart_account_transfer: - summary: Smart Account transfer response + default: + summary: EVM EOA account created value: - transactionHash: null - userOpHash: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' + evmAccount: + address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + createdAt: '2025-11-17T10:00:00Z' '400': description: Invalid request. content: @@ -2138,41 +2641,25 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - invalid_amount: - value: - errorType: invalid_request - errorMessage: Invalid amount format. Amount must be a valid decimal string. - errorParam: amount - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request - invalid_network: - value: - errorType: invalid_request - errorMessage: Unsupported network for USDC transfers. - errorParam: network - errorLink: https://docs.cdp.coinbase.com/get-started/supported-networks#supported-networks - invalid_asset: - value: - errorType: invalid_request - errorMessage: Unsupported asset. Currently only 'usdc' is supported. - errorParam: asset - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request - insufficient_balance: - value: - errorType: invalid_request - errorMessage: Account has insufficient USDC balance to complete the transfer. - errorParam: amount - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request - conflicting_paymaster: + max_accounts_reached: value: errorType: invalid_request - errorMessage: Cannot specify both 'useCdpPaymaster' and 'paymasterUrl'. Please use only one. - errorLink: https://docs.cdp.coinbase.com/embedded-wallets/evm-features/smart-accounts#gas-sponsorship-with-paymaster + errorMessage: Maximum number of EVM accounts (10) reached for this end user. '401': - $ref: '#/components/responses/UnauthorizedError' + description: Unauthorized. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + unauthorized: + value: + errorType: unauthorized + errorMessage: Wallet authentication error. '402': $ref: '#/components/responses/PaymentMethodRequiredError' '404': - description: Not found. + description: End user not found. content: application/json: schema: @@ -2181,9 +2668,7 @@ paths: not_found: value: errorType: not_found - errorMessage: EVM account with the given address not found. - errorParam: address - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#not-found + errorMessage: End user with the given ID not found. '422': $ref: '#/components/responses/IdempotencyError' '500': @@ -2192,76 +2677,96 @@ paths: $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/embedded-wallet-api/end-users/{userId}/evm/sign/message: + /v2/end-users/{userId}/evm-smart-account: post: - x-audience: public - summary: Sign an EIP-191 message with end user EVM account + summary: Add EVM smart account to end user description: |- - Signs an [EIP-191](https://eips.ethereum.org/EIPS/eip-191) message with the given end user EVM account. - - Per the specification, the message in the request body is prepended with `0x19 <0x45 (E)> ` before being signed. - operationId: signEvmMessageWithEndUserAccount + Creates an EVM smart account for an existing end user. The backend will create a new EVM EOA account to serve as the owner of the smart account. + This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. + operationId: addEndUserEvmSmartAccount tags: - - Embedded Wallets + - End User Accounts + x-audience: public security: - - endUserAuth: [] - apiKeyAuth: [] parameters: - - $ref: '#/components/parameters/XWalletAuthOptional' - - $ref: '#/components/parameters/IdempotencyKey' - name: userId - description: The ID of the end user. in: path required: true + description: The ID of the end user to add the smart account to. schema: type: string pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 - - $ref: '#/components/parameters/XDeveloperAuth' - - $ref: '#/components/parameters/ProjectIDOptional' + example: e051beeb-7163-4527-a5b6-35e301529ff2 + - $ref: '#/components/parameters/XWalletAuth' + - $ref: '#/components/parameters/IdempotencyKey' requestBody: + required: false content: application/json: schema: type: object properties: - address: - type: string - description: The 0x-prefixed address of the EVM account belonging to the end user. - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - pattern: ^0x[0-9a-fA-F]{40}$ - message: - type: string - description: The message to sign. - example: Hello, world! - walletSecretId: - description: Required when not using delegated signing. The ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. - type: string - pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 - required: - - address - - message + enableSpendPermissions: + type: boolean + description: If true, enables spend permissions for the EVM smart account. + default: false + example: true + examples: + default: + summary: Create smart account + value: {} + with_spend_permissions: + summary: Create smart account with spend permissions + value: + enableSpendPermissions: true responses: - '200': - description: Successfully signed message. + '201': + description: Successfully added EVM smart account to end user. content: application/json: schema: type: object - properties: - signature: - type: string - description: The signature of the message, as a 0x-prefixed hex string. - example: '0x1b0c9cf8cd4554c6c6d9e7311e88f1be075d7f25b418a044f4bf2c0a42a93e212ad0a8b54de9e0b5f7e3812de3f2c6cc79aa8c3e1c02e7ad14b4a8f42012c2c01b' required: - - signature + - evmSmartAccount + properties: + evmSmartAccount: + $ref: '#/components/schemas/EndUserEvmSmartAccount' + examples: + default: + summary: EVM smart account created + value: + evmSmartAccount: + address: '0x842d35Cc6634C0532925a3b844Bc454e4438f55f' + ownerAddresses: + - '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + createdAt: '2025-11-17T10:00:00Z' + '400': + description: Invalid request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + max_accounts_reached: + value: + errorType: invalid_request + errorMessage: Maximum number of EVM smart accounts (10) reached for this end user. '401': - $ref: '#/components/responses/UnauthorizedError' + description: Unauthorized. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + unauthorized: + value: + errorType: unauthorized + errorMessage: Wallet authentication error. '402': $ref: '#/components/responses/PaymentMethodRequiredError' '404': - description: Not found. + description: End user not found. content: application/json: schema: @@ -2270,9 +2775,7 @@ paths: not_found: value: errorType: not_found - errorMessage: EVM account with the given address not found. - '409': - $ref: '#/components/responses/AlreadyExistsError' + errorMessage: End user with the given ID not found. '422': $ref: '#/components/responses/IdempotencyError' '500': @@ -2281,65 +2784,58 @@ paths: $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/embedded-wallet-api/end-users/{userId}/evm/sign/typed-data: + /v2/end-users/{userId}/solana: post: - x-audience: public - summary: Sign EIP-712 typed data with end user EVM account - description: Signs [EIP-712](https://eips.ethereum.org/EIPS/eip-712) typed data with the given end user EVM account. - operationId: signEvmTypedDataWithEndUserAccount - tags: - - Embedded Wallets + summary: Add Solana account to end user + description: |- + Adds a new Solana account to an existing end user. End users can have up to 10 Solana accounts. + This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. + operationId: addEndUserSolanaAccount + tags: + - End User Accounts + x-audience: public security: - - endUserAuth: [] - apiKeyAuth: [] parameters: - - $ref: '#/components/parameters/XWalletAuthOptional' - - $ref: '#/components/parameters/IdempotencyKey' - name: userId - description: The ID of the end user. in: path required: true + description: The ID of the end user to add the account to. schema: type: string pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 - - $ref: '#/components/parameters/XDeveloperAuth' - - $ref: '#/components/parameters/ProjectIDOptional' + example: e051beeb-7163-4527-a5b6-35e301529ff2 + - $ref: '#/components/parameters/XWalletAuth' + - $ref: '#/components/parameters/IdempotencyKey' requestBody: + required: false content: application/json: schema: type: object - properties: - address: - type: string - description: The 0x-prefixed address of the EVM account belonging to the end user. - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - pattern: ^0x[0-9a-fA-F]{40}$ - typedData: - $ref: '#/components/schemas/EIP712Message' - walletSecretId: - description: Required when not using delegated signing. The ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. - type: string - pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 - required: - - address - - typedData + examples: + default: + summary: Create Solana account + value: {} responses: - '200': - description: Successfully signed typed data. + '201': + description: Successfully added Solana account to end user. content: application/json: schema: type: object - properties: - signature: - type: string - description: The signature of the typed data, as a 0x-prefixed hex string. - example: '0x1b0c9cf8cd4554c6c6d9e7311e88f1be075d7f25b418a044f4bf2c0a42a93e212ad0a8b54de9e0b5f7e3812de3f2c6cc79aa8c3e1c02e7ad14b4a8f42012c2c01b' required: - - signature + - solanaAccount + properties: + solanaAccount: + $ref: '#/components/schemas/EndUserSolanaAccount' + examples: + default: + summary: Solana account created + value: + solanaAccount: + address: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + createdAt: '2025-11-17T10:00:00Z' '400': description: Invalid request. content: @@ -2347,75 +2843,25 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - invalid_request: + max_accounts_reached: value: errorType: invalid_request - errorMessage: Invalid request. Please check the request body and parameters. + errorMessage: Maximum number of Solana accounts (10) reached for this end user. '401': - $ref: '#/components/responses/UnauthorizedError' - '402': - $ref: '#/components/responses/PaymentMethodRequiredError' - '404': - description: Not found. + description: Unauthorized. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - not_found: + unauthorized: value: - errorType: not_found - errorMessage: EVM account with the given address not found. - '422': - $ref: '#/components/responses/IdempotencyError' - '500': - $ref: '#/components/responses/InternalServerError' - '502': - $ref: '#/components/responses/BadGatewayError' - '503': - $ref: '#/components/responses/ServiceUnavailableError' - /v2/embedded-wallet-api/end-users/{userId}/delegation: - get: - x-audience: public - summary: Get delegation for end user - description: Returns the active delegation for the specified end user, if one exists. This operation can be performed by the end user themselves or by a developer using their API key. - operationId: getDelegationForEndUser - tags: - - Embedded Wallets - security: - - endUserAuth: [] - - apiKeyAuth: [] - parameters: - - name: userId - in: path - required: true - description: The ID of the end user. - schema: - type: string - pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 - - $ref: '#/components/parameters/ProjectIDOptional' - responses: - '200': - description: Active delegation found. - content: - application/json: - schema: - type: object - properties: - expiresAt: - type: string - format: date-time - description: The date until which the delegation is valid. - example: '2026-02-03T10:35:00Z' - required: - - expiresAt - example: - expiresAt: '2026-02-03T10:35:00Z' - '401': - $ref: '#/components/responses/UnauthorizedError' + errorType: unauthorized + errorMessage: Wallet authentication error. + '402': + $ref: '#/components/responses/PaymentMethodRequiredError' '404': - description: No active delegation found. + description: End user not found. content: application/json: schema: @@ -2424,149 +2870,131 @@ paths: not_found: value: errorType: not_found - errorMessage: No active delegation found for the specified end user. - errorParam: userId - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#not-found + errorMessage: End user with the given ID not found. + '422': + $ref: '#/components/responses/IdempotencyError' '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - delete: - x-audience: public - summary: Revoke delegation for end user - description: Revokes all active delegations for the specified end user. This operation can be performed by the end user themselves or by a developer using their API key. - operationId: revokeDelegationForEndUser + /v2/end-users/import: + post: + summary: Import end user private key + description: |- + Imports an existing private key for an end user into the developer's CDP Project. The private key must be encrypted using the CDP SDK's encryption scheme before being sent to this endpoint. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. + + This endpoint allows developers to import existing keys for their end users, supporting both EVM and Solana key types. The end user must have at least one authentication method configured. + operationId: importEndUser tags: - - Embedded Wallets + - End User Accounts + x-audience: public security: - - endUserAuth: [] - apiKeyAuth: [] parameters: - - $ref: '#/components/parameters/XWalletAuthOptional' - - $ref: '#/components/parameters/XDeveloperAuth' - required: false + - $ref: '#/components/parameters/XWalletAuth' - $ref: '#/components/parameters/IdempotencyKey' - - name: userId - in: path - required: true - description: The ID of the end user. - schema: - type: string - pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 - - $ref: '#/components/parameters/ProjectIDOptional' requestBody: - required: true content: application/json: schema: type: object properties: - walletSecretId: - description: When revoking with a wallet authentication scheme, the ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. + userId: + description: A stable, unique identifier for the end user. The `userId` must be unique across all end users in the developer's CDP Project. It must be between 1 and 100 characters long and can only contain alphanumeric characters and hyphens. type: string pattern: ^[a-zA-Z0-9-]{1,100}$ example: e051beeb-7163-4527-a5b6-35e301529ff2 - example: - walletSecretId: e051beeb-7163-4527-a5b6-35e301529ff2 + authenticationMethods: + $ref: '#/components/schemas/AuthenticationMethods' + encryptedPrivateKey: + type: string + description: The base64-encoded, encrypted private key to import. The private key must be encrypted using the CDP SDK's encryption scheme. This is a 32-byte raw private key. + example: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= + keyType: + type: string + description: The type of key being imported. Determines what type of account will be associated for the end user. + enum: + - evm + - solana + example: evm + required: + - userId + - authenticationMethods + - encryptedPrivateKey + - keyType + examples: + import_evm_key: + summary: Import an EVM private key + value: + userId: user-001 + authenticationMethods: + - type: email + email: user@example.com + encryptedPrivateKey: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= + keyType: evm + import_solana_key: + summary: Import a Solana private key + value: + userId: user-002 + authenticationMethods: + - type: sms + phoneNumber: '+15555551234' + encryptedPrivateKey: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= + keyType: solana + import_evm_key_with_jwt_auth: + summary: Import an EVM private key with JWT authentication + value: + userId: user-003 + authenticationMethods: + - type: jwt + sub: e051beeb-7163-4527-a5b6-35e301529ff2 + kid: NjVBRjY5MDlCMUIwNzU4RTA2QzZFMDQ4QzQ2MDAyQjVDNjk1RTM2Qg + encryptedPrivateKey: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= + keyType: evm responses: - '204': - description: Delegation revoked successfully. - '401': - $ref: '#/components/responses/UnauthorizedError' - '404': - description: Delegation not found. + '201': + description: Successfully imported key and created end user with the associated account. content: application/json: schema: - $ref: '#/components/schemas/Error' + $ref: '#/components/schemas/EndUser' examples: - not_found: + evm_key_imported: + summary: End user with imported EVM account value: - errorType: not_found - errorMessage: No active delegation found for the specified end user. - errorParam: userId - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#not-found - '500': - $ref: '#/components/responses/InternalServerError' - '502': - $ref: '#/components/responses/BadGatewayError' - '503': - $ref: '#/components/responses/ServiceUnavailableError' - /v2/embedded-wallet-api/end-users/{userId}/address/{address}/delegation: - post: - x-audience: public - summary: Create account-scoped delegation for an end user account - description: |- - Creates an account-scoped delegation that allows a developer to sign on behalf of an end user for a single blockchain account (identified by its address) for the specified duration. The end user must be authenticated to authorize this delegation. - Multiple account-scoped delegations may exist concurrently for a single end user (one per canonical account address). Account-scoped and user-scoped delegations cannot coexist for the same user. - When the address corresponds to an EVM Smart Account, the delegation is scoped to the Smart Account's owner EOA rather than the Smart Account address itself. This means `/address/{smartAccountAddress}/delegation` and `/address/{ownerEoaAddress}/delegation` resolve to the same delegation, and the 409 `account_scoped_delegation_active` error may be returned when creating via either address if one already exists for the canonical owner. - operationId: createDelegationForEndUserAccount - tags: - - Embedded Wallets - security: - - endUserAuth: [] - parameters: - - $ref: '#/components/parameters/XWalletAuth' - - $ref: '#/components/parameters/IdempotencyKey' - - name: userId - in: path - required: true - description: The ID of the end user. - schema: - type: string - pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 - - name: address - in: path - required: true - description: The blockchain address of the end user account to scope this delegation to. Format varies by network (e.g., 0x-prefixed for EVM, base58 for Solana). For EVM addresses, matching is case-insensitive. - schema: - $ref: '#/components/schemas/BlockchainAddress' - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - - $ref: '#/components/parameters/ProjectIDOptional' - requestBody: - required: true - content: - application/json: - schema: - type: object - properties: - expiresAt: - type: string - format: date-time - description: The date until which the delegation is valid. - example: '2026-02-03T10:35:00Z' - walletSecretId: - description: The ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. - type: string - pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 - required: - - expiresAt - - walletSecretId - example: - expiresAt: '2026-02-03T10:35:00Z' - walletSecretId: e051beeb-7163-4527-a5b6-35e301529ff2 - responses: - '201': - description: Delegation created successfully. - content: - application/json: - schema: - type: object - properties: - expiresAt: - type: string - format: date-time - description: The date until which the delegation is valid. - example: '2026-02-03T10:35:00Z' - required: - - expiresAt - example: - expiresAt: '2026-02-03T10:35:00Z' + userId: user-001 + authenticationMethods: + - type: email + email: user@example.com + evmAccounts: + - '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + evmAccountObjects: + - address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + createdAt: '2025-11-17T10:00:00Z' + evmSmartAccounts: [] + evmSmartAccountObjects: [] + solanaAccounts: [] + solanaAccountObjects: [] + createdAt: '2025-11-17T10:00:00Z' + solana_key_imported: + summary: End user with imported Solana account + value: + userId: user-002 + authenticationMethods: + - type: sms + phoneNumber: '+15555551234' + evmAccounts: [] + evmAccountObjects: [] + evmSmartAccounts: [] + evmSmartAccountObjects: [] + solanaAccounts: + - HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + solanaAccountObjects: + - address: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + createdAt: '2025-11-17T10:00:00Z' + createdAt: '2025-11-17T10:00:00Z' '400': description: Invalid request. content: @@ -2574,123 +3002,134 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - missing_expiresAt: + invalid_key: value: errorType: invalid_request - errorMessage: Field 'expiresAt' is required. - errorParam: expiresAt - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request - invalid_expiresAt: + errorMessage: The encrypted private key is invalid. + invalid_key_type: value: errorType: invalid_request - errorMessage: Field 'expiresAt' must be a valid ISO 8601 string. - errorParam: expiresAt - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request + errorMessage: Invalid key type. Must be 'evm' or 'solana'. + missing_auth_methods: + value: + errorType: invalid_request + errorMessage: At least one authentication method must be provided. '401': - $ref: '#/components/responses/UnauthorizedError' - '402': - $ref: '#/components/responses/PaymentMethodRequiredError' - '404': - description: Account not found. + description: Unauthorized. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - unknown_address: + unauthorized: value: - errorType: not_found - errorMessage: No account with the given address exists for this end user. - errorParam: address - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#not-found + errorType: unauthorized + errorMessage: Wallet authentication error. + '402': + $ref: '#/components/responses/PaymentMethodRequiredError' '409': - description: Conflict with an existing delegation. + description: Resource already exists. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - user_scoped_delegation_active: - value: - errorType: already_exists - errorMessage: A user-scoped delegation is already active for this user. Revoke it before creating an account-scoped delegation. - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#already-exists - account_scoped_delegation_active: + already_exists: value: errorType: already_exists - errorMessage: An account-scoped delegation is already active for this address. - errorParam: address - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#already-exists + errorMessage: An account with the given address already exists. '422': $ref: '#/components/responses/IdempotencyError' - '429': - description: Rate limit exceeded. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - rate_limit_exceeded: - value: - errorType: rate_limit_exceeded - errorMessage: Too many requests. Please try again later. - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#rate-limit-exceeded '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - get: + /v2/embedded-wallet-api/end-users/{userId}/evm/sign/transaction: + post: x-audience: public - summary: Get account-scoped delegation for an end user account + summary: Sign transaction via end user EVM account description: |- - Returns the active account-scoped delegation for the specified end user account, if one exists. Useful for showing delegation status in a UI. - When the address corresponds to an EVM Smart Account, this returns the delegation for the Smart Account's owner EOA. - operationId: getDelegationForEndUserAccount + Signs a transaction with the given end user EVM account. + The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). + + The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. + operationId: signEvmTransactionWithEndUserAccount tags: - Embedded Wallets security: - endUserAuth: [] - apiKeyAuth: [] parameters: + - $ref: '#/components/parameters/XWalletAuthOptional' + - $ref: '#/components/parameters/IdempotencyKey' - name: userId + description: The ID of the end user. in: path required: true - description: The ID of the end user. schema: type: string pattern: ^[a-zA-Z0-9-]{1,100}$ example: e051beeb-7163-4527-a5b6-35e301529ff2 - - name: address - in: path - required: true - description: The blockchain address of the end user account to query. For EVM addresses, matching is case-insensitive. - schema: - $ref: '#/components/schemas/BlockchainAddress' - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + - $ref: '#/components/parameters/XDeveloperAuth' - $ref: '#/components/parameters/ProjectIDOptional' + requestBody: + content: + application/json: + schema: + type: object + properties: + address: + type: string + description: The 0x-prefixed address of the EVM account belonging to the end user. + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + pattern: ^0x[0-9a-fA-F]{40}$ + transaction: + type: string + description: The RLP-encoded transaction to sign, as a 0x-prefixed hex string. + example: '0xf86b098505d21dba00830334509431415daf58e2c6b7323b4c58712fd92952145da79018080' + walletSecretId: + description: Required when not using delegated signing. The ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. + type: string + pattern: ^[a-zA-Z0-9-]{1,100}$ + example: e051beeb-7163-4527-a5b6-35e301529ff2 + required: + - address + - transaction responses: '200': - description: Active delegation found. + description: Successfully signed transaction. content: application/json: schema: type: object properties: - expiresAt: + signedTransaction: type: string - format: date-time - description: The date until which the delegation is valid. - example: '2026-02-03T10:35:00Z' + description: The RLP-encoded signed transaction, as a 0x-prefixed hex string. + example: '0x1b0c9cf8cd4554c6c6d9e7311e88f1be075d7f25b418a044f4bf2c0a42a93e212ad0a8b54de9e0b5f7e3812de3f2c6cc79aa8c3e1c02e7ad14b4a8f42012c2c01b' required: - - expiresAt - example: - expiresAt: '2026-02-03T10:35:00Z' + - signedTransaction + '400': + description: Invalid request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + malformed_transaction: + value: + errorType: malformed_transaction + errorMessage: Malformed unsigned transaction. '401': $ref: '#/components/responses/UnauthorizedError' + '402': + $ref: '#/components/responses/PaymentMethodRequiredError' + '403': + $ref: '#/components/responses/DelegationForbiddenError' '404': - description: No active delegation found. + description: Not found. content: application/json: schema: @@ -2699,101 +3138,49 @@ paths: not_found: value: errorType: not_found - errorMessage: No active account-scoped delegation found for the specified address. - errorParam: address - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#not-found + errorMessage: EVM account with the given address not found. + '409': + $ref: '#/components/responses/AlreadyExistsError' + '422': + $ref: '#/components/responses/IdempotencyError' '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - delete: + /v2/embedded-wallet-api/end-users/{userId}/evm/send/transaction: + post: x-audience: public - summary: Revoke account-scoped delegation for an end user account + summary: Send transaction via end user EVM account description: |- - Revokes the active account-scoped delegation for the specified end user account. Other account-scoped delegations for the same user are unaffected. This operation can be performed by the end user themselves or by a developer using their API key. - When the address corresponds to an EVM Smart Account, this revokes the delegation for the Smart Account's owner EOA. - operationId: revokeDelegationForEndUserAccount - tags: - - Embedded Wallets - security: - - endUserAuth: [] - - apiKeyAuth: [] - parameters: - - $ref: '#/components/parameters/XWalletAuthOptional' - - $ref: '#/components/parameters/XDeveloperAuth' - required: false - - $ref: '#/components/parameters/IdempotencyKey' - - name: userId - in: path - required: true - description: The ID of the end user. - schema: - type: string - pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 - - name: address - in: path - required: true - description: The blockchain address of the end user account whose delegation should be revoked. For EVM addresses, matching is case-insensitive. - schema: - $ref: '#/components/schemas/BlockchainAddress' - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - - $ref: '#/components/parameters/ProjectIDOptional' - requestBody: - required: true - content: - application/json: - schema: - type: object - properties: - walletSecretId: - description: When revoking with a wallet authentication scheme, the ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. - type: string - pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 - example: - walletSecretId: e051beeb-7163-4527-a5b6-35e301529ff2 - responses: - '204': - description: Delegation revoked successfully. - '401': - $ref: '#/components/responses/UnauthorizedError' - '404': - description: Delegation not found. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - not_found: - value: - errorType: not_found - errorMessage: No active account-scoped delegation found for the specified address. - errorParam: address - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#not-found - '500': - $ref: '#/components/responses/InternalServerError' - '502': - $ref: '#/components/responses/BadGatewayError' - '503': - $ref: '#/components/responses/ServiceUnavailableError' - /v2/embedded-wallet-api/end-users/{userId}/evm/eip7702/delegation: - post: - x-audience: public - summary: Create EIP-7702 delegation for end user EVM account - description: |- - Creates an EIP-7702 delegation for an end user's EVM EOA account, upgrading it with smart account capabilities. + Signs a transaction with the given end user EVM account and sends it to the indicated supported network. This API handles nonce management and gas estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). - This endpoint: - - Retrieves delegation artifacts from onchain - - Signs the EIP-7702 authorization for delegation - - Assembles and submits a Type 4 transaction - - Creates an associated smart account object + The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). - The delegation allows the EVM EOA to be used as a smart account, which enables batched transactions and gas sponsorship via paymaster. - operationId: createEvmEip7702DelegationWithEndUserAccount + + **Transaction fields and API behavior** + + - `to` *(Required)*: The address of the contract or account to send the transaction to. + - `chainId` *(Ignored)*: The value of the `chainId` field in the transaction is ignored. + The transaction will be sent to the network indicated by the `network` field in the request body. + + - `nonce` *(Optional)*: The nonce to use for the transaction. If not provided, the API will assign + a nonce to the transaction based on the current state of the account. + + - `maxPriorityFeePerGas` *(Optional)*: The maximum priority fee per gas to use for the transaction. + If not provided, the API will estimate a value based on current network conditions. + + - `maxFeePerGas` *(Optional)*: The maximum fee per gas to use for the transaction. + If not provided, the API will estimate a value based on current network conditions. + + - `gasLimit` *(Optional)*: The gas limit to use for the transaction. If not provided, the API will estimate a value + based on the `to` and `data` fields of the transaction. + + - `value` *(Optional)*: The amount of ETH, in wei, to send with the transaction. + - `data` *(Optional)*: The data to send with the transaction; only used for contract calls. + - `accessList` *(Optional)*: The access list to use for the transaction. + operationId: sendEvmTransactionWithEndUserAccount tags: - Embedded Wallets security: @@ -2803,9 +3190,9 @@ paths: - $ref: '#/components/parameters/XWalletAuthOptional' - $ref: '#/components/parameters/IdempotencyKey' - name: userId + description: The ID of the end user. in: path required: true - description: The ID of the end user. schema: type: string pattern: ^[a-zA-Z0-9-]{1,100}$ @@ -2813,7 +3200,6 @@ paths: - $ref: '#/components/parameters/XDeveloperAuth' - $ref: '#/components/parameters/ProjectIDOptional' requestBody: - required: true content: application/json: schema: @@ -2821,39 +3207,52 @@ paths: properties: address: type: string - description: The 0x-prefixed address of the EVM account to delegate. + description: The 0x-prefixed address of the EVM account belonging to the end user. example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' pattern: ^0x[0-9a-fA-F]{40}$ network: - $ref: '#/components/schemas/EvmEip7702DelegationNetwork' - enableSpendPermissions: - type: boolean - description: Whether to configure spend permissions for the upgraded, delegated account. When enabled, the account can grant permissions for third parties to spend on its behalf. - default: false - example: true + type: string + description: The network to send the transaction to. + enum: + - base + - base-sepolia + - ethereum + - ethereum-sepolia + - avalanche + - polygon + - optimism + - arbitrum + - arbitrum-sepolia + - world + - world-sepolia + example: base-sepolia walletSecretId: description: Required when not using delegated signing. The ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. type: string pattern: ^[a-zA-Z0-9-]{1,100}$ example: e051beeb-7163-4527-a5b6-35e301529ff2 + transaction: + type: string + description: The RLP-encoded transaction to sign and send, as a 0x-prefixed hex string. + example: '0xf86b098505d21dba00830334509431415daf58e2c6b7323b4c58712fd92952145da79018080' required: - address + - transaction - network responses: - '201': - description: Delegation operation created successfully. + '200': + description: Successfully signed and sent transaction. content: application/json: schema: type: object properties: - delegationOperationId: + transactionHash: type: string - format: uuid - description: The unique identifier for the delegation operation. Use this to poll the operation status. - example: a1b2c3d4-e5f6-7890-abcd-ef1234567890 + description: The hash of the transaction, as a 0x-prefixed hex string. + example: '0xf8f98fb6726fc936f24b2007df5cb20e2b8444ff3dfaa2a929335f432a9be2e7' required: - - delegationOperationId + - transactionHash '400': description: Invalid request. content: @@ -2861,24 +3260,18 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - missing_network: - value: - errorType: invalid_request - errorMessage: Field 'network' is required. - errorParam: network - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request - unsupported_network: + malformed_transaction: value: - errorType: invalid_request - errorMessage: Network 'gnosis' is not supported for EIP-7702. - errorParam: network - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request + errorType: malformed_transaction + errorMessage: Malformed unsigned transaction. '401': $ref: '#/components/responses/UnauthorizedError' '402': $ref: '#/components/responses/PaymentMethodRequiredError' + '403': + $ref: '#/components/responses/DelegationForbiddenError' '404': - description: EVM account not found. + description: Not found. content: application/json: schema: @@ -2888,55 +3281,32 @@ paths: value: errorType: not_found errorMessage: EVM account with the given address not found. - errorParam: address - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#not-found '409': - description: Account already delegated on the given network. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - already_delegated: - value: - errorType: already_exists - errorMessage: Account already has an active EIP-7702 delegation on the given network. - errorParam: address - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#already-exists + $ref: '#/components/responses/AlreadyExistsError' '422': $ref: '#/components/responses/IdempotencyError' - '429': - description: Rate limit exceeded. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - rate_limit_exceeded: - value: - errorType: rate_limit_exceeded - errorMessage: Too many requests. Please try again later. - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#rate-limit-exceeded '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/embedded-wallet-api/end-users/{userId}/evm/smart-accounts/{address}/send: + /v2/embedded-wallet-api/end-users/{userId}/evm/{address}/send/{asset}: post: x-audience: public - summary: Send a user operation for end user Smart Account - description: Prepares, signs, and sends a user operation for an end user's Smart Account. - operationId: sendUserOperationWithEndUserAccount + summary: Send USDC on EVM + description: |- + Sends USDC from an end user's EVM account (EOA or Smart Account) to a recipient address on a supported EVM network. This endpoint simplifies USDC transfers by automatically handling contract resolution, decimal conversion, gas estimation, and transaction encoding. + The `amount` field accepts human-readable amounts as decimal strings (e.g., "1.5", "25.50"). + operationId: sendEvmAssetWithEndUserAccount tags: - Embedded Wallets security: - endUserAuth: [] - apiKeyAuth: [] parameters: - - $ref: '#/components/parameters/IdempotencyKey' - $ref: '#/components/parameters/XWalletAuthOptional' + - $ref: '#/components/parameters/IdempotencyKey' - name: userId in: path required: true @@ -2944,15 +3314,26 @@ paths: schema: type: string pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 + example: e051beeb-7163-4527-a5b6-35e301529ff2 - name: address - description: The address of the EVM Smart Account to execute the user operation from. + description: The 0x-prefixed address of the EVM account (EOA or Smart Account) to send USDC from. The address does not need to be checksummed. in: path required: true schema: - type: string + allOf: + - $ref: '#/components/schemas/BlockchainAddress' pattern: ^0x[0-9a-fA-F]{40}$ example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + - name: asset + in: path + required: true + description: The asset to send. Currently only "usdc" is supported. + schema: + allOf: + - $ref: '#/components/schemas/Asset' + enum: + - usdc + example: usdc - $ref: '#/components/parameters/XDeveloperAuth' - $ref: '#/components/parameters/ProjectIDOptional' requestBody: @@ -2961,73 +3342,147 @@ paths: schema: type: object properties: + to: + allOf: + - $ref: '#/components/schemas/BlockchainAddress' + pattern: ^0x[0-9a-fA-F]{40}$ + description: The 0x-prefixed address of the recipient. + example: '0x1234567890123456789012345678901234567890' + amount: + type: string + minLength: 1 + maxLength: 32 + description: The amount of USDC to send as a decimal string (e.g., "1.5" or "25.50"). + example: '1.50' network: - $ref: '#/components/schemas/EvmUserOperationNetwork' - calls: - type: array - description: The list of calls to make from the Smart Account. - items: - $ref: '#/components/schemas/EvmCall' + type: string + description: The EVM network to send USDC on. + enum: + - base + - base-sepolia + - ethereum + - ethereum-sepolia + - avalanche + - polygon + - optimism + - arbitrum + - arbitrum-sepolia + - world + - world-sepolia + example: base-sepolia useCdpPaymaster: type: boolean - description: Whether to use the CDP Paymaster for the user operation. + description: Whether to use CDP Paymaster to sponsor gas fees. Only applicable for EVM Smart Accounts. When true, the transaction gas will be paid by the Paymaster, allowing users to send USDC without holding native gas tokens. Ignored for EOA accounts. Cannot be used together with `paymasterUrl`. example: true paymasterUrl: allOf: - $ref: '#/components/schemas/Url' - description: The URL of the paymaster to use for the user operation. If using the CDP Paymaster, use the `useCdpPaymaster` option. - example: https://api.developer.coinbase.com/rpc/v1/base/ + description: Optional custom Paymaster URL to use for gas sponsorship. Only applicable for EVM Smart Accounts. This allows you to use your own Paymaster service instead of CDP's Paymaster. Cannot be used together with `useCdpPaymaster`. + example: https://api.developer.coinbase.com/rpc/v1/base/AbCdEf123456 walletSecretId: description: Required when not using delegated signing. The ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. type: string pattern: ^[a-zA-Z0-9-]{1,100}$ example: e051beeb-7163-4527-a5b6-35e301529ff2 - dataSuffix: - type: string - pattern: ^0x[0-9a-fA-F]+$ - description: The EIP-8021 data suffix (hex-encoded) that enables transaction attribution for the user operation. - example: '0xdddddddd62617365617070070080218021802180218021802180218021' required: + - to + - amount - network - - calls - - useCdpPaymaster - responses: - '200': - description: The user operation was successfully prepared, signed, and sent. - content: - application/json: - schema: - $ref: '#/components/schemas/EvmUserOperation' - '400': - description: Invalid request. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - invalid_request: + examples: + send_usdc_eoa: + summary: Send USDC from EOA + value: + to: '0x1234567890123456789012345678901234567890' + amount: '25.50' + network: base-sepolia + walletSecretId: e051beeb-7163-4527-a5b6-35e301529ff2 + send_usdc_smart_account_cdp_paymaster: + summary: Send USDC from Smart Account with CDP Paymaster + value: + to: '0x1234567890123456789012345678901234567890' + amount: '10.00' + network: base-sepolia + useCdpPaymaster: true + walletSecretId: e051beeb-7163-4527-a5b6-35e301529ff2 + send_usdc_smart_account_custom_paymaster: + summary: Send USDC from Smart Account with custom Paymaster + value: + to: '0x1234567890123456789012345678901234567890' + amount: '15.00' + network: base-sepolia + paymasterUrl: https://api.developer.coinbase.com/rpc/v1/base/AbCdEf123456 + walletSecretId: e051beeb-7163-4527-a5b6-35e301529ff2 + responses: + '200': + description: Successfully sent transaction. + content: + application/json: + schema: + type: object + properties: + transactionHash: + type: string + description: The hash of the transaction, as a 0x-prefixed hex string. Populated for EOA accounts. Null for Smart Accounts (use userOpHash instead). + example: '0xf8f98fb6726fc936f24b2007df5cb20e2b8444ff3dfaa2a929335f432a9be2e7' + nullable: true + userOpHash: + type: string + description: The hash of the user operation, as a 0x-prefixed hex string. Populated for Smart Accounts. Null for EOA accounts (use transactionHash instead). + example: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' + nullable: true + examples: + eoa_transfer: + summary: EOA transfer response value: - errorType: invalid_request - errorMessage: Field "network" is required. - invalid_signature: + transactionHash: '0xf8f98fb6726fc936f24b2007df5cb20e2b8444ff3dfaa2a929335f432a9be2e7' + userOpHash: null + smart_account_transfer: + summary: Smart Account transfer response value: - errorType: invalid_signature - errorMessage: Failed to sign user operation. - '401': - $ref: '#/components/responses/UnauthorizedError' - '402': - $ref: '#/components/responses/PaymentMethodRequiredError' - '403': - description: Access to resource forbidden. + transactionHash: null + userOpHash: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' + '400': + description: Invalid request. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - forbidden: + invalid_amount: value: - errorType: forbidden - errorMessage: Unable to sign transaction for this address. + errorType: invalid_request + errorMessage: Invalid amount format. Amount must be a valid decimal string. + errorParam: amount + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request + invalid_network: + value: + errorType: invalid_request + errorMessage: Unsupported network for USDC transfers. + errorParam: network + errorLink: https://docs.cdp.coinbase.com/get-started/supported-networks#supported-networks + invalid_asset: + value: + errorType: invalid_request + errorMessage: Unsupported asset. Currently only 'usdc' is supported. + errorParam: asset + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request + insufficient_balance: + value: + errorType: invalid_request + errorMessage: Account has insufficient USDC balance to complete the transfer. + errorParam: amount + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request + conflicting_paymaster: + value: + errorType: invalid_request + errorMessage: Cannot specify both 'useCdpPaymaster' and 'paymasterUrl'. Please use only one. + errorLink: https://docs.cdp.coinbase.com/embedded-wallets/evm-features/smart-accounts#gas-sponsorship-with-paymaster + '401': + $ref: '#/components/responses/UnauthorizedError' + '402': + $ref: '#/components/responses/PaymentMethodRequiredError' + '403': + $ref: '#/components/responses/DelegationForbiddenError' '404': description: Not found. content: @@ -3038,32 +3493,26 @@ paths: not_found: value: errorType: not_found - errorMessage: End user Smart Account with the given address not found. - '429': - description: Rate limit exceeded. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - rate_limit_exceeded: - value: - errorType: rate_limit_exceeded - errorMessage: Max concurrent user operations reached. + errorMessage: EVM account with the given address not found. + errorParam: address + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#not-found + '422': + $ref: '#/components/responses/IdempotencyError' '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/embedded-wallet-api/end-users/{userId}/solana/sign/message: + /v2/embedded-wallet-api/end-users/{userId}/evm/sign/message: post: x-audience: public - summary: Sign a Base64 encoded message + summary: Sign EIP-191 message via end user EVM account description: |- - Signs an arbitrary Base64 encoded message with the given Solana account. - **WARNING:** Never sign a message that you didn't generate as it may put your funds at risk. - operationId: signSolanaMessageWithEndUserAccount + Signs an [EIP-191](https://eips.ethereum.org/EIPS/eip-191) message with the given end user EVM account. + + Per the specification, the message in the request body is prepended with `0x19 <0x45 (E)> ` before being signed. + operationId: signEvmMessageWithEndUserAccount tags: - Embedded Wallets security: @@ -3090,13 +3539,13 @@ paths: properties: address: type: string - description: The base58 encoded address of the Solana account belonging to the end user. - example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT - pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ + description: The 0x-prefixed address of the EVM account belonging to the end user. + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + pattern: ^0x[0-9a-fA-F]{40}$ message: type: string - description: The base64 encoded arbitrary message to sign. - example: SGVsbG8sIHdvcmxk + description: The message to sign. + example: Hello, world! walletSecretId: description: Required when not using delegated signing. The ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. type: string @@ -3115,27 +3564,18 @@ paths: properties: signature: type: string - description: The signature of the message, as a base58 encoded string. - example: 4YecmNqVT9QFqzuSvE9Zih3toZzNAijjXpj8xupgcC6E4VzwzFjuZBk5P99yz9JQaLRLm1K4L4FpMjxByFxQBe2h + description: The signature of the message, as a 0x-prefixed hex string. + example: '0x1b0c9cf8cd4554c6c6d9e7311e88f1be075d7f25b418a044f4bf2c0a42a93e212ad0a8b54de9e0b5f7e3812de3f2c6cc79aa8c3e1c02e7ad14b4a8f42012c2c01b' required: - signature - '400': - description: Invalid request. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - malformed_transaction: - value: - errorType: invalid_request - errorMessage: Malformed message to sign. '401': $ref: '#/components/responses/UnauthorizedError' '402': $ref: '#/components/responses/PaymentMethodRequiredError' + '403': + $ref: '#/components/responses/DelegationForbiddenError' '404': - description: Solana account not found. + description: Not found. content: application/json: schema: @@ -3144,7 +3584,7 @@ paths: not_found: value: errorType: not_found - errorMessage: Solana account with the given address not found. + errorMessage: EVM account with the given address not found. '409': $ref: '#/components/responses/AlreadyExistsError' '422': @@ -3155,35 +3595,28 @@ paths: $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/embedded-wallet-api/end-users/{userId}/solana/sign/transaction: + /v2/embedded-wallet-api/end-users/{userId}/evm/sign/typed-data: post: x-audience: public - summary: Sign a transaction with end user Solana account - description: |- - Signs a transaction with the given end user Solana account. - The unsigned transaction should be serialized into a byte array and then encoded as base64. - **Transaction types** - The following transaction types are supported: - * [Legacy transactions](https://solana-labs.github.io/solana-web3.js/classes/Transaction.html) - * [Versioned transactions](https://solana-labs.github.io/solana-web3.js/classes/VersionedTransaction.html) - The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. - operationId: signSolanaTransactionWithEndUserAccount + summary: Sign EIP-712 typed data via end user EVM account + description: Signs [EIP-712](https://eips.ethereum.org/EIPS/eip-712) typed data with the given end user EVM account. + operationId: signEvmTypedDataWithEndUserAccount tags: - Embedded Wallets security: - endUserAuth: [] - apiKeyAuth: [] parameters: + - $ref: '#/components/parameters/XWalletAuthOptional' + - $ref: '#/components/parameters/IdempotencyKey' - name: userId + description: The ID of the end user. in: path required: true - description: The ID of the end user. schema: type: string pattern: ^[a-zA-Z0-9-]{1,100}$ example: e051beeb-7163-4527-a5b6-35e301529ff2 - - $ref: '#/components/parameters/XWalletAuthOptional' - - $ref: '#/components/parameters/IdempotencyKey' - $ref: '#/components/parameters/XDeveloperAuth' - $ref: '#/components/parameters/ProjectIDOptional' requestBody: @@ -3194,13 +3627,11 @@ paths: properties: address: type: string - description: The base58 encoded address of the Solana account belonging to the end user. - example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT - pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ - transaction: - type: string - description: The base64 encoded transaction to sign. - example: AQABAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA= + description: The 0x-prefixed address of the EVM account belonging to the end user. + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + pattern: ^0x[0-9a-fA-F]{40}$ + typedData: + $ref: '#/components/schemas/EIP712Message' walletSecretId: description: Required when not using delegated signing. The ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. type: string @@ -3208,21 +3639,21 @@ paths: example: e051beeb-7163-4527-a5b6-35e301529ff2 required: - address - - transaction + - typedData responses: '200': - description: Successfully signed transaction. + description: Successfully signed typed data. content: application/json: schema: type: object properties: - signedTransaction: + signature: type: string - description: The base64 encoded signed transaction. - example: AQACAdSOvpk0UJXs/rQRXYKSI9hcR0bkGp24qGv6t0/M1XjcQpHf6AHwLcPjEtKQI7p/U0Zo98lnJ5/PZMfVq/0BAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA= + description: The signature of the typed data, as a 0x-prefixed hex string. + example: '0x1b0c9cf8cd4554c6c6d9e7311e88f1be075d7f25b418a044f4bf2c0a42a93e212ad0a8b54de9e0b5f7e3812de3f2c6cc79aa8c3e1c02e7ad14b4a8f42012c2c01b' required: - - signedTransaction + - signature '400': description: Invalid request. content: @@ -3230,25 +3661,16 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - malformed_transaction: + invalid_request: value: - errorType: malformed_transaction - errorMessage: Malformed unsigned transaction. + errorType: invalid_request + errorMessage: Invalid request. Please check the request body and parameters. '401': $ref: '#/components/responses/UnauthorizedError' '402': $ref: '#/components/responses/PaymentMethodRequiredError' '403': - description: Access to resource forbidden. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - forbidden: - value: - errorType: forbidden - errorMessage: Unable to sign transaction for this address. + $ref: '#/components/responses/DelegationForbiddenError' '404': description: Not found. content: @@ -3259,9 +3681,7 @@ paths: not_found: value: errorType: not_found - errorMessage: End user with the given ID not found. - '409': - $ref: '#/components/responses/AlreadyExistsError' + errorMessage: EVM account with the given address not found. '422': $ref: '#/components/responses/IdempotencyError' '500': @@ -3270,137 +3690,110 @@ paths: $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/embedded-wallet-api/end-users/{userId}/solana/send/transaction: - post: + /v2/embedded-wallet-api/end-users/{userId}/delegation: + get: x-audience: public - summary: Send a transaction with end user Solana account - description: |- - Signs a transaction with the given end user Solana account and sends it to the indicated supported network. - The API handles recent blockhash management and fee estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. - The unsigned transaction should be serialized into a byte array and then encoded as base64. - **Transaction types** - The following transaction types are supported: - * [Legacy transactions](https://solana.com/developers/guides/advanced/versions#current-transaction-versions) - * [Versioned transactions](https://solana.com/developers/guides/advanced/versions) - **Instruction Batching** - To batch multiple operations, include multiple instructions within a single transaction. All instructions within a transaction are executed atomically - if any instruction fails, the entire transaction fails and is rolled back. - **Network Support** - The following Solana networks are supported: - * `solana` - Solana Mainnet - * `solana-devnet` - Solana Devnet - The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. - operationId: sendSolanaTransactionWithEndUserAccount + summary: Get delegation for end user + description: Returns the active delegation for the specified end user, if one exists. This operation can be performed by the end user themselves or by a developer using their API key. + operationId: getDelegationForEndUser tags: - Embedded Wallets security: - endUserAuth: [] - apiKeyAuth: [] parameters: - - $ref: '#/components/parameters/XWalletAuthOptional' - - $ref: '#/components/parameters/IdempotencyKey' - - $ref: '#/components/parameters/XDeveloperAuth' - name: userId - description: The ID of the end user. in: path required: true + description: The ID of the end user. schema: type: string pattern: ^[a-zA-Z0-9-]{1,100}$ example: e051beeb-7163-4527-a5b6-35e301529ff2 - $ref: '#/components/parameters/ProjectIDOptional' - requestBody: - content: - application/json: - schema: - type: object - properties: - address: - type: string - description: The base58 encoded address of the Solana account belonging to the end user. - example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT - pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ - network: - type: string - description: The Solana network to send the transaction to. - enum: - - solana - - solana-devnet - example: solana-devnet - walletSecretId: - description: Required when not using delegated signing. The ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. - type: string - pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 - transaction: - type: string - description: The base64 encoded transaction to sign and send. This transaction can contain multiple instructions for native Solana batching. - example: AQABAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA= - useCdpSponsor: - type: boolean - description: Whether transaction fees should be sponsored by CDP. When true, CDP sponsors the transaction fees on behalf of the end user. When false, the end user is responsible for paying the transaction fees. - example: true - required: - - address - - network - - transaction - examples: - send_transaction: - summary: Send a transaction - value: - address: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT - network: solana-devnet - transaction: AQABAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA= - walletSecretId: e051beeb-7163-4527-a5b6-35e301529ff2 - send_transaction_sponsored: - summary: Send a transaction with CDP gas sponsorship - value: - address: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT - network: solana-devnet - transaction: AQABAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA= - walletSecretId: e051beeb-7163-4527-a5b6-35e301529ff2 - useCdpSponsor: true responses: '200': - description: Successfully signed and sent transaction. + description: Active delegation found. content: application/json: schema: type: object properties: - transactionSignature: + expiresAt: type: string - description: The base58 encoded transaction signature. - example: 5VERv8NMvzbJMEkV8xnrLkEaWRtSz9CosKDYjCJjBRnbJLgp8uirBgmQpjKhoR4tjF3ZpRzrFmBV6UjKdiSZkQUW + format: date-time + description: The date until which the delegation is valid. + example: '2026-02-03T10:35:00Z' required: - - transactionSignature - '400': - description: Invalid request. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - malformed_transaction: - value: - errorType: malformed_transaction - errorMessage: Malformed unsigned transaction. + - expiresAt + example: + expiresAt: '2026-02-03T10:35:00Z' '401': $ref: '#/components/responses/UnauthorizedError' - '402': - $ref: '#/components/responses/PaymentMethodRequiredError' - '403': - description: Access to resource forbidden. + '404': + description: No active delegation found. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - forbidden: + not_found: value: - errorType: forbidden - errorMessage: Unable to sign transaction for this address. + errorType: not_found + errorMessage: No active delegation found for the specified end user. + errorParam: userId + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#not-found + '500': + $ref: '#/components/responses/InternalServerError' + '502': + $ref: '#/components/responses/BadGatewayError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + delete: + x-audience: public + summary: Revoke delegation for end user + description: Revokes all active delegations for the specified end user. This operation can be performed by the end user themselves or by a developer using their API key. + operationId: revokeDelegationForEndUser + tags: + - Embedded Wallets + security: + - endUserAuth: [] + - apiKeyAuth: [] + parameters: + - $ref: '#/components/parameters/XWalletAuthOptional' + - $ref: '#/components/parameters/XDeveloperAuth' + required: false + - $ref: '#/components/parameters/IdempotencyKey' + - name: userId + in: path + required: true + description: The ID of the end user. + schema: + type: string + pattern: ^[a-zA-Z0-9-]{1,100}$ + example: e051beeb-7163-4527-a5b6-35e301529ff2 + - $ref: '#/components/parameters/ProjectIDOptional' + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + walletSecretId: + description: When revoking with a wallet authentication scheme, the ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. + type: string + pattern: ^[a-zA-Z0-9-]{1,100}$ + example: e051beeb-7163-4527-a5b6-35e301529ff2 + example: + walletSecretId: e051beeb-7163-4527-a5b6-35e301529ff2 + responses: + '204': + description: Delegation revoked successfully. + '401': + $ref: '#/components/responses/UnauthorizedError' '404': - description: Not found. + description: Delegation not found. content: application/json: schema: @@ -3409,33 +3802,31 @@ paths: not_found: value: errorType: not_found - errorMessage: Solana account with the given address not found. - '422': - $ref: '#/components/responses/IdempotencyError' + errorMessage: No active delegation found for the specified end user. + errorParam: userId + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#not-found '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/embedded-wallet-api/end-users/{userId}/solana/{address}/send/{asset}: + /v2/embedded-wallet-api/end-users/{userId}/address/{address}/delegation: post: x-audience: public - summary: Send USDC on Solana + summary: Create account-scoped delegation for end user description: |- - Sends USDC from an end user's Solana account to a recipient address on the Solana network. This endpoint simplifies USDC transfers by automatically handling mint resolution, Associated Token Account (ATA) creation, decimal conversion, and transaction encoding. - The `amount` field accepts human-readable amounts as decimal strings (e.g., "1.5", "25.50"). - Use the optional `createRecipientAta` parameter to control whether the sender pays for creating the recipient's Associated Token Account if it doesn't exist. - operationId: sendSolanaAssetWithEndUserAccount + Creates an account-scoped delegation that allows a developer to sign on behalf of an end user for a single blockchain account (identified by its address) for the specified duration. The end user must be authenticated to authorize this delegation. + Multiple account-scoped delegations may exist concurrently for a single end user (one per canonical account address). Account-scoped and user-scoped delegations cannot coexist for the same user. + When the address corresponds to an EVM Smart Account, the delegation is scoped to the Smart Account's owner EOA rather than the Smart Account address itself. This means `/address/{smartAccountAddress}/delegation` and `/address/{ownerEoaAddress}/delegation` resolve to the same delegation, and the 409 `account_scoped_delegation_active` error may be returned when creating via either address if one already exists for the canonical owner. + operationId: createDelegationForEndUserAccount tags: - Embedded Wallets security: - endUserAuth: [] - - apiKeyAuth: [] parameters: - - $ref: '#/components/parameters/XWalletAuthOptional' + - $ref: '#/components/parameters/XWalletAuth' - $ref: '#/components/parameters/IdempotencyKey' - - $ref: '#/components/parameters/XDeveloperAuth' - name: userId in: path required: true @@ -3443,339 +3834,179 @@ paths: schema: type: string pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 + example: e051beeb-7163-4527-a5b6-35e301529ff2 - name: address - description: The base58 encoded address of the Solana account to send USDC from. - in: path - required: true - schema: - allOf: - - $ref: '#/components/schemas/BlockchainAddress' - pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ - example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT - - name: asset in: path required: true - description: The asset to send. Currently only "usdc" is supported. + description: The blockchain address of the end user account to scope this delegation to. Format varies by network (e.g., 0x-prefixed for EVM, base58 for Solana). For EVM addresses, matching is case-insensitive. schema: - allOf: - - $ref: '#/components/schemas/Asset' - enum: - - usdc - example: usdc + $ref: '#/components/schemas/BlockchainAddress' + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - $ref: '#/components/parameters/ProjectIDOptional' requestBody: + required: true content: application/json: schema: type: object properties: - to: - allOf: - - $ref: '#/components/schemas/BlockchainAddress' - pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ - description: The base58 encoded address of the recipient. - example: ExXhNkgYf6efh7YyqDRVxPZuzafobao1A74drUdp8trd - amount: - type: string - minLength: 1 - maxLength: 32 - description: The amount of USDC to send as a decimal string (e.g., "1.5" or "25.50"). - example: '1.50' - network: + expiresAt: type: string - description: The Solana network to send USDC on. - enum: - - solana - - solana-devnet - example: solana-devnet - createRecipientAta: - type: boolean - description: Whether to automatically create an Associated Token Account (ATA) for the recipient if it doesn't exist. When true, the sender pays the rent-exempt minimum to create the recipient's USDC ATA. When false, the transaction will fail if the recipient doesn't have a USDC ATA. - example: true + format: date-time + description: The date until which the delegation is valid. + example: '2026-02-03T10:35:00Z' walletSecretId: - description: Required when not using delegated signing. The ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. + description: The ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. type: string pattern: ^[a-zA-Z0-9-]{1,100}$ example: e051beeb-7163-4527-a5b6-35e301529ff2 - useCdpSponsor: - type: boolean - description: Whether transaction fees should be sponsored by CDP. When true, CDP sponsors the transaction fees on behalf of the end user. When false, the end user is responsible for paying the transaction fees. - example: true required: - - to - - amount - - network - examples: - send_usdc_auto_create_ata: - summary: Send USDC (auto-create ATA) - value: - to: ExXhNkgYf6efh7YyqDRVxPZuzafobao1A74drUdp8trd - amount: '25.50' - network: solana-devnet - createRecipientAta: true - walletSecretId: e051beeb-7163-4527-a5b6-35e301529ff2 - send_usdc_no_ata_creation: - summary: Send USDC (no ATA creation) - value: - to: ExXhNkgYf6efh7YyqDRVxPZuzafobao1A74drUdp8trd - amount: '5.00' - network: solana-devnet - createRecipientAta: false - walletSecretId: e051beeb-7163-4527-a5b6-35e301529ff2 - send_usdc_sponsored: - summary: Send USDC with CDP gas sponsorship - value: - to: ExXhNkgYf6efh7YyqDRVxPZuzafobao1A74drUdp8trd - amount: '25.50' - network: solana-devnet - walletSecretId: e051beeb-7163-4527-a5b6-35e301529ff2 - useCdpSponsor: true + - expiresAt + - walletSecretId + example: + expiresAt: '2026-02-03T10:35:00Z' + walletSecretId: e051beeb-7163-4527-a5b6-35e301529ff2 responses: - '200': - description: Successfully sent transaction. + '201': + description: Delegation created successfully. content: application/json: schema: type: object properties: - transactionSignature: + expiresAt: type: string - description: The base58 encoded transaction signature. - example: 5VERv8NMvzbJMEkV8xnrLkEaWRtSz9CosKDYjCJjBRnbJLgp8uirBgmQpjKhoR4tjF3ZpRzrFmBV6UjKdiSZkQUW + format: date-time + description: The date until which the delegation is valid. + example: '2026-02-03T10:35:00Z' required: - - transactionSignature - examples: - successful_transfer: - value: - transactionSignature: 5VERv8NMvzbJMEkV8xnrLkEaWRtSz9CosKDYjCJjBRnbJLgp8uirBgmQpjKhoR4tjF3ZpRzrFmBV6UjKdiSZkQUW - '400': + - expiresAt + example: + expiresAt: '2026-02-03T10:35:00Z' + '400': description: Invalid request. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - invalid_amount: - value: - errorType: invalid_request - errorMessage: Invalid amount format. Amount must be a valid decimal string. - errorParam: amount - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request - invalid_network: - value: - errorType: invalid_request - errorMessage: Unsupported network for USDC transfers. - errorParam: network - errorLink: https://docs.cdp.coinbase.com/get-started/supported-networks#supported-networks - invalid_asset: - value: - errorType: invalid_request - errorMessage: Unsupported asset. Currently only 'usdc' is supported. - errorParam: asset - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request - insufficient_balance: - value: - errorType: invalid_request - errorMessage: Account has insufficient USDC balance to complete the transfer. - errorParam: amount - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request - insufficient_sol: + missing_expiresAt: value: errorType: invalid_request - errorMessage: Account has insufficient SOL to pay for transaction fees and rent. + errorMessage: Field 'expiresAt' is required. + errorParam: expiresAt errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request - recipient_ata_missing: + invalid_expiresAt: value: errorType: invalid_request - errorMessage: 'Recipient does not have a USDC Associated Token Account. Set ''createRecipientAta: true'' to create one automatically.' - errorParam: to + errorMessage: Field 'expiresAt' must be a valid ISO 8601 string. + errorParam: expiresAt errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request '401': $ref: '#/components/responses/UnauthorizedError' '402': $ref: '#/components/responses/PaymentMethodRequiredError' '404': - description: Not found. + description: Account not found. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - not_found: + unknown_address: value: errorType: not_found - errorMessage: Solana account with the given address not found. + errorMessage: No account with the given address exists for this end user. errorParam: address errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#not-found - '422': - $ref: '#/components/responses/IdempotencyError' - '500': - $ref: '#/components/responses/InternalServerError' - '502': - $ref: '#/components/responses/BadGatewayError' - '503': - $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/accounts: - get: - x-audience: public - summary: List EVM accounts - description: |- - Lists the EVM accounts belonging to the developer's CDP Project. - The response is paginated, and by default, returns 20 accounts per page. - operationId: listEvmAccounts - tags: - - EVM Accounts - security: - - apiKeyAuth: [] - parameters: - - $ref: '#/components/parameters/PageSize' - - $ref: '#/components/parameters/PageToken' - responses: - '200': - description: Successfully listed EVM accounts. - content: - application/json: - schema: - allOf: - - type: object - properties: - accounts: - type: array - items: - $ref: '#/components/schemas/EvmAccount' - description: The list of EVM accounts. - required: - - accounts - - $ref: '#/components/schemas/ListResponse' - '500': - $ref: '#/components/responses/InternalServerError' - '502': - $ref: '#/components/responses/BadGatewayError' - '503': - $ref: '#/components/responses/ServiceUnavailableError' - post: - x-audience: public - summary: Create an EVM account - description: Creates a new EVM account. - operationId: createEvmAccount - tags: - - EVM Accounts - security: - - apiKeyAuth: [] - parameters: - - $ref: '#/components/parameters/XWalletAuth' - - $ref: '#/components/parameters/IdempotencyKey' - requestBody: - required: false - content: - application/json: - schema: - type: object - properties: - name: - type: string - description: |- - 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. - example: my-wallet - pattern: ^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$ - accountPolicy: - type: string - x-audience: public - description: The ID of the account-level policy to apply to the account. - pattern: ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ - example: 123e4567-e89b-12d3-a456-426614174000 - responses: - '201': - description: Successfully created EVM account. - content: - application/json: - schema: - $ref: '#/components/schemas/EvmAccount' - '400': - description: Invalid request. + '409': + description: Conflict with an existing delegation. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - invalid_request: + user_scoped_delegation_active: value: - errorType: invalid_request - errorMessage: Project has no secret. Please register a secret with the project. - '401': - description: Unauthorized. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - unauthorized: + errorType: already_exists + errorMessage: A user-scoped delegation is already active for this user. Revoke it before creating an account-scoped delegation. + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#already-exists + account_scoped_delegation_active: value: - errorType: unauthorized - errorMessage: Wallet authentication error. - '402': - $ref: '#/components/responses/PaymentMethodRequiredError' - '409': - description: Resource already exists. + errorType: already_exists + errorMessage: An account-scoped delegation is already active for this address. + errorParam: address + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#already-exists + '422': + $ref: '#/components/responses/IdempotencyError' + '429': + description: Rate limit exceeded. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - already_exists: + rate_limit_exceeded: value: - errorType: already_exists - errorMessage: EVM account with the given name already exists. - '422': - $ref: '#/components/responses/IdempotencyError' + errorType: rate_limit_exceeded + errorMessage: Too many requests. Please try again later. + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#rate-limit-exceeded '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/accounts/{address}: get: x-audience: public - summary: Get an EVM account by address - description: Gets an EVM account by its address. - operationId: getEvmAccount + summary: Get account-scoped delegation for end user + description: |- + Returns the active account-scoped delegation for the specified end user account, if one exists. Useful for showing delegation status in a UI. + When the address corresponds to an EVM Smart Account, this returns the delegation for the Smart Account's owner EOA. + operationId: getDelegationForEndUserAccount tags: - - EVM Accounts + - Embedded Wallets security: + - endUserAuth: [] - apiKeyAuth: [] parameters: - - name: address - description: The 0x-prefixed address of the EVM account. The address does not need to be checksummed. + - name: userId in: path required: true + description: The ID of the end user. schema: type: string - pattern: ^0x[0-9a-fA-F]{40}$ + pattern: ^[a-zA-Z0-9-]{1,100}$ + example: e051beeb-7163-4527-a5b6-35e301529ff2 + - name: address + in: path + required: true + description: The blockchain address of the end user account to query. For EVM addresses, matching is case-insensitive. + schema: + $ref: '#/components/schemas/BlockchainAddress' example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + - $ref: '#/components/parameters/ProjectIDOptional' responses: '200': - description: Successfully got EVM account. - content: - application/json: - schema: - $ref: '#/components/schemas/EvmAccount' - '400': - description: Invalid request. + description: Active delegation found. content: application/json: schema: - $ref: '#/components/schemas/Error' - examples: - invalid_request: - value: - errorType: invalid_request - errorMessage: 'request body has an error: doesn''t match schema: Error at "name": string doesn''t match the regular expression "^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$"' + type: object + properties: + expiresAt: + type: string + format: date-time + description: The date until which the delegation is valid. + example: '2026-02-03T10:35:00Z' + required: + - expiresAt + example: + expiresAt: '2026-02-03T10:35:00Z' + '401': + $ref: '#/components/responses/UnauthorizedError' '404': - description: Not found. + description: No active delegation found. content: application/json: schema: @@ -3784,59 +4015,161 @@ paths: not_found: value: errorType: not_found - errorMessage: EVM account with the given address not found. + errorMessage: No active account-scoped delegation found for the specified address. + errorParam: address + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#not-found '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - put: + delete: x-audience: public - summary: Update an EVM account - description: Updates an existing EVM account. Use this to update the account's name or account-level policy. - operationId: updateEvmAccount + summary: Revoke account-scoped delegation for end user + description: |- + Revokes the active account-scoped delegation for the specified end user account. Other account-scoped delegations for the same user are unaffected. This operation can be performed by the end user themselves or by a developer using their API key. + When the address corresponds to an EVM Smart Account, this revokes the delegation for the Smart Account's owner EOA. + operationId: revokeDelegationForEndUserAccount tags: - - EVM Accounts + - Embedded Wallets security: + - endUserAuth: [] - apiKeyAuth: [] parameters: + - $ref: '#/components/parameters/XWalletAuthOptional' + - $ref: '#/components/parameters/XDeveloperAuth' + required: false - $ref: '#/components/parameters/IdempotencyKey' - - name: address - description: The 0x-prefixed address of the EVM account. The address does not need to be checksummed. + - name: userId in: path required: true + description: The ID of the end user. schema: type: string - pattern: ^0x[0-9a-fA-F]{40}$ + pattern: ^[a-zA-Z0-9-]{1,100}$ + example: e051beeb-7163-4527-a5b6-35e301529ff2 + - name: address + in: path + required: true + description: The blockchain address of the end user account whose delegation should be revoked. For EVM addresses, matching is case-insensitive. + schema: + $ref: '#/components/schemas/BlockchainAddress' example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + - $ref: '#/components/parameters/ProjectIDOptional' requestBody: + required: true content: application/json: schema: type: object properties: - name: + walletSecretId: + description: When revoking with a wallet authentication scheme, the ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. type: string - description: |- - 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. - example: my-wallet - pattern: ^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$ - accountPolicy: + pattern: ^[a-zA-Z0-9-]{1,100}$ + example: e051beeb-7163-4527-a5b6-35e301529ff2 + example: + walletSecretId: e051beeb-7163-4527-a5b6-35e301529ff2 + responses: + '204': + description: Delegation revoked successfully. + '401': + $ref: '#/components/responses/UnauthorizedError' + '404': + description: Delegation not found. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + not_found: + value: + errorType: not_found + errorMessage: No active account-scoped delegation found for the specified address. + errorParam: address + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#not-found + '500': + $ref: '#/components/responses/InternalServerError' + '502': + $ref: '#/components/responses/BadGatewayError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + /v2/embedded-wallet-api/end-users/{userId}/evm/eip7702/delegation: + post: + x-audience: public + summary: Create EIP-7702 delegation for end user EVM account + description: |- + Creates an EIP-7702 delegation for an end user's EVM EOA account, upgrading it with smart account capabilities. + + This endpoint: + - Retrieves delegation artifacts from onchain + - Signs the EIP-7702 authorization for delegation + - Assembles and submits a Type 4 transaction + - Creates an associated smart account object + + The delegation allows the EVM EOA to be used as a smart account, which enables batched transactions and gas sponsorship via paymaster. + operationId: createEvmEip7702DelegationWithEndUserAccount + tags: + - Embedded Wallets + security: + - endUserAuth: [] + - apiKeyAuth: [] + parameters: + - $ref: '#/components/parameters/XWalletAuthOptional' + - $ref: '#/components/parameters/IdempotencyKey' + - name: userId + in: path + required: true + description: The ID of the end user. + schema: + type: string + pattern: ^[a-zA-Z0-9-]{1,100}$ + example: e051beeb-7163-4527-a5b6-35e301529ff2 + - $ref: '#/components/parameters/XDeveloperAuth' + - $ref: '#/components/parameters/ProjectIDOptional' + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + address: type: string - x-audience: public - description: The ID of the account-level policy to apply to the account, or an empty string to unset attached policy. - pattern: (^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$)|(^$) - example: 123e4567-e89b-12d3-a456-426614174000 + description: The 0x-prefixed address of the EVM account to delegate. + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + pattern: ^0x[0-9a-fA-F]{40}$ + network: + $ref: '#/components/schemas/EvmEip7702DelegationNetwork' + enableSpendPermissions: + type: boolean + description: Whether to configure spend permissions for the upgraded, delegated account. When enabled, the account can grant permissions for third parties to spend on its behalf. + default: false + example: true + walletSecretId: + description: Required when not using delegated signing. The ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. + type: string + pattern: ^[a-zA-Z0-9-]{1,100}$ + example: e051beeb-7163-4527-a5b6-35e301529ff2 + required: + - address + - network responses: - '200': - description: Successfully updated EVM account. + '201': + description: Delegation operation created successfully. content: application/json: schema: - $ref: '#/components/schemas/EvmAccount' + type: object + properties: + delegationOperationId: + type: string + format: uuid + description: The unique identifier for the delegation operation. Use this to poll the operation status. + example: a1b2c3d4-e5f6-7890-abcd-ef1234567890 + required: + - delegationOperationId '400': description: Invalid request. content: @@ -3844,10 +4177,24 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - invalid_request: + missing_network: + value: + errorType: invalid_request + errorMessage: Field 'network' is required. + errorParam: network + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request + unsupported_network: value: errorType: invalid_request - errorMessage: 'request body has an error: doesn''t match schema: Error at "/name": string doesn''t match the regular expression "^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$"' + errorMessage: Network 'gnosis' is not supported for EIP-7702. + errorParam: network + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request + '401': + $ref: '#/components/responses/UnauthorizedError' + '402': + $ref: '#/components/responses/PaymentMethodRequiredError' + '403': + $ref: '#/components/responses/DelegationForbiddenError' '404': description: EVM account not found. content: @@ -3859,41 +4206,116 @@ paths: value: errorType: not_found errorMessage: EVM account with the given address not found. + errorParam: address + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#not-found '409': - $ref: '#/components/responses/AlreadyExistsError' + description: Account already delegated on the given network. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + already_delegated: + value: + errorType: already_exists + errorMessage: Account already has an active EIP-7702 delegation on the given network. + errorParam: address + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#already-exists '422': $ref: '#/components/responses/IdempotencyError' + '429': + description: Rate limit exceeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + rate_limit_exceeded: + value: + errorType: rate_limit_exceeded + errorMessage: Too many requests. Please try again later. + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#rate-limit-exceeded '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/accounts/by-name/{name}: - get: + /v2/embedded-wallet-api/end-users/{userId}/evm/smart-accounts/{address}/send: + post: x-audience: public - summary: Get an EVM account by name - description: Gets an EVM account by its name. - operationId: getEvmAccountByName + summary: Send user operation for end user Smart Account + description: Prepares, signs, and sends a user operation for an end user's Smart Account. + operationId: sendUserOperationWithEndUserAccount tags: - - EVM Accounts + - Embedded Wallets security: + - endUserAuth: [] - apiKeyAuth: [] parameters: - - name: name - description: The name of the EVM account. + - $ref: '#/components/parameters/IdempotencyKey' + - $ref: '#/components/parameters/XWalletAuthOptional' + - name: userId in: path required: true + description: The ID of the end user. schema: type: string - example: my-account + pattern: ^[a-zA-Z0-9-]{1,100}$ + example: e051beeb-7163-4527-a5b6-35e301529ff2 + - name: address + description: The address of the EVM Smart Account to execute the user operation from. + in: path + required: true + schema: + type: string + pattern: ^0x[0-9a-fA-F]{40}$ + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + - $ref: '#/components/parameters/XDeveloperAuth' + - $ref: '#/components/parameters/ProjectIDOptional' + requestBody: + content: + application/json: + schema: + type: object + properties: + network: + $ref: '#/components/schemas/EvmUserOperationNetwork' + calls: + type: array + description: The list of calls to make from the Smart Account. + items: + $ref: '#/components/schemas/EvmCall' + useCdpPaymaster: + type: boolean + description: Whether to use the CDP Paymaster for the user operation. + example: true + paymasterUrl: + allOf: + - $ref: '#/components/schemas/Url' + description: The URL of the paymaster to use for the user operation. If using the CDP Paymaster, use the `useCdpPaymaster` option. + example: https://api.developer.coinbase.com/rpc/v1/base/ + walletSecretId: + description: Required when not using delegated signing. The ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. + type: string + pattern: ^[a-zA-Z0-9-]{1,100}$ + example: e051beeb-7163-4527-a5b6-35e301529ff2 + dataSuffix: + type: string + pattern: ^0x[0-9a-fA-F]+$ + description: The EIP-8021 data suffix (hex-encoded) that enables transaction attribution for the user operation. + example: '0xdddddddd62617365617070070080218021802180218021802180218021' + required: + - network + - calls + - useCdpPaymaster responses: '200': - description: Successfully got EVM account. + description: The user operation was successfully prepared, signed, and sent. content: application/json: schema: - $ref: '#/components/schemas/EvmAccount' + $ref: '#/components/schemas/EvmUserOperation' '400': description: Invalid request. content: @@ -3904,7 +4326,17 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: 'error: parameter "name" must be a string' + errorMessage: Field "network" is required. + invalid_signature: + value: + errorType: invalid_signature + errorMessage: Failed to sign user operation. + '401': + $ref: '#/components/responses/UnauthorizedError' + '402': + $ref: '#/components/responses/PaymentMethodRequiredError' + '403': + $ref: '#/components/responses/DelegationForbiddenError' '404': description: Not found. content: @@ -3915,103 +4347,87 @@ paths: not_found: value: errorType: not_found - errorMessage: EVM account with the given name not found. + errorMessage: End user Smart Account with the given address not found. + '429': + description: Rate limit exceeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + rate_limit_exceeded: + value: + errorType: rate_limit_exceeded + errorMessage: Max concurrent user operations reached. '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/accounts/{address}/send/transaction: + /v2/embedded-wallet-api/end-users/{userId}/solana/sign/message: post: x-audience: public - summary: Send a transaction + summary: Sign Base64-encoded message description: |- - Signs a transaction with the given EVM account and sends it to the indicated supported network. This API handles nonce management and gas estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). - - The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). - - - **Transaction fields and API behavior** - - - `to` *(Required)*: The address of the contract or account to send the transaction to. - - `chainId` *(Ignored)*: The value of the `chainId` field in the transaction is ignored. - The transaction will be sent to the network indicated by the `network` field in the request body. - - - `nonce` *(Optional)*: The nonce to use for the transaction. If not provided, the API will assign - a nonce to the transaction based on the current state of the account. - - - `maxPriorityFeePerGas` *(Optional)*: The maximum priority fee per gas to use for the transaction. - If not provided, the API will estimate a value based on current network conditions. - - - `maxFeePerGas` *(Optional)*: The maximum fee per gas to use for the transaction. - If not provided, the API will estimate a value based on current network conditions. - - - `gasLimit` *(Optional)*: The gas limit to use for the transaction. If not provided, the API will estimate a value - based on the `to` and `data` fields of the transaction. - - - `value` *(Optional)*: The amount of ETH, in wei, to send with the transaction. - - `data` *(Optional)*: The data to send with the transaction; only used for contract calls. - - `accessList` *(Optional)*: The access list to use for the transaction. - operationId: sendEvmTransaction + Signs an arbitrary Base64 encoded message with the given Solana account. + **WARNING:** Never sign a message that you didn't generate as it may put your funds at risk. + operationId: signSolanaMessageWithEndUserAccount tags: - - EVM Accounts + - Embedded Wallets security: + - endUserAuth: [] - apiKeyAuth: [] parameters: - - $ref: '#/components/parameters/XWalletAuth' + - $ref: '#/components/parameters/XWalletAuthOptional' - $ref: '#/components/parameters/IdempotencyKey' - - name: address - description: The 0x-prefixed address of the Ethereum account. + - name: userId + description: The ID of the end user. in: path required: true schema: type: string - pattern: ^0x[0-9a-fA-F]{40}$ - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + pattern: ^[a-zA-Z0-9-]{1,100}$ + example: e051beeb-7163-4527-a5b6-35e301529ff2 + - $ref: '#/components/parameters/XDeveloperAuth' + - $ref: '#/components/parameters/ProjectIDOptional' requestBody: content: application/json: schema: type: object properties: - network: + address: type: string - description: The network to send the transaction to. - enum: - - base - - base-sepolia - - ethereum - - ethereum-sepolia - - avalanche - - polygon - - optimism - - arbitrum - - arbitrum-sepolia - - world - - world-sepolia - example: base-sepolia - transaction: + description: The base58 encoded address of the Solana account belonging to the end user. + example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ + message: type: string - description: The RLP-encoded transaction to sign and send, as a 0x-prefixed hex string. - example: '0xf86b098505d21dba00830334509431415daf58e2c6b7323b4c58712fd92952145da79018080' + description: The base64 encoded arbitrary message to sign. + example: SGVsbG8sIHdvcmxk + walletSecretId: + description: Required when not using delegated signing. The ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. + type: string + pattern: ^[a-zA-Z0-9-]{1,100}$ + example: e051beeb-7163-4527-a5b6-35e301529ff2 required: - - transaction - - network + - address + - message responses: '200': - description: Successfully signed and sent transaction. + description: Successfully signed message. content: application/json: schema: type: object properties: - transactionHash: + signature: type: string - description: The hash of the transaction, as a 0x-prefixed hex string. - example: '0xf8f98fb6726fc936f24b2007df5cb20e2b8444ff3dfaa2a929335f432a9be2e7' + description: The signature of the message, as a base58 encoded string. + example: 4YecmNqVT9QFqzuSvE9Zih3toZzNAijjXpj8xupgcC6E4VzwzFjuZBk5P99yz9JQaLRLm1K4L4FpMjxByFxQBe2h required: - - transactionHash + - signature '400': description: Invalid request. content: @@ -4021,34 +4437,16 @@ paths: examples: malformed_transaction: value: - errorType: malformed_transaction - errorMessage: Malformed unsigned transaction. + errorType: invalid_request + errorMessage: Malformed message to sign. '401': - description: Unauthorized. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - unauthorized: - value: - errorType: unauthorized - errorMessage: Wallet authentication error. + $ref: '#/components/responses/UnauthorizedError' '402': $ref: '#/components/responses/PaymentMethodRequiredError' '403': - description: Access to resource forbidden. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - forbidden: - value: - errorType: forbidden - errorMessage: Unable to sign transaction for this address. + $ref: '#/components/responses/DelegationForbiddenError' '404': - description: Not found. + description: Solana account not found. content: application/json: schema: @@ -4057,7 +4455,7 @@ paths: not_found: value: errorType: not_found - errorMessage: EVM account with the given address not found. + errorMessage: Solana account with the given address not found. '409': $ref: '#/components/responses/AlreadyExistsError' '422': @@ -4068,42 +4466,59 @@ paths: $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/accounts/{address}/sign/transaction: + /v2/embedded-wallet-api/end-users/{userId}/solana/sign/transaction: post: x-audience: public - summary: Sign a transaction + summary: Sign transaction via end user Solana account description: |- - Signs a transaction with the given EVM account. - The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). - - The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. - operationId: signEvmTransaction + Signs a transaction with the given end user Solana account. + The unsigned transaction should be serialized into a byte array and then encoded as base64. + **Transaction types** + The following transaction types are supported: + * [Legacy transactions](https://solana-labs.github.io/solana-web3.js/classes/Transaction.html) + * [Versioned transactions](https://solana-labs.github.io/solana-web3.js/classes/VersionedTransaction.html) + The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. + operationId: signSolanaTransactionWithEndUserAccount tags: - - EVM Accounts + - Embedded Wallets security: + - endUserAuth: [] - apiKeyAuth: [] parameters: - - $ref: '#/components/parameters/XWalletAuth' - - $ref: '#/components/parameters/IdempotencyKey' - - name: address - description: The 0x-prefixed address of the EVM account. + - name: userId in: path required: true + description: The ID of the end user. schema: type: string - pattern: ^0x[0-9a-fA-F]{40}$ - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + pattern: ^[a-zA-Z0-9-]{1,100}$ + example: e051beeb-7163-4527-a5b6-35e301529ff2 + - $ref: '#/components/parameters/XWalletAuthOptional' + - $ref: '#/components/parameters/IdempotencyKey' + - $ref: '#/components/parameters/XDeveloperAuth' + - $ref: '#/components/parameters/ProjectIDOptional' requestBody: content: application/json: schema: type: object properties: + address: + type: string + description: The base58 encoded address of the Solana account belonging to the end user. + example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ transaction: type: string - description: The RLP-encoded transaction to sign, as a 0x-prefixed hex string. - example: '0xf86b098505d21dba00830334509431415daf58e2c6b7323b4c58712fd92952145da79018080' + description: The base64 encoded transaction to sign. + example: AQABAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA= + walletSecretId: + description: Required when not using delegated signing. The ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. + type: string + pattern: ^[a-zA-Z0-9-]{1,100}$ + example: e051beeb-7163-4527-a5b6-35e301529ff2 required: + - address - transaction responses: '200': @@ -4115,8 +4530,8 @@ paths: properties: signedTransaction: type: string - description: The RLP-encoded signed transaction, as a 0x-prefixed hex string. - example: '0x1b0c9cf8cd4554c6c6d9e7311e88f1be075d7f25b418a044f4bf2c0a42a93e212ad0a8b54de9e0b5f7e3812de3f2c6cc79aa8c3e1c02e7ad14b4a8f42012c2c01b' + description: The base64 encoded signed transaction. + example: AQACAdSOvpk0UJXs/rQRXYKSI9hcR0bkGp24qGv6t0/M1XjcQpHf6AHwLcPjEtKQI7p/U0Zo98lnJ5/PZMfVq/0BAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA= required: - signedTransaction '400': @@ -4131,29 +4546,11 @@ paths: errorType: malformed_transaction errorMessage: Malformed unsigned transaction. '401': - description: Unauthorized. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - unauthorized: - value: - errorType: unauthorized - errorMessage: Wallet authentication error. + $ref: '#/components/responses/UnauthorizedError' '402': $ref: '#/components/responses/PaymentMethodRequiredError' '403': - description: Access to resource forbidden. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - forbidden: - value: - errorType: forbidden - errorMessage: Unable to sign transaction for this address. + $ref: '#/components/responses/DelegationForbiddenError' '404': description: Not found. content: @@ -4164,7 +4561,7 @@ paths: not_found: value: errorType: not_found - errorMessage: EVM account with the given address not found. + errorMessage: End user with the given ID not found. '409': $ref: '#/components/responses/AlreadyExistsError' '422': @@ -4175,53 +4572,109 @@ paths: $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/accounts/{address}/sign: + /v2/embedded-wallet-api/end-users/{userId}/solana/send/transaction: post: x-audience: public - summary: Sign a hash - description: Signs an arbitrary 32 byte hash with the given EVM account. - operationId: signEvmHash + summary: Send transaction via end user Solana account + description: |- + Signs a transaction with the given end user Solana account and sends it to the indicated supported network. + The API handles recent blockhash management and fee estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. + The unsigned transaction should be serialized into a byte array and then encoded as base64. + **Transaction types** + The following transaction types are supported: + * [Legacy transactions](https://solana.com/developers/guides/advanced/versions#current-transaction-versions) + * [Versioned transactions](https://solana.com/developers/guides/advanced/versions) + **Instruction Batching** + To batch multiple operations, include multiple instructions within a single transaction. All instructions within a transaction are executed atomically - if any instruction fails, the entire transaction fails and is rolled back. + **Network Support** + The following Solana networks are supported: + * `solana` - Solana Mainnet + * `solana-devnet` - Solana Devnet + The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. + operationId: sendSolanaTransactionWithEndUserAccount tags: - - EVM Accounts + - Embedded Wallets security: + - endUserAuth: [] - apiKeyAuth: [] parameters: - - $ref: '#/components/parameters/XWalletAuth' + - $ref: '#/components/parameters/XWalletAuthOptional' - $ref: '#/components/parameters/IdempotencyKey' - - name: address - description: The 0x-prefixed address of the EVM account. + - $ref: '#/components/parameters/XDeveloperAuth' + - name: userId + description: The ID of the end user. in: path required: true schema: type: string - pattern: ^0x[0-9a-fA-F]{40}$ - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + pattern: ^[a-zA-Z0-9-]{1,100}$ + example: e051beeb-7163-4527-a5b6-35e301529ff2 + - $ref: '#/components/parameters/ProjectIDOptional' requestBody: content: application/json: schema: type: object properties: - hash: + address: type: string - description: The arbitrary 32 byte hash to sign. - example: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' + description: The base58 encoded address of the Solana account belonging to the end user. + example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ + network: + type: string + description: The Solana network to send the transaction to. + enum: + - solana + - solana-devnet + example: solana-devnet + walletSecretId: + description: Required when not using delegated signing. The ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. + type: string + pattern: ^[a-zA-Z0-9-]{1,100}$ + example: e051beeb-7163-4527-a5b6-35e301529ff2 + transaction: + type: string + description: The base64 encoded transaction to sign and send. This transaction can contain multiple instructions for native Solana batching. + example: AQABAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA= + useCdpSponsor: + type: boolean + description: Whether transaction fees should be sponsored by CDP. When true, CDP sponsors the transaction fees on behalf of the end user. When false, the end user is responsible for paying the transaction fees. + example: true required: - - hash - responses: - '200': - description: Successfully signed hash. + - address + - network + - transaction + examples: + send_transaction: + summary: Send a transaction + value: + address: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + network: solana-devnet + transaction: AQABAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA= + walletSecretId: e051beeb-7163-4527-a5b6-35e301529ff2 + send_transaction_sponsored: + summary: Send a transaction with CDP gas sponsorship + value: + address: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + network: solana-devnet + transaction: AQABAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA= + walletSecretId: e051beeb-7163-4527-a5b6-35e301529ff2 + useCdpSponsor: true + responses: + '200': + description: Successfully signed and sent transaction. content: application/json: schema: type: object properties: - signature: + transactionSignature: type: string - description: The signature of the hash, as a 0x-prefixed hex string. - example: '0x1b0c9cf8cd4554c6c6d9e7311e88f1be075d7f25b418a044f4bf2c0a42a93e212ad0a8b54de9e0b5f7e3812de3f2c6cc79aa8c3e1c02e7ad14b4a8f42012c2c01b' + description: The base58 encoded transaction signature. + example: 5VERv8NMvzbJMEkV8xnrLkEaWRtSz9CosKDYjCJjBRnbJLgp8uirBgmQpjKhoR4tjF3ZpRzrFmBV6UjKdiSZkQUW required: - - signature + - transactionSignature '400': description: Invalid request. content: @@ -4229,12 +4682,16 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - invalid_request: + malformed_transaction: value: - errorType: invalid_request - errorMessage: Request body must be specified. + errorType: malformed_transaction + errorMessage: Malformed unsigned transaction. + '401': + $ref: '#/components/responses/UnauthorizedError' '402': $ref: '#/components/responses/PaymentMethodRequiredError' + '403': + $ref: '#/components/responses/DelegationForbiddenError' '404': description: Not found. content: @@ -4245,9 +4702,7 @@ paths: not_found: value: errorType: not_found - errorMessage: EVM account with the given address not found. - '409': - $ref: '#/components/responses/AlreadyExistsError' + errorMessage: Solana account with the given address not found. '422': $ref: '#/components/responses/IdempotencyError' '500': @@ -4256,69 +4711,185 @@ paths: $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/accounts/{address}/sign/message: + /v2/embedded-wallet-api/end-users/{userId}/solana/{address}/send/{asset}: post: x-audience: public - summary: Sign an EIP-191 message + summary: Send USDC on Solana description: |- - Signs an [EIP-191](https://eips.ethereum.org/EIPS/eip-191) message with the given EVM account. - - Per the specification, the message in the request body is prepended with `0x19 <0x45 (E)> ` before being signed. - operationId: signEvmMessage + Sends USDC from an end user's Solana account to a recipient address on the Solana network. This endpoint simplifies USDC transfers by automatically handling mint resolution, Associated Token Account (ATA) creation, decimal conversion, and transaction encoding. + The `amount` field accepts human-readable amounts as decimal strings (e.g., "1.5", "25.50"). + Use the optional `createRecipientAta` parameter to control whether the sender pays for creating the recipient's Associated Token Account if it doesn't exist. + operationId: sendSolanaAssetWithEndUserAccount tags: - - EVM Accounts + - Embedded Wallets security: + - endUserAuth: [] - apiKeyAuth: [] parameters: - - $ref: '#/components/parameters/XWalletAuth' + - $ref: '#/components/parameters/XWalletAuthOptional' - $ref: '#/components/parameters/IdempotencyKey' - - name: address - description: The 0x-prefixed address of the EVM account. + - $ref: '#/components/parameters/XDeveloperAuth' + - name: userId in: path required: true + description: The ID of the end user. schema: type: string - pattern: ^0x[0-9a-fA-F]{40}$ - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + pattern: ^[a-zA-Z0-9-]{1,100}$ + example: e051beeb-7163-4527-a5b6-35e301529ff2 + - name: address + description: The base58 encoded address of the Solana account to send USDC from. + in: path + required: true + schema: + allOf: + - $ref: '#/components/schemas/BlockchainAddress' + pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ + example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + - name: asset + in: path + required: true + description: The asset to send. Currently only "usdc" is supported. + schema: + allOf: + - $ref: '#/components/schemas/Asset' + enum: + - usdc + example: usdc + - $ref: '#/components/parameters/ProjectIDOptional' requestBody: content: application/json: schema: type: object properties: - message: + to: + allOf: + - $ref: '#/components/schemas/BlockchainAddress' + pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ + description: The base58 encoded address of the recipient. + example: ExXhNkgYf6efh7YyqDRVxPZuzafobao1A74drUdp8trd + amount: type: string - description: The message to sign. - example: Hello, world! + minLength: 1 + maxLength: 32 + description: The amount of USDC to send as a decimal string (e.g., "1.5" or "25.50"). + example: '1.50' + network: + type: string + description: The Solana network to send USDC on. + enum: + - solana + - solana-devnet + example: solana-devnet + createRecipientAta: + type: boolean + description: Whether to automatically create an Associated Token Account (ATA) for the recipient if it doesn't exist. When true, the sender pays the rent-exempt minimum to create the recipient's USDC ATA. When false, the transaction will fail if the recipient doesn't have a USDC ATA. + example: true + walletSecretId: + description: Required when not using delegated signing. The ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. + type: string + pattern: ^[a-zA-Z0-9-]{1,100}$ + example: e051beeb-7163-4527-a5b6-35e301529ff2 + useCdpSponsor: + type: boolean + description: Whether transaction fees should be sponsored by CDP. When true, CDP sponsors the transaction fees on behalf of the end user. When false, the end user is responsible for paying the transaction fees. + example: true required: - - message + - to + - amount + - network + examples: + send_usdc_auto_create_ata: + summary: Send USDC (auto-create ATA) + value: + to: ExXhNkgYf6efh7YyqDRVxPZuzafobao1A74drUdp8trd + amount: '25.50' + network: solana-devnet + createRecipientAta: true + walletSecretId: e051beeb-7163-4527-a5b6-35e301529ff2 + send_usdc_no_ata_creation: + summary: Send USDC (no ATA creation) + value: + to: ExXhNkgYf6efh7YyqDRVxPZuzafobao1A74drUdp8trd + amount: '5.00' + network: solana-devnet + createRecipientAta: false + walletSecretId: e051beeb-7163-4527-a5b6-35e301529ff2 + send_usdc_sponsored: + summary: Send USDC with CDP gas sponsorship + value: + to: ExXhNkgYf6efh7YyqDRVxPZuzafobao1A74drUdp8trd + amount: '25.50' + network: solana-devnet + walletSecretId: e051beeb-7163-4527-a5b6-35e301529ff2 + useCdpSponsor: true responses: '200': - description: Successfully signed message. + description: Successfully sent transaction. content: application/json: schema: type: object properties: - signature: + transactionSignature: type: string - description: The signature of the message, as a 0x-prefixed hex string. - example: '0x1b0c9cf8cd4554c6c6d9e7311e88f1be075d7f25b418a044f4bf2c0a42a93e212ad0a8b54de9e0b5f7e3812de3f2c6cc79aa8c3e1c02e7ad14b4a8f42012c2c01b' + description: The base58 encoded transaction signature. + example: 5VERv8NMvzbJMEkV8xnrLkEaWRtSz9CosKDYjCJjBRnbJLgp8uirBgmQpjKhoR4tjF3ZpRzrFmBV6UjKdiSZkQUW required: - - signature - '401': - description: Unauthorized. + - transactionSignature + examples: + successful_transfer: + value: + transactionSignature: 5VERv8NMvzbJMEkV8xnrLkEaWRtSz9CosKDYjCJjBRnbJLgp8uirBgmQpjKhoR4tjF3ZpRzrFmBV6UjKdiSZkQUW + '400': + description: Invalid request. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - unauthorized: + invalid_amount: value: - errorType: unauthorized - errorMessage: Wallet authentication error. + errorType: invalid_request + errorMessage: Invalid amount format. Amount must be a valid decimal string. + errorParam: amount + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request + invalid_network: + value: + errorType: invalid_request + errorMessage: Unsupported network for USDC transfers. + errorParam: network + errorLink: https://docs.cdp.coinbase.com/get-started/supported-networks#supported-networks + invalid_asset: + value: + errorType: invalid_request + errorMessage: Unsupported asset. Currently only 'usdc' is supported. + errorParam: asset + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request + insufficient_balance: + value: + errorType: invalid_request + errorMessage: Account has insufficient USDC balance to complete the transfer. + errorParam: amount + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request + insufficient_sol: + value: + errorType: invalid_request + errorMessage: Account has insufficient SOL to pay for transaction fees and rent. + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request + recipient_ata_missing: + value: + errorType: invalid_request + errorMessage: 'Recipient does not have a USDC Associated Token Account. Set ''createRecipientAta: true'' to create one automatically.' + errorParam: to + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request + '401': + $ref: '#/components/responses/UnauthorizedError' '402': $ref: '#/components/responses/PaymentMethodRequiredError' + '403': + $ref: '#/components/responses/DelegationForbiddenError' '404': description: Not found. content: @@ -4329,9 +4900,9 @@ paths: not_found: value: errorType: not_found - errorMessage: EVM account with the given address not found. - '409': - $ref: '#/components/responses/AlreadyExistsError' + errorMessage: Solana account with the given address not found. + errorParam: address + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#not-found '422': $ref: '#/components/responses/IdempotencyError' '500': @@ -4340,47 +4911,85 @@ paths: $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/accounts/{address}/sign/typed-data: - post: + /v2/evm/accounts: + get: x-audience: public - summary: Sign EIP-712 typed data - description: Signs [EIP-712](https://eips.ethereum.org/EIPS/eip-712) typed data with the given EVM account. - operationId: signEvmTypedData + summary: List EVM accounts + description: |- + Lists the EVM accounts belonging to the developer's CDP Project. + The response is paginated, and by default, returns 20 accounts per page. + operationId: listEvmAccounts tags: - EVM Accounts security: - apiKeyAuth: [] parameters: - - $ref: '#/components/parameters/XWalletAuth' - - $ref: '#/components/parameters/IdempotencyKey' - - name: address - description: The 0x-prefixed address of the EVM account. - in: path - required: true - schema: - type: string - pattern: ^0x[0-9a-fA-F]{40}$ - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/EIP712Message' + - $ref: '#/components/parameters/PageSize' + - $ref: '#/components/parameters/PageToken' responses: '200': - description: Successfully signed typed data. + description: Successfully listed EVM accounts. content: application/json: schema: - type: object - properties: - signature: - type: string - description: The signature of the typed data, as a 0x-prefixed hex string. - example: '0x1b0c9cf8cd4554c6c6d9e7311e88f1be075d7f25b418a044f4bf2c0a42a93e212ad0a8b54de9e0b5f7e3812de3f2c6cc79aa8c3e1c02e7ad14b4a8f42012c2c01b' - required: - - signature - '400': + allOf: + - type: object + properties: + accounts: + type: array + items: + $ref: '#/components/schemas/EvmAccount' + description: The list of EVM accounts. + required: + - accounts + - $ref: '#/components/schemas/ListResponse' + '500': + $ref: '#/components/responses/InternalServerError' + '502': + $ref: '#/components/responses/BadGatewayError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + post: + x-audience: public + summary: Create EVM account + description: Creates a new EVM account. + operationId: createEvmAccount + tags: + - EVM Accounts + security: + - apiKeyAuth: [] + parameters: + - $ref: '#/components/parameters/XWalletAuth' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: false + content: + application/json: + schema: + type: object + properties: + name: + type: string + description: |- + 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. + example: my-wallet + pattern: ^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$ + accountPolicy: + type: string + x-audience: public + description: The ID of the account-level policy to apply to the account. + pattern: ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ + example: 123e4567-e89b-12d3-a456-426614174000 + responses: + '201': + description: Successfully created EVM account. + content: + application/json: + schema: + $ref: '#/components/schemas/EvmAccount' + '400': description: Invalid request. content: application/json: @@ -4390,7 +4999,7 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: Invalid request. Please check the request body and parameters. + errorMessage: Project has no secret. Please register a secret with the project. '401': description: Unauthorized. content: @@ -4404,17 +5013,17 @@ paths: errorMessage: Wallet authentication error. '402': $ref: '#/components/responses/PaymentMethodRequiredError' - '404': - description: Not found. + '409': + description: Resource already exists. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - not_found: + already_exists: value: - errorType: not_found - errorMessage: EVM account with the given address not found. + errorType: already_exists + errorMessage: EVM account with the given name already exists. '422': $ref: '#/components/responses/IdempotencyError' '500': @@ -4423,67 +5032,32 @@ paths: $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/accounts/{address}/eip7702/delegation: - post: + /v2/evm/accounts/{address}: + get: x-audience: public - summary: Create EIP-7702 delegation - description: |- - Creates an EIP-7702 delegation for an EVM EOA account, upgrading it with smart account capabilities. - - This endpoint: - - Retrieves delegation artifacts from onchain - - Signs the EIP-7702 authorization for delegation - - Assembles and submits a Type 4 transaction - - Creates an associated smart account object - - The delegation allows the EVM EOA to be used as a smart account, which enables batched transactions and gas sponsorship via paymaster. - operationId: createEvmEip7702Delegation + summary: Get EVM account by address + description: Gets an EVM account by its address. + operationId: getEvmAccount tags: - EVM Accounts security: - apiKeyAuth: [] parameters: - - $ref: '#/components/parameters/XWalletAuth' - - $ref: '#/components/parameters/IdempotencyKey' - name: address - description: The 0x-prefixed address of the EVM account to delegate. + description: The 0x-prefixed address of the EVM account. The address does not need to be checksummed. in: path required: true schema: type: string pattern: ^0x[0-9a-fA-F]{40}$ - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - requestBody: - required: true - content: - application/json: - schema: - type: object - properties: - network: - $ref: '#/components/schemas/EvmEip7702DelegationNetwork' - enableSpendPermissions: - type: boolean - description: Whether to configure spend permissions for the upgraded, delegated account. When enabled, the account can grant permissions for third parties to spend on its behalf. - default: false - example: true - required: - - network + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' responses: - '201': - description: Delegation operation created successfully. + '200': + description: Successfully got EVM account. content: application/json: schema: - type: object - properties: - delegationOperationId: - type: string - format: uuid - description: The unique identifier for the delegation operation. Use this to poll the operation status. - example: a1b2c3d4-e5f6-7890-abcd-ef1234567890 - required: - - delegationOperationId + $ref: '#/components/schemas/EvmAccount' '400': description: Invalid request. content: @@ -4491,24 +5065,12 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - missing_network: - value: - errorType: invalid_request - errorMessage: Field 'network' is required. - errorParam: network - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request - unsupported_network: + invalid_request: value: errorType: invalid_request - errorMessage: Network 'gnosis' is not supported for EIP-7702. - errorParam: network - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request - '401': - $ref: '#/components/responses/UnauthorizedError' - '402': - $ref: '#/components/responses/PaymentMethodRequiredError' + errorMessage: 'request body has an error: doesn''t match schema: Error at "name": string doesn''t match the regular expression "^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$".' '404': - description: EVM account not found. + description: Not found. content: application/json: schema: @@ -4518,55 +5080,58 @@ paths: value: errorType: not_found errorMessage: EVM account with the given address not found. - errorParam: address - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#not-found - '409': - description: Account already delegated on the given network. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - already_delegated: - value: - errorType: already_exists - errorMessage: Account already has an active EIP-7702 delegation on the given network. - errorParam: address - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#already-exists - '422': - $ref: '#/components/responses/IdempotencyError' '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/eip7702/delegation-operations/{delegationOperationId}: - get: + put: x-audience: public - summary: Get EIP-7702 delegation operation for an operationID - description: Returns the EIP-7702 delegation operation. Use the delegationOperationId returned by the Create EIP-7702 delegation endpoint to poll for operation completion. - operationId: getEvmEip7702DelegationOperationById + summary: Update EVM account + description: Updates an existing EVM account. Use this to update the account's name or account-level policy. + operationId: updateEvmAccount tags: - EVM Accounts security: - apiKeyAuth: [] parameters: - - name: delegationOperationId - description: The unique identifier for the delegation operation. + - $ref: '#/components/parameters/IdempotencyKey' + - name: address + description: The 0x-prefixed address of the EVM account. The address does not need to be checksummed. in: path required: true schema: type: string - format: uuid - example: a1b2c3d4-e5f6-7890-abcd-ef1234567890 + pattern: ^0x[0-9a-fA-F]{40}$ + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + requestBody: + content: + application/json: + schema: + type: object + properties: + name: + type: string + description: |- + 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. + example: my-wallet + pattern: ^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$ + accountPolicy: + type: string + x-audience: public + description: The ID of the account-level policy to apply to the account, or an empty string to unset attached policy. + pattern: (^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$)|(^$) + example: 123e4567-e89b-12d3-a456-426614174000 responses: '200': - description: Delegation operation retrieved successfully. + description: Successfully updated EVM account. content: application/json: schema: - $ref: '#/components/schemas/EvmEip7702DelegationOperation' + $ref: '#/components/schemas/EvmAccount' '400': description: Invalid request. content: @@ -4574,14 +5139,12 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - invalid_id: + invalid_request: value: errorType: invalid_request - errorMessage: Invalid delegation operation ID format. - errorParam: delegationOperationId - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request + errorMessage: 'request body has an error: doesn''t match schema: Error at "/name": string doesn''t match the regular expression "^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$".' '404': - description: Delegation operation not found. + description: EVM account not found. content: application/json: schema: @@ -4590,46 +5153,42 @@ paths: not_found: value: errorType: not_found - errorMessage: Delegation operation not found. - errorParam: delegationOperationId - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#not-found + errorMessage: EVM account with the given address not found. + '409': + $ref: '#/components/responses/AlreadyExistsError' + '422': + $ref: '#/components/responses/IdempotencyError' '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/smart-accounts: + /v2/evm/accounts/by-name/{name}: get: - summary: List Smart Accounts - description: |- - Lists the Smart Accounts belonging to the developer's CDP Project. - The response is paginated, and by default, returns 20 accounts per page. - operationId: listEvmSmartAccounts + x-audience: public + summary: Get EVM account by name + description: Gets an EVM account by its name. + operationId: getEvmAccountByName tags: - - EVM Smart Accounts + - EVM Accounts security: - apiKeyAuth: [] parameters: - - $ref: '#/components/parameters/PageSize' - - $ref: '#/components/parameters/PageToken' + - name: name + description: The name of the EVM account. + in: path + required: true + schema: + type: string + example: my-account responses: '200': - description: Successfully listed Smart Accounts. + description: Successfully got EVM account. content: application/json: schema: - allOf: - - type: object - properties: - accounts: - type: array - items: - $ref: '#/components/schemas/EvmSmartAccount' - description: The list of Smart Accounts. - required: - - accounts - - $ref: '#/components/schemas/ListResponse' + $ref: '#/components/schemas/EvmAccount' '400': description: Invalid request. content: @@ -4640,109 +5199,7 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: Invalid request. Please check the request body and parameters. - '500': - $ref: '#/components/responses/InternalServerError' - '502': - $ref: '#/components/responses/BadGatewayError' - '503': - $ref: '#/components/responses/ServiceUnavailableError' - post: - summary: Create a Smart Account - description: Creates a new Smart Account. - operationId: createEvmSmartAccount - tags: - - EVM Smart Accounts - security: - - apiKeyAuth: [] - parameters: - - $ref: '#/components/parameters/IdempotencyKey' - requestBody: - content: - application/json: - schema: - type: object - properties: - owners: - type: array - description: Today, only a single owner can be set for a Smart Account, but this is an array to allow setting multiple owners in the future. - items: - type: string - pattern: ^0x[0-9a-fA-F]{40}$ - example: - - '0xfc807D1bE4997e5C7B33E4d8D57e60c5b0f02B1a' - name: - type: string - description: |- - 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. - example: my-smart-wallet - pattern: ^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$ - required: - - owners - responses: - '201': - description: Successfully created Smart Account. - content: - application/json: - schema: - $ref: '#/components/schemas/EvmSmartAccount' - '400': - description: Invalid request. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - invalid_request: - value: - errorType: invalid_request - errorMessage: Invalid owner address or account name provided. - '402': - $ref: '#/components/responses/PaymentMethodRequiredError' - '500': - $ref: '#/components/responses/InternalServerError' - '502': - $ref: '#/components/responses/BadGatewayError' - '503': - $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/smart-accounts/by-name/{name}: - get: - x-audience: public - summary: Get a Smart Account by name - description: Gets a Smart Account by its name. - operationId: getEvmSmartAccountByName - security: - - apiKeyAuth: [] - tags: - - EVM Smart Accounts - parameters: - - name: name - description: The name of the Smart Account. - in: path - required: true - schema: - type: string - example: my-account - responses: - '200': - description: Successfully got Smart Account. - content: - application/json: - schema: - $ref: '#/components/schemas/EvmSmartAccount' - '400': - description: Invalid request. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - invalid_request: - value: - errorType: invalid_request - errorMessage: 'error: parameter "name" must be a string' + errorMessage: 'error: parameter "name" must be a string.' '404': description: Not found. content: @@ -4753,19 +5210,45 @@ paths: not_found: value: errorType: not_found - errorMessage: Smart Account with the given name not found. + errorMessage: EVM account with the given name not found. '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/accounts/import: + /v2/evm/accounts/{address}/send/transaction: post: x-audience: public - summary: Import an EVM account - description: Import an existing EVM account into the developer's CDP Project. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. - operationId: importEvmAccount + summary: Send transaction + description: |- + Signs a transaction with the given EVM account and sends it to the indicated supported network. This API handles nonce management and gas estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). + + The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). + + + **Transaction fields and API behavior** + + - `to` *(Required)*: The address of the contract or account to send the transaction to. + - `chainId` *(Ignored)*: The value of the `chainId` field in the transaction is ignored. + The transaction will be sent to the network indicated by the `network` field in the request body. + + - `nonce` *(Optional)*: The nonce to use for the transaction. If not provided, the API will assign + a nonce to the transaction based on the current state of the account. + + - `maxPriorityFeePerGas` *(Optional)*: The maximum priority fee per gas to use for the transaction. + If not provided, the API will estimate a value based on current network conditions. + + - `maxFeePerGas` *(Optional)*: The maximum fee per gas to use for the transaction. + If not provided, the API will estimate a value based on current network conditions. + + - `gasLimit` *(Optional)*: The gas limit to use for the transaction. If not provided, the API will estimate a value + based on the `to` and `data` fields of the transaction. + + - `value` *(Optional)*: The amount of ETH, in wei, to send with the transaction. + - `data` *(Optional)*: The data to send with the transaction; only used for contract calls. + - `accessList` *(Optional)*: The access list to use for the transaction. + operationId: sendEvmTransaction tags: - EVM Accounts security: @@ -4773,39 +5256,57 @@ paths: parameters: - $ref: '#/components/parameters/XWalletAuth' - $ref: '#/components/parameters/IdempotencyKey' + - name: address + description: The 0x-prefixed address of the Ethereum account. + in: path + required: true + schema: + type: string + pattern: ^0x[0-9a-fA-F]{40}$ + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' requestBody: content: application/json: schema: type: object properties: - encryptedPrivateKey: - type: string - description: The base64-encoded, encrypted private key of the EVM account. The private key must be encrypted using the CDP SDK's encryption scheme. - example: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= - name: + network: type: string - description: |- - 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. - example: my-wallet - pattern: ^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$ - accountPolicy: + description: The network to send the transaction to. + enum: + - base + - base-sepolia + - ethereum + - ethereum-sepolia + - avalanche + - polygon + - optimism + - arbitrum + - arbitrum-sepolia + - world + - world-sepolia + example: base-sepolia + transaction: type: string - x-audience: public - description: The ID of the account-level policy to apply to the account. - pattern: ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ - example: 123e4567-e89b-12d3-a456-426614174000 + description: The RLP-encoded transaction to sign and send, as a 0x-prefixed hex string. + example: '0xf86b098505d21dba00830334509431415daf58e2c6b7323b4c58712fd92952145da79018080' required: - - encryptedPrivateKey + - transaction + - network responses: - '201': - description: Successfully imported EVM account. + '200': + description: Successfully signed and sent transaction. content: application/json: schema: - $ref: '#/components/schemas/EvmAccount' + type: object + properties: + transactionHash: + type: string + description: The hash of the transaction, as a 0x-prefixed hex string. + example: '0xf8f98fb6726fc936f24b2007df5cb20e2b8444ff3dfaa2a929335f432a9be2e7' + required: + - transactionHash '400': description: Invalid request. content: @@ -4813,10 +5314,10 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - invalid_request: + malformed_transaction: value: - errorType: invalid_request - errorMessage: The encrypted private key is invalid. + errorType: malformed_transaction + errorMessage: Malformed unsigned transaction. '401': description: Unauthorized. content: @@ -4830,17 +5331,30 @@ paths: errorMessage: Wallet authentication error. '402': $ref: '#/components/responses/PaymentMethodRequiredError' - '409': - description: Resource already exists. + '403': + description: Access to resource forbidden. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - already_exists: + forbidden: value: - errorType: already_exists - errorMessage: EVM account with the given address already exists. + errorType: forbidden + errorMessage: Unable to sign transaction for this address. + '404': + description: Not found. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + not_found: + value: + errorType: not_found + errorMessage: EVM account with the given address not found. + '409': + $ref: '#/components/responses/AlreadyExistsError' '422': $ref: '#/components/responses/IdempotencyError' '500': @@ -4849,23 +5363,25 @@ paths: $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/accounts/{address}/export: + /v2/evm/accounts/{address}/sign/transaction: post: x-audience: public - summary: Export an EVM account - description: Export an existing EVM account's private key. It is important to store the private key in a secure place after it's exported. - operationId: exportEvmAccount + summary: Sign transaction + description: |- + Signs a transaction with the given EVM account. + The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). + + The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. + operationId: signEvmTransaction tags: - EVM Accounts security: - apiKeyAuth: [] - x-required-api-auth-scopes: - - accounts#export parameters: - $ref: '#/components/parameters/XWalletAuth' - $ref: '#/components/parameters/IdempotencyKey' - name: address - description: The 0x-prefixed address of the EVM account. The address does not need to be checksummed. + description: The 0x-prefixed address of the EVM account. in: path required: true schema: @@ -4878,26 +5394,26 @@ paths: schema: type: object properties: - exportEncryptionKey: + transaction: type: string - description: The base64-encoded, public part of the RSA key in DER format used to encrypt the account private key. - example: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= + description: The RLP-encoded transaction to sign, as a 0x-prefixed hex string. + example: '0xf86b098505d21dba00830334509431415daf58e2c6b7323b4c58712fd92952145da79018080' required: - - exportEncryptionKey + - transaction responses: '200': - description: Successfully exported EVM account. + description: Successfully signed transaction. content: application/json: schema: type: object properties: - encryptedPrivateKey: + signedTransaction: type: string - description: The base64-encoded, encrypted private key of the EVM account which is a 32 byte raw private key. The private key is encrypted in transport using the exportEncryptionKey in the request. - example: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= + description: The RLP-encoded signed transaction, as a 0x-prefixed hex string. + example: '0x1b0c9cf8cd4554c6c6d9e7311e88f1be075d7f25b418a044f4bf2c0a42a93e212ad0a8b54de9e0b5f7e3812de3f2c6cc79aa8c3e1c02e7ad14b4a8f42012c2c01b' required: - - encryptedPrivateKey + - signedTransaction '400': description: Invalid request. content: @@ -4905,10 +5421,10 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - invalid_request: + malformed_transaction: value: - errorType: invalid_request - errorMessage: EVM account with the given address not found. + errorType: malformed_transaction + errorMessage: Malformed unsigned transaction. '401': description: Unauthorized. content: @@ -4922,17 +5438,30 @@ paths: errorMessage: Wallet authentication error. '402': $ref: '#/components/responses/PaymentMethodRequiredError' - '404': - description: Not found. + '403': + description: Access to resource forbidden. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - not_found: + forbidden: + value: + errorType: forbidden + errorMessage: Unable to sign transaction for this address. + '404': + description: Not found. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + not_found: value: errorType: not_found errorMessage: EVM account with the given address not found. + '409': + $ref: '#/components/responses/AlreadyExistsError' '422': $ref: '#/components/responses/IdempotencyError' '500': @@ -4941,54 +5470,53 @@ paths: $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/accounts/export/by-name/{name}: + /v2/evm/accounts/{address}/sign: post: x-audience: public - summary: Export an EVM account by name - description: Export an existing EVM account's private key by its name. It is important to store the private key in a secure place after it's exported. - operationId: exportEvmAccountByName + summary: Sign hash + description: Signs an arbitrary 32 byte hash with the given EVM account. + operationId: signEvmHash tags: - EVM Accounts security: - apiKeyAuth: [] - x-required-api-auth-scopes: - - accounts#export parameters: - $ref: '#/components/parameters/XWalletAuth' - $ref: '#/components/parameters/IdempotencyKey' - - name: name - description: The name of the EVM account. + - name: address + description: The 0x-prefixed address of the EVM account. in: path required: true schema: type: string - example: my-account + pattern: ^0x[0-9a-fA-F]{40}$ + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' requestBody: content: application/json: schema: type: object properties: - exportEncryptionKey: + hash: type: string - description: The base64-encoded, public part of the RSA key in DER format used to encrypt the account private key. - example: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= + description: The arbitrary 32 byte hash to sign. + example: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' required: - - exportEncryptionKey + - hash responses: '200': - description: Successfully exported EVM account. + description: Successfully signed hash. content: application/json: schema: type: object properties: - encryptedPrivateKey: + signature: type: string - description: The base64-encoded, encrypted private key of the EVM account which is a 32 byte raw private key. The private key is encrypted in transport using the exportEncryptionKey in the request. - example: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= + description: The signature of the hash, as a 0x-prefixed hex string. + example: '0x1b0c9cf8cd4554c6c6d9e7311e88f1be075d7f25b418a044f4bf2c0a42a93e212ad0a8b54de9e0b5f7e3812de3f2c6cc79aa8c3e1c02e7ad14b4a8f42012c2c01b' required: - - encryptedPrivateKey + - signature '400': description: Invalid request. content: @@ -4999,18 +5527,7 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: 'error: parameter "name" must be a string' - '401': - description: Unauthorized. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - unauthorized: - value: - errorType: unauthorized - errorMessage: Wallet authentication error. + errorMessage: Request body must be specified. '402': $ref: '#/components/responses/PaymentMethodRequiredError' '404': @@ -5023,7 +5540,9 @@ paths: not_found: value: errorType: not_found - errorMessage: EVM account with the given name not found. + errorMessage: EVM account with the given address not found. + '409': + $ref: '#/components/responses/AlreadyExistsError' '422': $ref: '#/components/responses/IdempotencyError' '500': @@ -5032,42 +5551,69 @@ paths: $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/smart-accounts/{address}: - get: - summary: Get a Smart Account by address - description: Gets a Smart Account by its address. - operationId: getEvmSmartAccount + /v2/evm/accounts/{address}/sign/message: + post: + x-audience: public + summary: Sign EIP-191 message + description: |- + Signs an [EIP-191](https://eips.ethereum.org/EIPS/eip-191) message with the given EVM account. + + Per the specification, the message in the request body is prepended with `0x19 <0x45 (E)> ` before being signed. + operationId: signEvmMessage tags: - - EVM Smart Accounts + - EVM Accounts security: - apiKeyAuth: [] parameters: + - $ref: '#/components/parameters/XWalletAuth' + - $ref: '#/components/parameters/IdempotencyKey' - name: address - description: The 0x-prefixed address of the Smart Account. + description: The 0x-prefixed address of the EVM account. in: path required: true schema: type: string pattern: ^0x[0-9a-fA-F]{40}$ example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + requestBody: + content: + application/json: + schema: + type: object + properties: + message: + type: string + description: The message to sign. + example: Hello, world! + required: + - message responses: '200': - description: Successfully got Smart Account. + description: Successfully signed message. content: application/json: schema: - $ref: '#/components/schemas/EvmSmartAccount' - '400': - description: Invalid request. + type: object + properties: + signature: + type: string + description: The signature of the message, as a 0x-prefixed hex string. + example: '0x1b0c9cf8cd4554c6c6d9e7311e88f1be075d7f25b418a044f4bf2c0a42a93e212ad0a8b54de9e0b5f7e3812de3f2c6cc79aa8c3e1c02e7ad14b4a8f42012c2c01b' + required: + - signature + '401': + description: Unauthorized. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - invalid_request: + unauthorized: value: - errorType: invalid_request - errorMessage: Invalid address provided. + errorType: unauthorized + errorMessage: Wallet authentication error. + '402': + $ref: '#/components/responses/PaymentMethodRequiredError' '404': description: Not found. content: @@ -5078,25 +5624,32 @@ paths: not_found: value: errorType: not_found - errorMessage: Smart Account with the given address not found. + errorMessage: EVM account with the given address not found. + '409': + $ref: '#/components/responses/AlreadyExistsError' + '422': + $ref: '#/components/responses/IdempotencyError' '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - put: + /v2/evm/accounts/{address}/sign/typed-data: + post: x-audience: public - summary: Update an EVM Smart Account - description: Updates an existing EVM smart account. Use this to update the smart account's name. - operationId: updateEvmSmartAccount + summary: Sign EIP-712 typed data + description: Signs [EIP-712](https://eips.ethereum.org/EIPS/eip-712) typed data with the given EVM account. + operationId: signEvmTypedData tags: - - EVM Smart Accounts + - EVM Accounts security: - apiKeyAuth: [] parameters: + - $ref: '#/components/parameters/XWalletAuth' + - $ref: '#/components/parameters/IdempotencyKey' - name: address - description: The 0x-prefixed address of the EVM smart account. The address does not need to be checksummed. + description: The 0x-prefixed address of the EVM account. in: path required: true schema: @@ -5107,23 +5660,21 @@ paths: content: application/json: schema: - type: object - properties: - name: - type: string - description: |- - An optional name for the smart 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 smart accounts in the developer's CDP Project. - example: my-smart-account - pattern: ^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$ + $ref: '#/components/schemas/EIP712Message' responses: '200': - description: Successfully updated EVM smart account. + description: Successfully signed typed data. content: application/json: schema: - $ref: '#/components/schemas/EvmSmartAccount' + type: object + properties: + signature: + type: string + description: The signature of the typed data, as a 0x-prefixed hex string. + example: '0x1b0c9cf8cd4554c6c6d9e7311e88f1be075d7f25b418a044f4bf2c0a42a93e212ad0a8b54de9e0b5f7e3812de3f2c6cc79aa8c3e1c02e7ad14b4a8f42012c2c01b' + required: + - signature '400': description: Invalid request. content: @@ -5134,9 +5685,22 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: 'request body has an error: doesn''t match schema: Error at "/name": string doesn''t match the regular expression "^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$"' + errorMessage: Invalid request. Please check the request body and parameters. + '401': + description: Unauthorized. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + unauthorized: + value: + errorType: unauthorized + errorMessage: Wallet authentication error. + '402': + $ref: '#/components/responses/PaymentMethodRequiredError' '404': - description: EVM account not found. + description: Not found. content: application/json: schema: @@ -5145,9 +5709,7 @@ paths: not_found: value: errorType: not_found - errorMessage: EVM smart account with the given address not found. - '409': - $ref: '#/components/responses/AlreadyExistsError' + errorMessage: EVM account with the given address not found. '422': $ref: '#/components/responses/IdempotencyError' '500': @@ -5156,57 +5718,67 @@ paths: $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/smart-accounts/{address}/user-operations: + /v2/evm/accounts/{address}/eip7702/delegation: post: - summary: Prepare a user operation - description: Prepares a new user operation on a Smart Account for a specific network. - operationId: prepareUserOperation + x-audience: public + summary: Create EIP-7702 delegation + description: |- + Creates an EIP-7702 delegation for an EVM EOA account, upgrading it with smart account capabilities. + + This endpoint: + - Retrieves delegation artifacts from onchain + - Signs the EIP-7702 authorization for delegation + - Assembles and submits a Type 4 transaction + - Creates an associated smart account object + + The delegation allows the EVM EOA to be used as a smart account, which enables batched transactions and gas sponsorship via paymaster. + operationId: createEvmEip7702Delegation tags: - - EVM Smart Accounts + - EVM Accounts security: - apiKeyAuth: [] parameters: + - $ref: '#/components/parameters/XWalletAuth' + - $ref: '#/components/parameters/IdempotencyKey' - name: address - description: The address of the Smart Account to create the user operation on. + description: The 0x-prefixed address of the EVM account to delegate. in: path required: true schema: type: string pattern: ^0x[0-9a-fA-F]{40}$ - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' requestBody: + required: true content: application/json: schema: type: object properties: network: - $ref: '#/components/schemas/EvmUserOperationNetwork' - calls: - type: array - description: The list of calls to make from the Smart Account. - items: - $ref: '#/components/schemas/EvmCall' - paymasterUrl: - allOf: - - $ref: '#/components/schemas/Url' - description: The URL of the paymaster to use for the user operation. - example: https://api.developer.coinbase.com/rpc/v1/base/ - dataSuffix: - type: string - pattern: ^0x[0-9a-fA-F]+$ - description: The EIP-8021 data suffix (hex-encoded) that enables transaction attribution for the user operation. - example: '0xdddddddd62617365617070070080218021802180218021802180218021' + $ref: '#/components/schemas/EvmEip7702DelegationNetwork' + enableSpendPermissions: + type: boolean + description: Whether to configure spend permissions for the upgraded, delegated account. When enabled, the account can grant permissions for third parties to spend on its behalf. + default: false + example: true required: - network - - calls responses: '201': - description: The prepared user operation. + description: Delegation operation created successfully. content: application/json: schema: - $ref: '#/components/schemas/EvmUserOperation' + type: object + properties: + delegationOperationId: + type: string + format: uuid + description: The unique identifier for the delegation operation. Use this to poll the operation status. + example: a1b2c3d4-e5f6-7890-abcd-ef1234567890 + required: + - delegationOperationId '400': description: Invalid request. content: @@ -5214,23 +5786,24 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - invalid_request: + missing_network: value: errorType: invalid_request - errorMessage: Field "network" is required. - '403': - description: Access to resource forbidden. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - forbidden: + errorMessage: Field 'network' is required. + errorParam: network + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request + unsupported_network: value: - errorType: forbidden - errorMessage: Unable to sign transaction for this address. - '404': - description: Not found. + errorType: invalid_request + errorMessage: Network 'gnosis' is not supported for EIP-7702. + errorParam: network + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request + '401': + $ref: '#/components/responses/UnauthorizedError' + '402': + $ref: '#/components/responses/PaymentMethodRequiredError' + '404': + description: EVM account not found. content: application/json: schema: @@ -5239,62 +5812,56 @@ paths: not_found: value: errorType: not_found - errorMessage: EVM smart account with the given address not found. + errorMessage: EVM account with the given address not found. + errorParam: address + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#not-found + '409': + description: Account already delegated on the given network. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + already_delegated: + value: + errorType: already_exists + errorMessage: Account already has an active EIP-7702 delegation on the given network. + errorParam: address + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#already-exists + '422': + $ref: '#/components/responses/IdempotencyError' '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/smart-accounts/{address}/user-operations/prepare-and-send: - post: + /v2/evm/eip7702/delegation-operations/{delegationOperationId}: + get: x-audience: public - summary: Prepare and send a user operation for EVM Smart Account - description: Prepares, signs, and sends a user operation for an EVM Smart Account. This API can be used only if the owner on Smart Account is a CDP EVM Account. - operationId: prepareAndSendUserOperation + summary: Get EIP-7702 delegation operation by ID + description: Returns the EIP-7702 delegation operation. Use the delegationOperationId returned by the Create EIP-7702 delegation endpoint to poll for operation completion. + operationId: getEvmEip7702DelegationOperationById tags: - - EVM Smart Accounts + - EVM Accounts security: - apiKeyAuth: [] parameters: - - $ref: '#/components/parameters/IdempotencyKey' - - $ref: '#/components/parameters/XWalletAuth' - - name: address - description: The address of the EVM Smart Account to execute the user operation from. + - name: delegationOperationId + description: The unique identifier for the delegation operation. in: path required: true schema: type: string - pattern: ^0x[0-9a-fA-F]{40}$ - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - requestBody: - content: - application/json: - schema: - type: object - properties: - network: - $ref: '#/components/schemas/EvmUserOperationNetwork' - calls: - type: array - description: The list of calls to make from the Smart Account. - items: - $ref: '#/components/schemas/EvmCall' - paymasterUrl: - allOf: - - $ref: '#/components/schemas/Url' - description: The URL of the paymaster to use for the user operation. - example: https://api.developer.coinbase.com/rpc/v1/base/ - required: - - network - - calls + format: uuid + example: a1b2c3d4-e5f6-7890-abcd-ef1234567890 responses: '200': - description: The user operation was successfully prepared, signed, and sent. + description: Delegation operation retrieved successfully. content: application/json: schema: - $ref: '#/components/schemas/EvmUserOperation' + $ref: '#/components/schemas/EvmEip7702DelegationOperation' '400': description: Invalid request. content: @@ -5302,31 +5869,14 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - invalid_request: + invalid_id: value: errorType: invalid_request - errorMessage: Field "network" is required. - invalid_signature: - value: - errorType: invalid_signature - errorMessage: Failed to sign user operation. - '401': - $ref: '#/components/responses/UnauthorizedError' - '402': - $ref: '#/components/responses/PaymentMethodRequiredError' - '403': - description: Access to resource forbidden. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - forbidden: - value: - errorType: forbidden - errorMessage: Unable to sign transaction for this address. + errorMessage: Invalid delegation operation ID format. + errorParam: delegationOperationId + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request '404': - description: Not found. + description: Delegation operation not found. content: application/json: schema: @@ -5335,57 +5885,46 @@ paths: not_found: value: errorType: not_found - errorMessage: End user Smart Account with the given address not found. - '429': - description: Rate limit exceeded. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - rate_limit_exceeded: - value: - errorType: rate_limit_exceeded - errorMessage: Max concurrent user operations reached. + errorMessage: Delegation operation not found. + errorParam: delegationOperationId + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#not-found '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/smart-accounts/{address}/user-operations/{userOpHash}: + /v2/evm/smart-accounts: get: - summary: Get a user operation - description: Gets a user operation by its hash. - operationId: getUserOperation + summary: List Smart Accounts + description: |- + Lists the Smart Accounts belonging to the developer's CDP Project. + The response is paginated, and by default, returns 20 accounts per page. + operationId: listEvmSmartAccounts tags: - EVM Smart Accounts security: - apiKeyAuth: [] parameters: - - name: address - description: The address of the Smart Account the user operation belongs to. - in: path - required: true - schema: - type: string - pattern: ^0x[0-9a-fA-F]{40}$ - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - - name: userOpHash - description: The hash of the user operation to fetch. - in: path - required: true - schema: - type: string - pattern: ^0x[0-9a-fA-F]{64}$ - example: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' + - $ref: '#/components/parameters/PageSize' + - $ref: '#/components/parameters/PageToken' responses: '200': - description: Successfully retrieved the user operation. + description: Successfully listed Smart Accounts. content: application/json: schema: - $ref: '#/components/schemas/EvmUserOperation' + allOf: + - type: object + properties: + accounts: + type: array + items: + $ref: '#/components/schemas/EvmSmartAccount' + description: The list of Smart Accounts. + required: + - accounts + - $ref: '#/components/schemas/ListResponse' '400': description: Invalid request. content: @@ -5397,72 +5936,53 @@ paths: value: errorType: invalid_request errorMessage: Invalid request. Please check the request body and parameters. - '404': - description: Not found. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - not_found: - value: - errorType: not_found - errorMessage: User operation not found. '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/smart-accounts/{address}/user-operations/{userOpHash}/send: post: - summary: Send a user operation - description: |- - Sends a user operation with a signature. - The payload to sign must be the `userOpHash` field of the user operation. This hash should be signed directly (not using `personal_sign` or EIP-191 message hashing). - The signature must be 65 bytes in length, consisting of: - 32 bytes for the `r` value - 32 bytes for the `s` value - 1 byte for the `v` value (must be 27 or 28) - If using the CDP Paymaster, the user operation must be signed and sent within 2 minutes of being prepared. - operationId: sendUserOperation + summary: Create Smart Account + description: Creates a new Smart Account. + operationId: createEvmSmartAccount tags: - EVM Smart Accounts security: - apiKeyAuth: [] parameters: - - name: address - description: The address of the Smart Account to send the user operation from. - in: path - required: true - schema: - type: string - pattern: ^0x[0-9a-fA-F]{40}$ - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - - name: userOpHash - description: The hash of the user operation to send. - in: path - required: true - schema: - type: string - pattern: ^0x[0-9a-fA-F]{64}$ - example: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' + - $ref: '#/components/parameters/IdempotencyKey' requestBody: content: application/json: schema: type: object properties: - signature: + owners: + type: array + description: Today, only a single owner can be set for a Smart Account, but this is an array to allow setting multiple owners in the future. + items: + type: string + pattern: ^0x[0-9a-fA-F]{40}$ + example: + - '0xfc807D1bE4997e5C7B33E4d8D57e60c5b0f02B1a' + name: type: string - description: The hex-encoded signature of the user operation. This should be a 65-byte signature consisting of the `r`, `s`, and `v` values of the ECDSA signature. Note that the `v` value should conform to the `personal_sign` standard, which means it should be 27 or 28. - example: '0x1b0c9cf8cd4554c6c6d9e7311e88f1be075d7f25b418a044f4bf2c0a42a93e212ad0a8b54de9e0b5f7e3812de3f2c6cc79aa8c3e1c02e7ad14b4a8f42012c2c01b' + description: |- + 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. + example: my-smart-wallet + pattern: ^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$ required: - - signature + - owners responses: - '200': - description: The sent user operation. + '201': + description: Successfully created Smart Account. content: application/json: schema: - $ref: '#/components/schemas/EvmUserOperation' + $ref: '#/components/schemas/EvmSmartAccount' '400': description: Invalid request. content: @@ -5470,85 +5990,117 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - invalid_signature: + invalid_request: value: - errorType: invalid_signature - errorMessage: Invalid signature. + errorType: invalid_request + errorMessage: Invalid owner address or account name provided. '402': $ref: '#/components/responses/PaymentMethodRequiredError' - '403': - description: Access to resource forbidden. + '500': + $ref: '#/components/responses/InternalServerError' + '502': + $ref: '#/components/responses/BadGatewayError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + /v2/evm/smart-accounts/by-name/{name}: + get: + x-audience: public + summary: Get Smart Account by name + description: Gets a Smart Account by its name. + operationId: getEvmSmartAccountByName + security: + - apiKeyAuth: [] + tags: + - EVM Smart Accounts + parameters: + - name: name + description: The name of the Smart Account. + in: path + required: true + schema: + type: string + example: my-account + responses: + '200': + description: Successfully got Smart Account. content: application/json: schema: - $ref: '#/components/schemas/Error' - examples: - forbidden: - value: - errorType: forbidden - errorMessage: Unable to sign transaction for this address. - '404': - description: Not found. + $ref: '#/components/schemas/EvmSmartAccount' + '400': + description: Invalid request. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - not_found: + invalid_request: value: - errorType: not_found - errorMessage: User operation not found. - '429': - description: Rate limit exceeded. + errorType: invalid_request + errorMessage: 'error: parameter "name" must be a string.' + '404': + description: Not found. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - rate_limit_exceeded: + not_found: value: - errorType: rate_limit_exceeded - errorMessage: Max concurrent user operations reached. + errorType: not_found + errorMessage: Smart Account with the given name not found. '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/smart-accounts/{address}/spend-permissions: + /v2/evm/accounts/import: post: x-audience: public - summary: Create a spend permission - description: Creates a spend permission for the given smart account address. - operationId: createSpendPermission + summary: Import EVM account + description: Import an existing EVM account into the developer's CDP Project. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. + operationId: importEvmAccount tags: - - EVM Smart Accounts + - EVM Accounts security: - apiKeyAuth: [] parameters: - $ref: '#/components/parameters/XWalletAuth' - $ref: '#/components/parameters/IdempotencyKey' - - name: address - description: The address of the Smart Account to create the spend permission for. - in: path - required: true - schema: - type: string - pattern: ^0x[0-9a-fA-F]{40}$ - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' requestBody: - required: true content: application/json: schema: - $ref: '#/components/schemas/CreateSpendPermissionRequest' + type: object + properties: + encryptedPrivateKey: + type: string + description: The base64-encoded, encrypted private key of the EVM account. The private key must be encrypted using the CDP SDK's encryption scheme. + example: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= + name: + type: string + description: |- + 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. + example: my-wallet + pattern: ^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$ + accountPolicy: + type: string + x-audience: public + description: The ID of the account-level policy to apply to the account. + pattern: ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ + example: 123e4567-e89b-12d3-a456-426614174000 + required: + - encryptedPrivateKey responses: - '200': - description: Successfully created spend permission. + '201': + description: Successfully imported EVM account. content: application/json: schema: - $ref: '#/components/schemas/EvmUserOperation' + $ref: '#/components/schemas/EvmAccount' '400': description: Invalid request. content: @@ -5559,75 +6111,88 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: Invalid request. Please check the request body and parameters. - '404': - description: Not found. + errorMessage: The encrypted private key is invalid. + '401': + description: Unauthorized. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - not_found: + unauthorized: value: - errorType: not_found - errorMessage: Smart account not found. + errorType: unauthorized + errorMessage: Wallet authentication error. + '402': + $ref: '#/components/responses/PaymentMethodRequiredError' + '409': + description: Resource already exists. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + already_exists: + value: + errorType: already_exists + errorMessage: EVM account with the given address already exists. + '422': + $ref: '#/components/responses/IdempotencyError' '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/smart-accounts/{address}/spend-permissions/list: - get: + /v2/evm/accounts/{address}/export: + post: x-audience: public - summary: List spend permissions - description: Lists spend permission for the given smart account address. - operationId: listSpendPermissions + summary: Export EVM account + description: Export an existing EVM account's private key. It is important to store the private key in a secure place after it's exported. + operationId: exportEvmAccount tags: - - EVM Smart Accounts + - EVM Accounts security: - apiKeyAuth: [] + x-required-api-auth-scopes: + - accounts#export parameters: + - $ref: '#/components/parameters/XWalletAuth' + - $ref: '#/components/parameters/IdempotencyKey' - name: address - description: The address of the Smart account to list spend permissions for. + description: The 0x-prefixed address of the EVM account. The address does not need to be checksummed. in: path required: true schema: type: string pattern: ^0x[0-9a-fA-F]{40}$ example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - - name: pageSize - description: The number of spend permissions to return per page. - in: query - required: false - schema: - type: integer - default: 20 - example: 10 - - name: pageToken - description: The token for the next page of spend permissions. Will be empty if there are no more spend permissions to fetch. - in: query - required: false - schema: - type: string - example: eyJsYXN0X2lkIjogImFiYzEyMyIsICJ0aW1lc3RhbXAiOiAxNzA3ODIzNzAxfQ== + requestBody: + content: + application/json: + schema: + type: object + properties: + exportEncryptionKey: + type: string + description: The base64-encoded, public part of the RSA key in DER format used to encrypt the account private key. + example: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= + required: + - exportEncryptionKey responses: '200': - description: Successfully listed spend permissions. + description: Successfully exported EVM account. content: application/json: schema: - allOf: - - type: object - required: - - spendPermissions - properties: - spendPermissions: - type: array - description: The spend permissions for the smart account. - items: - $ref: '#/components/schemas/SpendPermissionResponseObject' - - $ref: '#/components/schemas/ListResponse' + type: object + properties: + encryptedPrivateKey: + type: string + description: The base64-encoded, encrypted private key of the EVM account which is a 32 byte raw private key. The private key is encrypted in transport using the exportEncryptionKey in the request. + example: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= + required: + - encryptedPrivateKey '400': description: Invalid request. content: @@ -5638,7 +6203,20 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: Invalid request. Please check the request body and parameters. + errorMessage: EVM account with the given address not found. + '401': + description: Unauthorized. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + unauthorized: + value: + errorType: unauthorized + errorMessage: Wallet authentication error. + '402': + $ref: '#/components/responses/PaymentMethodRequiredError' '404': description: Not found. content: @@ -5649,47 +6227,63 @@ paths: not_found: value: errorType: not_found - errorMessage: Smart account not found. + errorMessage: EVM account with the given address not found. + '422': + $ref: '#/components/responses/IdempotencyError' '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/smart-accounts/{address}/spend-permissions/revoke: + /v2/evm/accounts/export/by-name/{name}: post: x-audience: public - summary: Revoke a spend permission - description: Revokes an existing spend permission. - operationId: revokeSpendPermission + summary: Export EVM account by name + description: Export an existing EVM account's private key by its name. It is important to store the private key in a secure place after it's exported. + operationId: exportEvmAccountByName tags: - - EVM Smart Accounts + - EVM Accounts security: - apiKeyAuth: [] + x-required-api-auth-scopes: + - accounts#export parameters: - $ref: '#/components/parameters/XWalletAuth' - $ref: '#/components/parameters/IdempotencyKey' - - name: address - description: The address of the Smart account this spend permission is valid for. + - name: name + description: The name of the EVM account. in: path required: true schema: type: string - pattern: ^0x[0-9a-fA-F]{40}$ - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + example: my-account requestBody: - required: true content: application/json: schema: - $ref: '#/components/schemas/RevokeSpendPermissionRequest' + type: object + properties: + exportEncryptionKey: + type: string + description: The base64-encoded, public part of the RSA key in DER format used to encrypt the account private key. + example: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= + required: + - exportEncryptionKey responses: '200': - description: Successfully revoked spend permission. + description: Successfully exported EVM account. content: application/json: schema: - $ref: '#/components/schemas/EvmUserOperation' + type: object + properties: + encryptedPrivateKey: + type: string + description: The base64-encoded, encrypted private key of the EVM account which is a 32 byte raw private key. The private key is encrypted in transport using the exportEncryptionKey in the request. + example: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= + required: + - encryptedPrivateKey '400': description: Invalid request. content: @@ -5700,7 +6294,20 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: Invalid request. Please check the request body and parameters. + errorMessage: 'error: parameter "name" must be a string.' + '401': + description: Unauthorized. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + unauthorized: + value: + errorType: unauthorized + errorMessage: Wallet authentication error. + '402': + $ref: '#/components/responses/PaymentMethodRequiredError' '404': description: Not found. content: @@ -5711,104 +6318,40 @@ paths: not_found: value: errorType: not_found - errorMessage: Smart account not found. + errorMessage: EVM account with the given name not found. + '422': + $ref: '#/components/responses/IdempotencyError' '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/swaps/quote: + /v2/evm/smart-accounts/{address}: get: - x-audience: public - summary: Get a price estimate for a swap - description: Get a price estimate for a swap between two tokens on an EVM network. - operationId: getEvmSwapPrice + summary: Get Smart Account by address + description: Gets a Smart Account by its address. + operationId: getEvmSmartAccount tags: - - EVM Swaps + - EVM Smart Accounts security: - apiKeyAuth: [] parameters: - - in: query - name: network + - name: address + description: The 0x-prefixed address of the Smart Account. + in: path required: true schema: - $ref: '#/components/schemas/EvmSwapsNetwork' - - in: query - name: toToken - required: true - schema: - $ref: '#/components/schemas/toToken' - - in: query - name: fromToken - required: true - schema: - $ref: '#/components/schemas/fromToken' - - in: query - name: fromAmount - required: true - schema: - $ref: '#/components/schemas/fromAmount' - - in: query - name: taker - required: true - schema: - $ref: '#/components/schemas/taker' - - in: query - name: signerAddress - required: false - schema: - $ref: '#/components/schemas/signerAddress' - - in: query - name: gasPrice - required: false - schema: - $ref: '#/components/schemas/gasPrice' - - in: query - name: slippageBps - required: false - schema: - $ref: '#/components/schemas/slippageBps' + type: string + pattern: ^0x[0-9a-fA-F]{40}$ + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' responses: '200': - description: A price estimate for the swap. + description: Successfully got Smart Account. content: application/json: schema: - $ref: '#/components/schemas/GetSwapPriceResponseWrapper' - examples: - success: - summary: Successful swap price retrieval - value: - blockNumber: '17038723' - toAmount: '1000000000000000000' - toToken: '0x7F5c764cBc14f9669B88837ca1490cCa17c31607' - fees: - gasFee: - amount: '1000000000000000000' - token: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE' - protocolFee: - amount: '1000000000000000000' - token: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE' - issues: - allowance: - currentAllowance: '1000000000' - spender: '0x000000000022D473030F116dDEE9F6B43aC78BA3' - balance: - token: '0x6B175474E89094C44Da98b954EedeAC495271d0F' - currentBalance: '1000000000000000000' - requiredBalance: '1000000000000000000' - simulationIncomplete: false - liquidityAvailable: true - minToAmount: '900000000000000000' - fromAmount: '1000000000000000000' - fromToken: '0x6B175474E89094C44Da98b954EedeAC495271d0F' - gas: '100000' - gasPrice: '1000000000' - unavailable: - summary: Swap with unavailable liquidity - value: - liquidityAvailable: false + $ref: '#/components/schemas/EvmSmartAccount' '400': description: Invalid request. content: @@ -5819,169 +6362,63 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: Invalid request. Please check the request body and parameters. - '403': - description: Taker not permitted to perform swap. + errorMessage: Invalid address provided. + '404': + description: Not found. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - forbidden: + not_found: value: - errorType: forbidden - errorMessage: Taker not permitted to perform swap. + errorType: not_found + errorMessage: Smart Account with the given address not found. '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/swaps: - post: + put: x-audience: public - summary: Create a swap quote - description: Create a swap quote, which includes the payload to sign as well as the transaction data needed to execute the swap. The developer is responsible for signing the payload and submitting the transaction to the network in order to execute the swap. - operationId: createEvmSwapQuote + summary: Update EVM Smart Account + description: Updates an existing EVM smart account. Use this to update the smart account's name. + operationId: updateEvmSmartAccount tags: - - EVM Swaps + - EVM Smart Accounts security: - apiKeyAuth: [] parameters: - - $ref: '#/components/parameters/IdempotencyKey' + - name: address + description: The 0x-prefixed address of the EVM smart account. The address does not need to be checksummed. + in: path + required: true + schema: + type: string + pattern: ^0x[0-9a-fA-F]{40}$ + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' requestBody: - required: true content: application/json: schema: type: object properties: - network: - $ref: '#/components/schemas/EvmSwapsNetwork' - toToken: - type: string - pattern: ^0x[a-fA-F0-9]{40}$ - description: The 0x-prefixed contract address of the token to receive. - example: '0x7F5c764cBc14f9669B88837ca1490cCa17c31607' - fromToken: - type: string - pattern: ^0x[a-fA-F0-9]{40}$ - description: The 0x-prefixed contract address of the token to send. - example: '0x6B175474E89094C44Da98b954EedeAC495271d0F' - fromAmount: - type: string - pattern: ^\d+$ - description: The amount of the `fromToken` to send in atomic units of the token. For example, `1000000000000000000` when sending ETH equates to 1 ETH, `1000000` when sending USDC equates to 1 USDC, etc. - example: '1000000000000000000' - taker: - type: string - pattern: ^0x[a-fA-F0-9]{40}$ - description: The 0x-prefixed address that holds the `fromToken` balance and has the `Permit2` allowance set for the swap. - example: '0xAc0974bec39a17e36ba4a6b4d238ff944bacb478' - signerAddress: - type: string - pattern: ^0x[a-fA-F0-9]{40}$ - description: The 0x-prefixed Externally Owned Account (EOA) address that will sign the `Permit2` EIP-712 permit message. This is only needed if `taker` is a smart contract. - example: '0x922f49447d8a07e3bd95bd0d56f35241523fbab8' - gasPrice: + name: type: string - pattern: ^\d+$ - description: The target gas price for the swap transaction, in Wei. For EIP-1559 transactions, this value should be seen as the `maxFeePerGas` value. If not provided, the API will use an estimate based on the current network conditions. - example: '1000000000' - slippageBps: - type: integer - minimum: 0 - maximum: 10000 - description: The maximum acceptable slippage of the `toToken` in basis points. If this parameter is set to 0, no slippage will be tolerated. If not provided, the default slippage tolerance is 100 bps (i.e., 1%). - default: 100 - example: 100 - required: - - network - - toToken - - fromToken - - fromAmount - - taker + description: |- + An optional name for the smart 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 smart accounts in the developer's CDP Project. + example: my-smart-account + pattern: ^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$ responses: - '201': - description: Successfully created swap quote. + '200': + description: Successfully updated EVM smart account. content: application/json: schema: - $ref: '#/components/schemas/CreateSwapQuoteResponseWrapper' - examples: - success: - summary: Successful swap quote creation - value: - blockNumber: '17038723' - toAmount: '1000000000000000000' - toToken: '0x7F5c764cBc14f9669B88837ca1490cCa17c31607' - fees: - gasFee: - amount: '1000000000000000000' - token: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE' - protocolFee: - amount: '1000000000000000000' - token: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE' - issues: - allowance: - currentAllowance: '1000000000' - spender: '0x000000000022D473030F116dDEE9F6B43aC78BA3' - balance: - token: '0x6B175474E89094C44Da98b954EedeAC495271d0F' - currentBalance: '1000000000000000000' - requiredBalance: '1000000000000000000' - simulationIncomplete: false - liquidityAvailable: true - minToAmount: '900000000000000000' - fromAmount: '1000000000000000000' - fromToken: '0x6B175474E89094C44Da98b954EedeAC495271d0F' - permit2: - hash: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' - eip712: - domain: - name: Permit2 - chainId: 1 - verifyingContract: '0x000000000022D473030F116dDEE9F6B43aC78BA3' - types: - EIP712Domain: - - name: name - type: string - - name: chainId - type: uint256 - - name: verifyingContract - type: address - PermitTransferFrom: - - name: permitted - type: TokenPermissions - - name: spender - type: address - - name: nonce - type: uint256 - - name: deadline - type: uint256 - TokenPermissions: - - name: token - type: address - - name: amount - type: uint256 - primaryType: PermitTransferFrom - message: - permitted: - token: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48' - amount: '1000000' - spender: '0xFfFfFfFFfFFfFFfFFfFFFFFffFFFffffFfFFFfFf' - nonce: '123456' - deadline: '1717123200' - transaction: - to: '0x000000000022D473030F116dDEE9F6B43aC78BA3' - data: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' - gas: '100000' - gasPrice: '1000000000' - value: '1000000000000000000' - unavailable: - summary: Swap with unavailable liquidity - value: - liquidityAvailable: false + $ref: '#/components/schemas/EvmSmartAccount' '400': description: Invalid request. content: @@ -5992,88 +6429,79 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: Invalid request. Please check the request body and parameters. - '403': - description: Taker not permitted to perform swap. + errorMessage: 'request body has an error: doesn''t match schema: Error at "/name": string doesn''t match the regular expression "^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$".' + '404': + description: EVM account not found. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - forbidden: + not_found: value: - errorType: forbidden - errorMessage: Taker not permitted to perform swap. + errorType: not_found + errorMessage: EVM smart account with the given address not found. + '409': + $ref: '#/components/responses/AlreadyExistsError' + '422': + $ref: '#/components/responses/IdempotencyError' '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/token-balances/{network}/{address}: - get: - x-audience: public - summary: List EVM token balances - description: |- - Lists the token balances of an EVM address on a given network. The balances include ERC-20 tokens and the native gas token (usually ETH). The response is paginated, and by default, returns 20 balances per page. - **Note:** This endpoint is still under development and does not yet provide strong freshness guarantees. Specifically, balances of new tokens can, on occasion, take up to ~30 seconds to appear, while balances of tokens already belonging to an address will generally be close to chain tip. Freshness of new token balances will improve over the coming weeks. - operationId: listEvmTokenBalances + /v2/evm/smart-accounts/{address}/user-operations: + post: + summary: Prepare user operation + description: Prepares a new user operation on a Smart Account for a specific network. + operationId: prepareUserOperation tags: - - EVM Token Balances + - EVM Smart Accounts security: - apiKeyAuth: [] parameters: - name: address - description: The 0x-prefixed EVM address to get balances for. The address does not need to be checksummed. + description: The address of the Smart Account to create the user operation on. in: path required: true schema: type: string pattern: ^0x[0-9a-fA-F]{40}$ example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - - name: network - description: The human-readable network name to get the balances for. - in: path - required: true - schema: - $ref: '#/components/schemas/ListEvmTokenBalancesNetwork' - example: base - - $ref: '#/components/parameters/PageSize' - - $ref: '#/components/parameters/PageToken' + requestBody: + content: + application/json: + schema: + type: object + properties: + network: + $ref: '#/components/schemas/EvmUserOperationNetwork' + calls: + type: array + description: The list of calls to make from the Smart Account. + items: + $ref: '#/components/schemas/EvmCall' + paymasterUrl: + allOf: + - $ref: '#/components/schemas/Url' + description: The URL of the paymaster to use for the user operation. + example: https://api.developer.coinbase.com/rpc/v1/base/ + dataSuffix: + type: string + pattern: ^0x[0-9a-fA-F]+$ + description: The EIP-8021 data suffix (hex-encoded) that enables transaction attribution for the user operation. + example: '0xdddddddd62617365617070070080218021802180218021802180218021' + required: + - network + - calls responses: - '200': - description: Successfully listed token balances. + '201': + description: The prepared user operation. content: application/json: schema: - allOf: - - type: object - required: - - balances - properties: - balances: - type: array - items: - $ref: '#/components/schemas/TokenBalance' - description: The list of EVM token balances. - example: - - amount: - amount: '1250000000000000000' - decimals: 18 - token: - network: base - symbol: ETH - name: ether - contractAddress: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE' - - amount: - amount: '123456' - decimals: 6 - token: - network: base - symbol: USDC - name: USD Coin - contractAddress: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' - - $ref: '#/components/schemas/ListResponse' + $ref: '#/components/schemas/EvmUserOperation' '400': description: Invalid request. content: @@ -6084,7 +6512,18 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: string doesn't match the regular expression "^0x[0-9a-fA-F]{40}$" + errorMessage: Field "network" is required. + '403': + description: Access to resource forbidden. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + forbidden: + value: + errorType: forbidden + errorMessage: Unable to sign transaction for this address. '404': description: Not found. content: @@ -6095,37 +6534,34 @@ paths: not_found: value: errorType: not_found - errorMessage: Address not found, or no balances found for the given address on this chain. + errorMessage: EVM smart account with the given address not found. '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/evm/faucet: + /v2/evm/smart-accounts/{address}/user-operations/prepare-and-send: post: x-audience: public - summary: Request funds on EVM test networks - description: | - Request funds from the CDP Faucet on supported EVM test networks. - - Faucets are available for ETH, USDC, EURC, and cbBTC on Base Sepolia and Ethereum Sepolia, and for ETH only on Ethereum Hoodi. - - To prevent abuse, we enforce rate limits within a rolling 24-hour window to control the amount of funds that can be requested. - These limits are applied at both the CDP User level and the blockchain address level. - A single blockchain address cannot exceed the specified limits, even if multiple users submit requests to the same address. - - | Token | Amount per Faucet Request |Rolling 24-hour window Rate Limits| - |:-----:|:-------------------------:|:--------------------------------:| - | ETH | 0.0001 ETH | 0.1 ETH | - | USDC | 1 USDC | 10 USDC | - | EURC | 1 EURC | 10 EURC | - | cbBTC | 0.0001 cbBTC | 0.001 cbBTC | - operationId: requestEvmFaucet + summary: Prepare and send user operation + description: Prepares, signs, and sends a user operation for an EVM Smart Account. This API can be used only if the owner on Smart Account is a CDP EVM Account. + operationId: prepareAndSendUserOperation tags: - - Faucets + - EVM Smart Accounts security: - apiKeyAuth: [] + parameters: + - $ref: '#/components/parameters/IdempotencyKey' + - $ref: '#/components/parameters/XWalletAuth' + - name: address + description: The address of the EVM Smart Account to execute the user operation from. + in: path + required: true + schema: + type: string + pattern: ^0x[0-9a-fA-F]{40}$ + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' requestBody: content: application/json: @@ -6133,47 +6569,27 @@ paths: type: object properties: network: - type: string - description: The network to request funds from. - enum: - - base-sepolia - - ethereum-sepolia - - ethereum-hoodi - example: base-sepolia - address: - type: string - description: The address to request funds to, which is a 0x-prefixed hexadecimal string. - pattern: ^0x[0-9a-fA-F]{40}$ - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - token: - type: string - description: The token to request funds for. - enum: - - eth - - usdc - - eurc - - cbbtc - example: eth + $ref: '#/components/schemas/EvmUserOperationNetwork' + calls: + type: array + description: The list of calls to make from the Smart Account. + items: + $ref: '#/components/schemas/EvmCall' + paymasterUrl: + allOf: + - $ref: '#/components/schemas/Url' + description: The URL of the paymaster to use for the user operation. + example: https://api.developer.coinbase.com/rpc/v1/base/ required: - network - - address - - token + - calls responses: '200': - description: Successfully requested funds. + description: The user operation was successfully prepared, signed, and sent. content: application/json: schema: - type: object - properties: - transactionHash: - type: string - description: |- - The hash of the transaction that requested the funds. - **Note:** In rare cases, when gas conditions are unusually high, the transaction may not confirm, and the system may issue a replacement transaction to complete the faucet request. In these rare cases, the `transactionHash` will be out of sync with the actual faucet transaction that was confirmed onchain. - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - required: - - transactionHash + $ref: '#/components/schemas/EvmUserOperation' '400': description: Invalid request. content: @@ -6184,7 +6600,15 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: 'request body has an error: doesn''t match schema: Error at "address": string doesn''t match the regular expression "^0x[0-9a-fA-F]{40}$"' + errorMessage: Field "network" is required. + invalid_signature: + value: + errorType: invalid_signature + errorMessage: Failed to sign user operation. + '401': + $ref: '#/components/responses/UnauthorizedError' + '402': + $ref: '#/components/responses/PaymentMethodRequiredError' '403': description: Access to resource forbidden. content: @@ -6195,7 +6619,18 @@ paths: forbidden: value: errorType: forbidden - errorMessage: Unable to request faucet funds for this address. + errorMessage: Unable to sign transaction for this address. + '404': + description: Not found. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + not_found: + value: + errorType: not_found + errorMessage: End user Smart Account with the given address not found. '429': description: Rate limit exceeded. content: @@ -6203,113 +6638,49 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - faucet_limit_exceeded: + rate_limit_exceeded: value: - errorType: faucet_limit_exceeded - errorMessage: Faucet limit reached for this address. Please try again later. + errorType: rate_limit_exceeded + errorMessage: Max concurrent user operations reached. '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/policy-engine/policies: + /v2/evm/smart-accounts/{address}/user-operations/{userOpHash}: get: - x-audience: public - summary: List policies - description: |- - Lists the policies belonging to the developer's CDP Project. Use the `scope` parameter to filter the policies by scope. - The response is paginated, and by default, returns 20 policies per page. - operationId: listPolicies + summary: Get user operation + description: Gets a user operation by its hash. + operationId: getUserOperation tags: - - Policy Engine + - EVM Smart Accounts security: - apiKeyAuth: [] parameters: - - $ref: '#/components/parameters/PageSize' - - $ref: '#/components/parameters/PageToken' - - name: scope - description: The scope of the policies to return. If `project`, the response will include exactly one policy, which is the project-level policy. If `account`, the response will include all account-level policies for the developer's CDP Project. - in: query - required: false + - name: address + description: The address of the Smart Account the user operation belongs to. + in: path + required: true schema: type: string - enum: - - project - - account - example: project + pattern: ^0x[0-9a-fA-F]{40}$ + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + - name: userOpHash + description: The hash of the user operation to fetch. + in: path + required: true + schema: + type: string + pattern: ^0x[0-9a-fA-F]{64}$ + example: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' responses: '200': - description: Successfully listed policies. + description: Successfully retrieved the user operation. content: application/json: schema: - allOf: - - type: object - properties: - policies: - type: array - items: - $ref: '#/components/schemas/Policy' - description: The list of policies. - required: - - policies - - $ref: '#/components/schemas/ListResponse' - '500': - $ref: '#/components/responses/InternalServerError' - '502': - $ref: '#/components/responses/BadGatewayError' - '503': - $ref: '#/components/responses/ServiceUnavailableError' - post: - x-audience: public - summary: Create a policy - description: Create a policy that can be used to govern the behavior of accounts. - operationId: createPolicy - tags: - - Policy Engine - security: - - apiKeyAuth: [] - x-required-api-auth-scopes: - - policies#manage - parameters: - - $ref: '#/components/parameters/IdempotencyKey' - requestBody: - required: true - content: - application/json: - schema: - type: object - properties: - scope: - type: string - description: The scope of the policy. - enum: - - project - - account - example: project - description: - type: string - description: |- - An optional human-readable description for the policy. - Policy descriptions can consist of alphanumeric characters, spaces, commas, and periods, and be 50 characters or less. - pattern: ^[A-Za-z0-9 ,.]{1,50}$ - example: Default policy - rules: - type: array - description: A list of rules that comprise the policy. There is a limit of 10 rules per policy. - items: - $ref: '#/components/schemas/Rule' - required: - - scope - - rules - responses: - '201': - description: Successfully created policy. - content: - application/json: - schema: - $ref: '#/components/schemas/Policy' + $ref: '#/components/schemas/EvmUserOperation' '400': description: Invalid request. content: @@ -6320,45 +6691,9 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: Policy name must be between 1 and 50 characters - '409': - $ref: '#/components/responses/AlreadyExistsError' - '422': - $ref: '#/components/responses/IdempotencyError' - '500': - $ref: '#/components/responses/InternalServerError' - '502': - $ref: '#/components/responses/BadGatewayError' - '503': - $ref: '#/components/responses/ServiceUnavailableError' - /v2/policy-engine/policies/{policyId}: - get: - x-audience: public - summary: Get a policy by ID - description: Get a policy by its ID. - operationId: getPolicyById - tags: - - Policy Engine - security: - - apiKeyAuth: [] - parameters: - - name: policyId - description: The ID of the policy to get. - in: path - required: true - schema: - type: string - pattern: ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ - example: 123e4567-e89b-12d3-a456-426614174000 - responses: - '200': - description: Successfully retrieved policy. - content: - application/json: - schema: - $ref: '#/components/schemas/Policy' + errorMessage: Invalid request. Please check the request body and parameters. '404': - description: Policy not found. + description: Not found. content: application/json: schema: @@ -6367,50 +6702,88 @@ paths: not_found: value: errorType: not_found - errorMessage: Policy not found + errorMessage: User operation not found. '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - delete: - x-audience: public - summary: Delete a policy - description: Delete a policy by its ID. This will have the effect of removing the policy from all accounts that are currently using it. - operationId: deletePolicy + /v2/evm/smart-accounts/{address}/user-operations/{userOpHash}/send: + post: + summary: Send user operation + description: |- + Sends a user operation with a signature. + The payload to sign must be the `userOpHash` field of the user operation. This hash should be signed directly (not using `personal_sign` or EIP-191 message hashing). + The signature must be 65 bytes in length, consisting of: - 32 bytes for the `r` value - 32 bytes for the `s` value - 1 byte for the `v` value (must be 27 or 28) + If using the CDP Paymaster, the user operation must be signed and sent within 2 minutes of being prepared. + operationId: sendUserOperation tags: - - Policy Engine + - EVM Smart Accounts security: - apiKeyAuth: [] - x-required-api-auth-scopes: - - policies#manage parameters: - - $ref: '#/components/parameters/IdempotencyKey' - - name: policyId - description: The ID of the policy to delete. + - name: address + description: The address of the Smart Account to send the user operation from. in: path required: true schema: type: string - pattern: ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ - example: 123e4567-e89b-12d3-a456-426614174000 + pattern: ^0x[0-9a-fA-F]{40}$ + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + - name: userOpHash + description: The hash of the user operation to send. + in: path + required: true + schema: + type: string + pattern: ^0x[0-9a-fA-F]{64}$ + example: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' + requestBody: + content: + application/json: + schema: + type: object + properties: + signature: + type: string + description: The hex-encoded signature of the user operation. This should be a 65-byte signature consisting of the `r`, `s`, and `v` values of the ECDSA signature. Note that the `v` value should conform to the `personal_sign` standard, which means it should be 27 or 28. + example: '0x1b0c9cf8cd4554c6c6d9e7311e88f1be075d7f25b418a044f4bf2c0a42a93e212ad0a8b54de9e0b5f7e3812de3f2c6cc79aa8c3e1c02e7ad14b4a8f42012c2c01b' + required: + - signature responses: - '204': - description: Successfully deleted policy. + '200': + description: The sent user operation. + content: + application/json: + schema: + $ref: '#/components/schemas/EvmUserOperation' '400': - description: Unable to delete policy. + description: Invalid request. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - not_found: + invalid_signature: value: - errorType: policy_in_use - errorMessage: Policy in use + errorType: invalid_signature + errorMessage: Invalid signature. + '402': + $ref: '#/components/responses/PaymentMethodRequiredError' + '403': + description: Access to resource forbidden. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + forbidden: + value: + errorType: forbidden + errorMessage: Unable to sign transaction for this address. '404': - description: Policy not found. + description: Not found. content: application/json: schema: @@ -6419,66 +6792,58 @@ paths: not_found: value: errorType: not_found - errorMessage: Policy not found - '409': - $ref: '#/components/responses/AlreadyExistsError' - '422': - $ref: '#/components/responses/IdempotencyError' + errorMessage: User operation not found. + '429': + description: Rate limit exceeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + rate_limit_exceeded: + value: + errorType: rate_limit_exceeded + errorMessage: Max concurrent user operations reached. '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - put: + /v2/evm/smart-accounts/{address}/spend-permissions: + post: x-audience: public - summary: Update a policy - description: Updates a policy by its ID. This will have the effect of applying the updated policy to all accounts that are currently using it. - operationId: updatePolicy + summary: Create spend permission + description: Creates a spend permission for the given smart account address. + operationId: createSpendPermission tags: - - Policy Engine + - EVM Smart Accounts security: - apiKeyAuth: [] - x-required-api-auth-scopes: - - policies#manage parameters: + - $ref: '#/components/parameters/XWalletAuth' - $ref: '#/components/parameters/IdempotencyKey' - - name: policyId - description: The ID of the policy to update. + - name: address + description: The address of the Smart Account to create the spend permission for. in: path required: true schema: type: string - pattern: ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ - example: 123e4567-e89b-12d3-a456-426614174000 + pattern: ^0x[0-9a-fA-F]{40}$ + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' requestBody: required: true content: application/json: schema: - type: object - properties: - description: - type: string - description: |- - An optional human-readable description for the policy. - Policy descriptions can consist of alphanumeric characters, spaces, commas, and periods, and be 50 characters or less. - pattern: ^[A-Za-z0-9 ,.]{1,50}$ - example: Default policy - rules: - type: array - description: A list of rules that comprise the policy. There is a limit of 10 rules per policy. - items: - $ref: '#/components/schemas/Rule' - required: - - rules + $ref: '#/components/schemas/CreateSpendPermissionRequest' responses: '200': - description: Successfully updated policy. + description: Successfully created spend permission. content: application/json: schema: - $ref: '#/components/schemas/Policy' + $ref: '#/components/schemas/EvmUserOperation' '400': description: Invalid request. content: @@ -6489,9 +6854,9 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: Policy name must be between 1 and 50 characters + errorMessage: Invalid request. Please check the request body and parameters. '404': - description: Policy not found. + description: Not found. content: application/json: schema: @@ -6500,166 +6865,64 @@ paths: not_found: value: errorType: not_found - errorMessage: Policy not found - '409': - $ref: '#/components/responses/AlreadyExistsError' - '422': - $ref: '#/components/responses/IdempotencyError' + errorMessage: Smart account not found. '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/solana/accounts: + /v2/evm/smart-accounts/{address}/spend-permissions/list: get: x-audience: public - summary: List Solana accounts or get account by name - description: |- - Lists the Solana accounts belonging to the developer. - The response is paginated, and by default, returns 20 accounts per page. - - If a name is provided, the response will contain only the account with that name. - operationId: listSolanaAccounts + summary: List spend permissions + description: Lists spend permission for the given smart account address. + operationId: listSpendPermissions tags: - - Solana Accounts - security: - - apiKeyAuth: [] - parameters: - - $ref: '#/components/parameters/PageSize' - - $ref: '#/components/parameters/PageToken' - responses: - '200': - description: Successfully listed Solana accounts. - content: - application/json: - schema: - allOf: - - type: object - properties: - accounts: - type: array - items: - $ref: '#/components/schemas/SolanaAccount' - description: The list of Solana accounts. - required: - - accounts - - $ref: '#/components/schemas/ListResponse' - '500': - $ref: '#/components/responses/InternalServerError' - '502': - $ref: '#/components/responses/BadGatewayError' - '503': - $ref: '#/components/responses/ServiceUnavailableError' - post: - x-audience: public - summary: Create a Solana account - description: Creates a new Solana account. - operationId: createSolanaAccount - tags: - - Solana Accounts - security: - - apiKeyAuth: [] - parameters: - - $ref: '#/components/parameters/XWalletAuth' - - $ref: '#/components/parameters/IdempotencyKey' - requestBody: - required: false - content: - application/json: - schema: - type: object - properties: - name: - type: string - description: |- - 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 Solana accounts in the developer's CDP Project. - example: my-wallet - pattern: ^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$ - accountPolicy: - type: string - x-audience: public - description: The ID of the account-level policy to apply to the account. - pattern: ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ - example: 123e4567-e89b-12d3-a456-426614174000 - responses: - '201': - description: Successfully created Solana account. - content: - application/json: - schema: - $ref: '#/components/schemas/SolanaAccount' - '400': - description: Invalid request. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - invalid_request: - value: - errorType: invalid_request - errorMessage: Project has no secret. Please register a secret with the project. - '401': - description: Unauthorized. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - unauthorized: - value: - errorType: unauthorized - errorMessage: Wallet authentication error. - '402': - $ref: '#/components/responses/PaymentMethodRequiredError' - '409': - description: Resource already exists. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - already_exists: - value: - errorType: already_exists - errorMessage: Solana account with the given name already exists. - '422': - $ref: '#/components/responses/IdempotencyError' - '500': - $ref: '#/components/responses/InternalServerError' - '502': - $ref: '#/components/responses/BadGatewayError' - '503': - $ref: '#/components/responses/ServiceUnavailableError' - /v2/solana/accounts/{address}: - get: - x-audience: public - summary: Get a Solana account by address - description: Gets a Solana account by its address. - operationId: getSolanaAccount - tags: - - Solana Accounts + - EVM Smart Accounts security: - apiKeyAuth: [] parameters: - name: address - description: The base58 encoded address of the Solana account. + description: The address of the Smart account to list spend permissions for. in: path required: true schema: type: string - pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ - example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + pattern: ^0x[0-9a-fA-F]{40}$ + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + - name: pageSize + description: The number of spend permissions to return per page. + in: query + required: false + schema: + type: integer + default: 20 + example: 10 + - name: pageToken + description: The token for the next page of spend permissions. Will be empty if there are no more spend permissions to fetch. + in: query + required: false + schema: + type: string + example: eyJsYXN0X2lkIjogImFiYzEyMyIsICJ0aW1lc3RhbXAiOiAxNzA3ODIzNzAxfQ== responses: '200': - description: Successfully got Solana account. + description: Successfully listed spend permissions. content: application/json: schema: - $ref: '#/components/schemas/SolanaAccount' + allOf: + - type: object + required: + - spendPermissions + properties: + spendPermissions: + type: array + description: The spend permissions for the smart account. + items: + $ref: '#/components/schemas/SpendPermissionResponseObject' + - $ref: '#/components/schemas/ListResponse' '400': description: Invalid request. content: @@ -6670,7 +6933,7 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: 'request body has an error: doesn''t match schema: Error at "address": string doesn''t match the regular expression "^[1-9A-HJ-NP-Za-km-z]{32,44}$"' + errorMessage: Invalid request. Please check the request body and parameters. '404': description: Not found. content: @@ -6681,58 +6944,47 @@ paths: not_found: value: errorType: not_found - errorMessage: Solana account with the given address not found. + errorMessage: Smart account not found. '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - put: + /v2/evm/smart-accounts/{address}/spend-permissions/revoke: + post: x-audience: public - summary: Update a Solana account - description: Updates an existing Solana account. Use this to update the account's name or account-level policy. - operationId: updateSolanaAccount + summary: Revoke spend permission + description: Revokes an existing spend permission. + operationId: revokeSpendPermission tags: - - Solana Accounts + - EVM Smart Accounts security: - apiKeyAuth: [] parameters: + - $ref: '#/components/parameters/XWalletAuth' - $ref: '#/components/parameters/IdempotencyKey' - name: address - description: The base58 encoded address of the Solana account. + description: The address of the Smart account this spend permission is valid for. in: path required: true schema: type: string - pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ - example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + pattern: ^0x[0-9a-fA-F]{40}$ + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' requestBody: + required: true content: application/json: schema: - type: object - properties: - name: - type: string - description: |- - 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 Solana accounts in the developer's CDP Project. - example: my-wallet - pattern: ^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$ - accountPolicy: - type: string - x-audience: public - description: The ID of the account-level policy to apply to the account, or an empty string to unset attached policy. - pattern: (^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$)|(^$) - example: 123e4567-e89b-12d3-a456-426614174000 + $ref: '#/components/schemas/RevokeSpendPermissionRequest' responses: '200': - description: Successfully updated Solana account. + description: Successfully revoked spend permission. content: application/json: schema: - $ref: '#/components/schemas/SolanaAccount' + $ref: '#/components/schemas/EvmUserOperation' '400': description: Invalid request. content: @@ -6743,9 +6995,9 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: 'request body has an error: doesn''t match schema: Error at "name": string doesn''t match the regular expression "^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$"' + errorMessage: Invalid request. Please check the request body and parameters. '404': - description: Solana account not found. + description: Not found. content: application/json: schema: @@ -6754,110 +7006,277 @@ paths: not_found: value: errorType: not_found - errorMessage: Solana account with the given address not found. - '409': - $ref: '#/components/responses/AlreadyExistsError' - '422': - $ref: '#/components/responses/IdempotencyError' + errorMessage: Smart account not found. '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/solana/accounts/by-name/{name}: + /v2/evm/swaps/quote: get: x-audience: public - summary: Get a Solana account by name - description: Gets a Solana account by its name. - operationId: getSolanaAccountByName + summary: Get swap price estimate + description: Get a price estimate for a swap between two tokens on an EVM network. + operationId: getEvmSwapPrice tags: - - Solana Accounts + - EVM Swaps security: - apiKeyAuth: [] parameters: - - name: name - description: The name of the Solana account. - in: path + - in: query + name: network required: true schema: - type: string - example: my-account + $ref: '#/components/schemas/EvmSwapsNetwork' + - in: query + name: toToken + required: true + schema: + $ref: '#/components/schemas/toToken' + - in: query + name: fromToken + required: true + schema: + $ref: '#/components/schemas/fromToken' + - in: query + name: fromAmount + required: true + schema: + $ref: '#/components/schemas/fromAmount' + - in: query + name: taker + required: true + schema: + $ref: '#/components/schemas/taker' + - in: query + name: signerAddress + required: false + schema: + $ref: '#/components/schemas/signerAddress' + - in: query + name: gasPrice + required: false + schema: + $ref: '#/components/schemas/gasPrice' + - in: query + name: slippageBps + required: false + schema: + $ref: '#/components/schemas/slippageBps' responses: '200': - description: Successfully got Solana account. - content: - application/json: - schema: - $ref: '#/components/schemas/SolanaAccount' - '400': - description: Invalid request. + description: A price estimate for the swap. content: application/json: schema: - $ref: '#/components/schemas/Error' + $ref: '#/components/schemas/GetSwapPriceResponseWrapper' examples: - invalid_request: + success: + summary: Successful swap price retrieval value: - errorType: invalid_request - errorMessage: 'error: parameter "name" must be a string' - '404': - description: Not found. - content: - application/json: - schema: + blockNumber: '17038723' + toAmount: '1000000000000000000' + toToken: '0x7F5c764cBc14f9669B88837ca1490cCa17c31607' + fees: + gasFee: + amount: '1000000000000000000' + token: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE' + protocolFee: + amount: '1000000000000000000' + token: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE' + issues: + allowance: + currentAllowance: '1000000000' + spender: '0x000000000022D473030F116dDEE9F6B43aC78BA3' + balance: + token: '0x6B175474E89094C44Da98b954EedeAC495271d0F' + currentBalance: '1000000000000000000' + requiredBalance: '1000000000000000000' + simulationIncomplete: false + liquidityAvailable: true + minToAmount: '900000000000000000' + fromAmount: '1000000000000000000' + fromToken: '0x6B175474E89094C44Da98b954EedeAC495271d0F' + gas: '100000' + gasPrice: '1000000000' + unavailable: + summary: Swap with unavailable liquidity + value: + liquidityAvailable: false + '400': + description: Invalid request. + content: + application/json: + schema: $ref: '#/components/schemas/Error' examples: - not_found: + invalid_request: value: - errorType: not_found - errorMessage: Solana account with the given name not found. + errorType: invalid_request + errorMessage: Invalid request. Please check the request body and parameters. + '403': + description: Taker not permitted to perform swap. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + forbidden: + value: + errorType: forbidden + errorMessage: Taker not permitted to perform swap. '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/solana/accounts/import: + /v2/evm/swaps: post: x-audience: public - summary: Import a Solana account - description: Import an existing Solana account into the developer's CDP Project. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. - operationId: importSolanaAccount + summary: Create swap quote + description: Create a swap quote, which includes the payload to sign as well as the transaction data needed to execute the swap. The developer is responsible for signing the payload and submitting the transaction to the network in order to execute the swap. + operationId: createEvmSwapQuote tags: - - Solana Accounts + - EVM Swaps security: - apiKeyAuth: [] parameters: - - $ref: '#/components/parameters/XWalletAuth' - $ref: '#/components/parameters/IdempotencyKey' requestBody: + required: true content: application/json: schema: type: object properties: - encryptedPrivateKey: + network: + $ref: '#/components/schemas/EvmSwapsNetwork' + toToken: type: string - description: The base64-encoded, encrypted 32-byte private key of the Solana account. The private key must be encrypted using the CDP SDK's encryption scheme. - example: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= - name: + pattern: ^0x[a-fA-F0-9]{40}$ + description: The 0x-prefixed contract address of the token to receive. + example: '0x7F5c764cBc14f9669B88837ca1490cCa17c31607' + fromToken: type: string - description: |- - 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. - example: my-solana-wallet - pattern: ^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$ + pattern: ^0x[a-fA-F0-9]{40}$ + description: The 0x-prefixed contract address of the token to send. + example: '0x6B175474E89094C44Da98b954EedeAC495271d0F' + fromAmount: + type: string + pattern: ^\d+$ + description: The amount of the `fromToken` to send in atomic units of the token. For example, `1000000000000000000` when sending ETH equates to 1 ETH, `1000000` when sending USDC equates to 1 USDC, etc. + example: '1000000000000000000' + taker: + type: string + pattern: ^0x[a-fA-F0-9]{40}$ + description: The 0x-prefixed address that holds the `fromToken` balance and has the `Permit2` allowance set for the swap. + example: '0xAc0974bec39a17e36ba4a6b4d238ff944bacb478' + signerAddress: + type: string + pattern: ^0x[a-fA-F0-9]{40}$ + description: The 0x-prefixed Externally Owned Account (EOA) address that will sign the `Permit2` EIP-712 permit message. This is only needed if `taker` is a smart contract. + example: '0x922f49447d8a07e3bd95bd0d56f35241523fbab8' + gasPrice: + type: string + pattern: ^\d+$ + description: The target gas price for the swap transaction, in Wei. For EIP-1559 transactions, this value should be seen as the `maxFeePerGas` value. If not provided, the API will use an estimate based on the current network conditions. + example: '1000000000' + slippageBps: + type: integer + minimum: 0 + maximum: 10000 + description: The maximum acceptable slippage of the `toToken` in basis points. If this parameter is set to 0, no slippage will be tolerated. If not provided, the default slippage tolerance is 100 bps (i.e., 1%). + default: 100 + example: 100 required: - - encryptedPrivateKey + - network + - toToken + - fromToken + - fromAmount + - taker responses: '201': - description: Successfully imported Solana account. + description: Successfully created swap quote. content: application/json: schema: - $ref: '#/components/schemas/SolanaAccount' + $ref: '#/components/schemas/CreateSwapQuoteResponseWrapper' + examples: + success: + summary: Successful swap quote creation + value: + blockNumber: '17038723' + toAmount: '1000000000000000000' + toToken: '0x7F5c764cBc14f9669B88837ca1490cCa17c31607' + fees: + gasFee: + amount: '1000000000000000000' + token: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE' + protocolFee: + amount: '1000000000000000000' + token: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE' + issues: + allowance: + currentAllowance: '1000000000' + spender: '0x000000000022D473030F116dDEE9F6B43aC78BA3' + balance: + token: '0x6B175474E89094C44Da98b954EedeAC495271d0F' + currentBalance: '1000000000000000000' + requiredBalance: '1000000000000000000' + simulationIncomplete: false + liquidityAvailable: true + minToAmount: '900000000000000000' + fromAmount: '1000000000000000000' + fromToken: '0x6B175474E89094C44Da98b954EedeAC495271d0F' + permit2: + hash: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' + eip712: + domain: + name: Permit2 + chainId: 1 + verifyingContract: '0x000000000022D473030F116dDEE9F6B43aC78BA3' + types: + EIP712Domain: + - name: name + type: string + - name: chainId + type: uint256 + - name: verifyingContract + type: address + PermitTransferFrom: + - name: permitted + type: TokenPermissions + - name: spender + type: address + - name: nonce + type: uint256 + - name: deadline + type: uint256 + TokenPermissions: + - name: token + type: address + - name: amount + type: uint256 + primaryType: PermitTransferFrom + message: + permitted: + token: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48' + amount: '1000000' + spender: '0xFfFfFfFFfFFfFFfFFfFFFFFffFFFffffFfFFFfFf' + nonce: '123456' + deadline: '1717123200' + transaction: + to: '0x000000000022D473030F116dDEE9F6B43aC78BA3' + data: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' + gas: '100000' + gasPrice: '1000000000' + value: '1000000000000000000' + unavailable: + summary: Swap with unavailable liquidity + value: + liquidityAvailable: false '400': description: Invalid request. content: @@ -6868,88 +7287,88 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: The encrypted private key is invalid. - '401': - description: Unauthorized. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - unauthorized: - value: - errorType: unauthorized - errorMessage: Wallet authentication error. - '402': - $ref: '#/components/responses/PaymentMethodRequiredError' - '409': - description: Resource already exists. + errorMessage: Invalid request. Please check the request body and parameters. + '403': + description: Taker not permitted to perform swap. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - already_exists: + forbidden: value: - errorType: already_exists - errorMessage: Solana account with the given address already exists. - '422': - $ref: '#/components/responses/IdempotencyError' + errorType: forbidden + errorMessage: Taker not permitted to perform swap. '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/solana/accounts/{address}/export: - post: + /v2/evm/token-balances/{network}/{address}: + get: x-audience: public - summary: Export an Solana account - description: Export an existing Solana account's private key. It is important to store the private key in a secure place after it's exported. - operationId: exportSolanaAccount + summary: List EVM token balances + description: |- + Lists the token balances of an EVM address on a given network. The balances include ERC-20 tokens and the native gas token (usually ETH). The response is paginated, and by default, returns 20 balances per page. + **Note:** This endpoint is still under development and does not yet provide strong freshness guarantees. Specifically, balances of new tokens can, on occasion, take up to ~30 seconds to appear, while balances of tokens already belonging to an address will generally be close to chain tip. Freshness of new token balances will improve over the coming weeks. + operationId: listEvmTokenBalances tags: - - Solana Accounts + - EVM Token Balances security: - apiKeyAuth: [] - x-required-api-auth-scopes: - - accounts#export parameters: - - $ref: '#/components/parameters/XWalletAuth' - - $ref: '#/components/parameters/IdempotencyKey' - name: address - description: The base58 encoded address of the Solana account. + description: The 0x-prefixed EVM address to get balances for. The address does not need to be checksummed. in: path required: true schema: type: string - pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ - example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT - requestBody: - content: - application/json: - schema: - type: object - properties: - exportEncryptionKey: - type: string - description: The base64-encoded, public part of the RSA key in DER format used to encrypt the account private key. - example: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= - required: - - exportEncryptionKey - responses: - '200': - description: Successfully exported Solana account. - content: + pattern: ^0x[0-9a-fA-F]{40}$ + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + - name: network + description: The human-readable network name to get the balances for. + in: path + required: true + schema: + $ref: '#/components/schemas/ListEvmTokenBalancesNetwork' + example: base + - $ref: '#/components/parameters/PageSize' + - $ref: '#/components/parameters/PageToken' + responses: + '200': + description: Successfully listed token balances. + content: application/json: schema: - type: object - properties: - encryptedPrivateKey: - type: string - description: The base64-encoded, encrypted private key of the Solana account which is a 32 byte raw private key. The private key is encrypted in transport using the exportEncryptionKey in the request. - example: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= - required: - - encryptedPrivateKey + allOf: + - type: object + required: + - balances + properties: + balances: + type: array + items: + $ref: '#/components/schemas/TokenBalance' + description: The list of EVM token balances. + example: + - amount: + amount: '1250000000000000000' + decimals: 18 + token: + network: base + symbol: ETH + name: ether + contractAddress: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE' + - amount: + amount: '123456' + decimals: 6 + token: + network: base + symbol: USDC + name: USD Coin + contractAddress: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' + - $ref: '#/components/schemas/ListResponse' '400': description: Invalid request. content: @@ -6960,20 +7379,7 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: Solana account with the given address not found. - '401': - description: Unauthorized. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - unauthorized: - value: - errorType: unauthorized - errorMessage: Wallet authentication error. - '402': - $ref: '#/components/responses/PaymentMethodRequiredError' + errorMessage: string doesn't match the regular expression "^0x[0-9a-fA-F]{40}$". '404': description: Not found. content: @@ -6984,63 +7390,85 @@ paths: not_found: value: errorType: not_found - errorMessage: Solana account with the given address not found. - '422': - $ref: '#/components/responses/IdempotencyError' + errorMessage: Address not found, or no balances found for the given address on this chain. '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/solana/accounts/export/by-name/{name}: + /v2/evm/faucet: post: x-audience: public - summary: Export a Solana account by name - description: Export an existing Solana account's private key by its name. It is important to store the private key in a secure place after it's exported. - operationId: exportSolanaAccountByName + summary: Request funds on EVM test networks + description: | + Request funds from the CDP Faucet on supported EVM test networks. + + Faucets are available for ETH, USDC, EURC, and cbBTC on Base Sepolia and Ethereum Sepolia, and for ETH only on Ethereum Hoodi. + + To prevent abuse, we enforce rate limits within a rolling 24-hour window to control the amount of funds that can be requested. + These limits are applied at both the CDP User level and the blockchain address level. + A single blockchain address cannot exceed the specified limits, even if multiple users submit requests to the same address. + + | Token | Amount per Faucet Request |Rolling 24-hour window Rate Limits| + |:-----:|:-------------------------:|:--------------------------------:| + | ETH | 0.0001 ETH | 0.1 ETH | + | USDC | 1 USDC | 10 USDC | + | EURC | 1 EURC | 10 EURC | + | cbBTC | 0.0001 cbBTC | 0.001 cbBTC | + operationId: requestEvmFaucet tags: - - Solana Accounts + - Faucets security: - apiKeyAuth: [] - x-required-api-auth-scopes: - - accounts#export - parameters: - - $ref: '#/components/parameters/XWalletAuth' - - $ref: '#/components/parameters/IdempotencyKey' - - name: name - description: The name of the Solana account. - in: path - required: true - schema: - type: string - example: my-account requestBody: content: application/json: schema: type: object properties: - exportEncryptionKey: + network: type: string - description: The base64-encoded, public part of the RSA key in DER format used to encrypt the account private key. - example: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= + description: The network to request funds from. + enum: + - base-sepolia + - ethereum-sepolia + - ethereum-hoodi + example: base-sepolia + address: + type: string + description: The address to request funds to, which is a 0x-prefixed hexadecimal string. + pattern: ^0x[0-9a-fA-F]{40}$ + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + token: + type: string + description: The token to request funds for. + enum: + - eth + - usdc + - eurc + - cbbtc + example: eth required: - - exportEncryptionKey + - network + - address + - token responses: '200': - description: Successfully exported Solana account. + description: Successfully requested funds. content: application/json: schema: type: object properties: - encryptedPrivateKey: + transactionHash: type: string - description: The base64-encoded, encrypted private key of the Solana account which is a 32 byte raw private key. The private key is encrypted in transport using the exportEncryptionKey in the request. - example: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= + description: |- + The hash of the transaction that requested the funds. + **Note:** In rare cases, when gas conditions are unusually high, the transaction may not confirm, and the system may issue a replacement transaction to complete the faucet request. In these rare cases, the `transactionHash` will be out of sync with the actual faucet transaction that was confirmed onchain. + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' required: - - encryptedPrivateKey + - transactionHash '400': description: Invalid request. content: @@ -7051,96 +7479,132 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: 'error: parameter "name" must be a string' - '401': - description: Unauthorized. + errorMessage: 'request body has an error: doesn''t match schema: Error at "address": string doesn''t match the regular expression "^0x[0-9a-fA-F]{40}$".' + '403': + description: Access to resource forbidden. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - unauthorized: + forbidden: value: - errorType: unauthorized - errorMessage: Wallet authentication error. - '402': - $ref: '#/components/responses/PaymentMethodRequiredError' - '404': - description: Not found. + errorType: forbidden + errorMessage: Unable to request faucet funds for this address. + '429': + description: Rate limit exceeded. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - not_found: + faucet_limit_exceeded: value: - errorType: not_found - errorMessage: Solana account with the given name not found. - '422': - $ref: '#/components/responses/IdempotencyError' + errorType: faucet_limit_exceeded + errorMessage: Faucet limit reached for this address. Please try again later. '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/solana/accounts/{address}/sign/transaction: - post: + /v2/policy-engine/policies: + get: x-audience: public - summary: Sign a transaction + summary: List policies description: |- - Signs a transaction with the given Solana account. - The unsigned transaction should be serialized into a byte array and then encoded as base64. - - **Transaction types** - - The following transaction types are supported: - * [Legacy transactions](https://solana-labs.github.io/solana-web3.js/classes/Transaction.html) - * [Versioned transactions](https://solana-labs.github.io/solana-web3.js/classes/VersionedTransaction.html) - - The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. - operationId: signSolanaTransaction + Lists the policies belonging to the developer's CDP Project. Use the `scope` parameter to filter the policies by scope. + The response is paginated, and by default, returns 20 policies per page. + operationId: listPolicies tags: - - Solana Accounts + - Policy Engine security: - apiKeyAuth: [] parameters: - - $ref: '#/components/parameters/XWalletAuth' - - $ref: '#/components/parameters/IdempotencyKey' - - name: address - description: The base58 encoded address of the Solana account. - in: path - required: true + - $ref: '#/components/parameters/PageSize' + - $ref: '#/components/parameters/PageToken' + - name: scope + description: The scope of the policies to return. If `project`, the response will include exactly one policy, which is the project-level policy. If `account`, the response will include all account-level policies for the developer's CDP Project. + in: query + required: false schema: type: string - pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ - example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + enum: + - project + - account + example: project + responses: + '200': + description: Successfully listed policies. + content: + application/json: + schema: + allOf: + - type: object + properties: + policies: + type: array + items: + $ref: '#/components/schemas/Policy' + description: The list of policies. + required: + - policies + - $ref: '#/components/schemas/ListResponse' + '500': + $ref: '#/components/responses/InternalServerError' + '502': + $ref: '#/components/responses/BadGatewayError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + post: + x-audience: public + summary: Create policy + description: Create a policy that can be used to govern the behavior of accounts. + operationId: createPolicy + tags: + - Policy Engine + security: + - apiKeyAuth: [] + x-required-api-auth-scopes: + - policies#manage + parameters: + - $ref: '#/components/parameters/IdempotencyKey' requestBody: + required: true content: application/json: schema: type: object properties: - transaction: + scope: type: string - description: The base64 encoded transaction to sign. - example: AQABAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA= - required: - - transaction - responses: - '200': - description: Successfully signed transaction. - content: - application/json: - schema: - type: object - properties: - signedTransaction: - type: string - description: The base64 encoded signed transaction. - example: AQACAdSOvpk0UJXs/rQRXYKSI9hcR0bkGp24qGv6t0/M1XjcQpHf6AHwLcPjEtKQI7p/U0Zo98lnJ5/PZMfVq/0BAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA= - required: - - signedTransaction + description: The scope of the policy. + enum: + - project + - account + example: project + description: + type: string + description: |- + An optional human-readable description for the policy. + Policy descriptions can consist of alphanumeric characters, spaces, commas, and periods, and be 50 characters or less. + pattern: ^[A-Za-z0-9 ,.]{1,50}$ + example: Default policy + rules: + type: array + description: A list of rules that comprise the policy. There is a limit of 10 rules per policy. + items: + $ref: '#/components/schemas/Rule' + required: + - scope + - rules + responses: + '201': + description: Successfully created policy. + content: + application/json: + schema: + $ref: '#/components/schemas/Policy' '400': description: Invalid request. content: @@ -7148,36 +7612,100 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - malformed_transaction: + invalid_request: value: - errorType: malformed_transaction - errorMessage: Malformed unsigned transaction. - '401': - description: Unauthorized. + errorType: invalid_request + errorMessage: Policy name must be between 1 and 50 characters. + '409': + $ref: '#/components/responses/AlreadyExistsError' + '422': + $ref: '#/components/responses/IdempotencyError' + '500': + $ref: '#/components/responses/InternalServerError' + '502': + $ref: '#/components/responses/BadGatewayError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + /v2/policy-engine/policies/{policyId}: + get: + x-audience: public + summary: Get policy by ID + description: Get a policy by its ID. + operationId: getPolicyById + tags: + - Policy Engine + security: + - apiKeyAuth: [] + parameters: + - name: policyId + description: The ID of the policy to get. + in: path + required: true + schema: + type: string + pattern: ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ + example: 123e4567-e89b-12d3-a456-426614174000 + responses: + '200': + description: Successfully retrieved policy. + content: + application/json: + schema: + $ref: '#/components/schemas/Policy' + '404': + description: Policy not found. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - unauthorized: + not_found: value: - errorType: unauthorized - errorMessage: Wallet authentication error. - '402': - $ref: '#/components/responses/PaymentMethodRequiredError' - '403': - description: Access to resource forbidden. + errorType: not_found + errorMessage: Policy not found. + '500': + $ref: '#/components/responses/InternalServerError' + '502': + $ref: '#/components/responses/BadGatewayError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + delete: + x-audience: public + summary: Delete policy + description: Delete a policy by its ID. This will have the effect of removing the policy from all accounts that are currently using it. + operationId: deletePolicy + tags: + - Policy Engine + security: + - apiKeyAuth: [] + x-required-api-auth-scopes: + - policies#manage + parameters: + - $ref: '#/components/parameters/IdempotencyKey' + - name: policyId + description: The ID of the policy to delete. + in: path + required: true + schema: + type: string + pattern: ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ + example: 123e4567-e89b-12d3-a456-426614174000 + responses: + '204': + description: Successfully deleted policy. + '400': + description: Unable to delete policy. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - forbidden: + not_found: value: - errorType: forbidden - errorMessage: Unable to sign transaction for this address. + errorType: policy_in_use + errorMessage: Policy in use. '404': - description: Solana account not found. + description: Policy not found. content: application/json: schema: @@ -7186,7 +7714,7 @@ paths: not_found: value: errorType: not_found - errorMessage: Solana account with the given address not found. + errorMessage: Policy not found. '409': $ref: '#/components/responses/AlreadyExistsError' '422': @@ -7197,56 +7725,55 @@ paths: $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/solana/accounts/{address}/sign/message: - post: + put: x-audience: public - summary: Sign a message - description: |- - Signs an arbitrary message with the given Solana account. - - **WARNING:** Never sign a message that you didn't generate, as it can be an arbitrary transaction. For example, it might send all of your funds to an attacker. - operationId: signSolanaMessage + summary: Update policy + description: Updates a policy by its ID. This will have the effect of applying the updated policy to all accounts that are currently using it. + operationId: updatePolicy tags: - - Solana Accounts + - Policy Engine security: - apiKeyAuth: [] + x-required-api-auth-scopes: + - policies#manage parameters: - - $ref: '#/components/parameters/XWalletAuth' - $ref: '#/components/parameters/IdempotencyKey' - - name: address - description: The base58 encoded address of the Solana account. + - name: policyId + description: The ID of the policy to update. in: path required: true schema: type: string - pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ - example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + pattern: ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ + example: 123e4567-e89b-12d3-a456-426614174000 requestBody: + required: true content: application/json: schema: type: object properties: - message: + description: type: string - description: The arbitrary message to sign. - example: Hello, world! + description: |- + An optional human-readable description for the policy. + Policy descriptions can consist of alphanumeric characters, spaces, commas, and periods, and be 50 characters or less. + pattern: ^[A-Za-z0-9 ,.]{1,50}$ + example: Default policy + rules: + type: array + description: A list of rules that comprise the policy. There is a limit of 10 rules per policy. + items: + $ref: '#/components/schemas/Rule' required: - - message + - rules responses: '200': - description: Successfully signed message. + description: Successfully updated policy. content: application/json: schema: - type: object - properties: - signature: - type: string - description: The signature of the message, as a base58 encoded string. - example: 4YecmNqVT9QFqzuSvE9Zih3toZzNAijjXpj8xupgcC6E4VzwzFjuZBk5P99yz9JQaLRLm1K4L4FpMjxByFxQBe2h - required: - - signature + $ref: '#/components/schemas/Policy' '400': description: Invalid request. content: @@ -7257,22 +7784,9 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: 'request body has an error: doesn''t match schema: Error at "message": string doesn''t match the regular expression "^0x[0-9a-fA-F]{40}$"' - '401': - description: Unauthorized. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - unauthorized: - value: - errorType: unauthorized - errorMessage: Wallet authentication error. - '402': - $ref: '#/components/responses/PaymentMethodRequiredError' + errorMessage: Policy name must be between 1 and 50 characters. '404': - description: Solana account not found. + description: Policy not found. content: application/json: schema: @@ -7281,7 +7795,7 @@ paths: not_found: value: errorType: not_found - errorMessage: Solana account with the given address not found. + errorMessage: Policy not found. '409': $ref: '#/components/responses/AlreadyExistsError' '422': @@ -7292,33 +7806,51 @@ paths: $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/solana/accounts/send/transaction: - post: + /v2/solana/accounts: + get: x-audience: public - summary: Send a Solana transaction + summary: List Solana accounts description: |- - Signs and sends a single Solana transaction using multiple Solana accounts. The transaction may contain contain several instructions, each of which may require signatures from different account keys. - - The transaction should be serialized into a byte array and base64 encoded. The API handles recent blockhash management and fee estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. - - **Transaction types** - - The following transaction types are supported: - * [Legacy transactions](https://solana.com/developers/guides/advanced/versions#current-transaction-versions) - * [Versioned transactions](https://solana.com/developers/guides/advanced/versions) - - **Instruction Batching** - - To batch multiple operations, include multiple instructions within a single transaction. All instructions within a transaction are executed atomically - if any instruction fails, the entire transaction fails and is rolled back. - - **Network Support** - - The following Solana networks are supported: - * `solana` - Solana Mainnet - * `solana-devnet` - Solana Devnet + Lists the Solana accounts belonging to the developer. + The response is paginated, and by default, returns 20 accounts per page. - The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. - operationId: sendSolanaTransaction + If a name is provided, the response will contain only the account with that name. + operationId: listSolanaAccounts + tags: + - Solana Accounts + security: + - apiKeyAuth: [] + parameters: + - $ref: '#/components/parameters/PageSize' + - $ref: '#/components/parameters/PageToken' + responses: + '200': + description: Successfully listed Solana accounts. + content: + application/json: + schema: + allOf: + - type: object + properties: + accounts: + type: array + items: + $ref: '#/components/schemas/SolanaAccount' + description: The list of Solana accounts. + required: + - accounts + - $ref: '#/components/schemas/ListResponse' + '500': + $ref: '#/components/responses/InternalServerError' + '502': + $ref: '#/components/responses/BadGatewayError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + post: + x-audience: public + summary: Create Solana account + description: Creates a new Solana account. + operationId: createSolanaAccount tags: - Solana Accounts security: @@ -7327,55 +7859,33 @@ paths: - $ref: '#/components/parameters/XWalletAuth' - $ref: '#/components/parameters/IdempotencyKey' requestBody: + required: false content: application/json: schema: type: object properties: - network: + name: type: string - description: The Solana network to send the transaction to. - enum: - - solana - - solana-devnet - example: solana-devnet - transaction: + description: |- + 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 Solana accounts in the developer's CDP Project. + example: my-wallet + pattern: ^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$ + accountPolicy: type: string - description: The base64 encoded transaction to sign and send. This transaction can contain multiple instructions for native Solana batching. - example: AQABAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA= - useCdpSponsor: - type: boolean - description: Whether transaction fees should be sponsored by CDP. When true, CDP sponsors the transaction fees on behalf of the server wallet. When false, the server wallet is responsible for paying the transaction fees. - example: true - required: - - network - - transaction - examples: - send_transaction: - summary: Send a transaction - value: - network: solana-devnet - transaction: AQABAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA= - send_transaction_sponsored: - summary: Send a transaction with CDP fee sponsorship - value: - network: solana-devnet - transaction: AQABAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA= - useCdpSponsor: true + x-audience: public + description: The ID of the account-level policy to apply to the account. + pattern: ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ + example: 123e4567-e89b-12d3-a456-426614174000 responses: - '200': - description: Successfully signed and sent transaction. + '201': + description: Successfully created Solana account. content: application/json: schema: - type: object - properties: - transactionSignature: - type: string - description: The base58 encoded transaction signature. - example: 5VERv8NMvzbJMEkV8xnrLkEaWRtSz9CosKDYjCJjBRnbJLgp8uirBgmQpjKhoR4tjF3ZpRzrFmBV6UjKdiSZkQUW - required: - - transactionSignature + $ref: '#/components/schemas/SolanaAccount' '400': description: Invalid request. content: @@ -7383,10 +7893,10 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - malformed_transaction: + invalid_request: value: - errorType: malformed_transaction - errorMessage: Malformed unsigned transaction. + errorType: invalid_request + errorMessage: Project has no secret. Please register a secret with the project. '401': description: Unauthorized. content: @@ -7400,17 +7910,62 @@ paths: errorMessage: Wallet authentication error. '402': $ref: '#/components/responses/PaymentMethodRequiredError' - '403': - description: Access to resource forbidden. + '409': + description: Resource already exists. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - forbidden: + already_exists: value: - errorType: forbidden - errorMessage: Unable to sign transaction for this address + errorType: already_exists + errorMessage: Solana account with the given name already exists. + '422': + $ref: '#/components/responses/IdempotencyError' + '500': + $ref: '#/components/responses/InternalServerError' + '502': + $ref: '#/components/responses/BadGatewayError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + /v2/solana/accounts/{address}: + get: + x-audience: public + summary: Get Solana account by address + description: Gets a Solana account by its address. + operationId: getSolanaAccount + tags: + - Solana Accounts + security: + - apiKeyAuth: [] + parameters: + - name: address + description: The base58 encoded address of the Solana account. + in: path + required: true + schema: + type: string + pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ + example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + responses: + '200': + description: Successfully got Solana account. + content: + application/json: + schema: + $ref: '#/components/schemas/SolanaAccount' + '400': + description: Invalid request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + invalid_request: + value: + errorType: invalid_request + errorMessage: 'request body has an error: doesn''t match schema: Error at "address": string doesn''t match the regular expression "^[1-9A-HJ-NP-Za-km-z]{32,44}$".' '404': description: Not found. content: @@ -7422,73 +7977,57 @@ paths: value: errorType: not_found errorMessage: Solana account with the given address not found. - '422': - $ref: '#/components/responses/IdempotencyError' '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/solana/faucet: - post: + put: x-audience: public - summary: Request funds on Solana devnet - description: | - Request funds from the CDP Faucet on Solana devnet. - - Faucets are available for SOL, USDC, and CBTUSD. - - To prevent abuse, we enforce rate limits within a rolling 24-hour window to control the amount of funds that can be requested. - These limits are applied at both the CDP Project level and the blockchain address level. - A single blockchain address cannot exceed the specified limits, even if multiple users submit requests to the same address. - - | Token | Amount per Faucet Request |Rolling 24-hour window Rate Limits| - |:-----: |:-------------------------:|:--------------------------------:| - | SOL | 0.00125 SOL | 0.0125 SOL | - | USDC | 1 USDC | 10 USDC | - | CBTUSD | 1 CBTUSD | 10 CBTUSD | - operationId: requestSolanaFaucet + summary: Update Solana account + description: Updates an existing Solana account. Use this to update the account's name or account-level policy. + operationId: updateSolanaAccount tags: - - Faucets + - Solana Accounts security: - apiKeyAuth: [] + parameters: + - $ref: '#/components/parameters/IdempotencyKey' + - name: address + description: The base58 encoded address of the Solana account. + in: path + required: true + schema: + type: string + pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ + example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT requestBody: content: application/json: schema: type: object properties: - address: + name: type: string - description: The address to request funds to, which is a base58-encoded string. - pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ - example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT - token: + description: |- + 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 Solana accounts in the developer's CDP Project. + example: my-wallet + pattern: ^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$ + accountPolicy: type: string - description: The token to request funds for. - enum: - - sol - - usdc - - cbtusd - example: sol - required: - - address - - token + x-audience: public + description: The ID of the account-level policy to apply to the account, or an empty string to unset attached policy. + pattern: (^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$)|(^$) + example: 123e4567-e89b-12d3-a456-426614174000 responses: '200': - description: Successfully requested funds. + description: Successfully updated Solana account. content: application/json: schema: - type: object - properties: - transactionSignature: - type: string - description: The signature identifying the transaction that requested the funds. - example: 4dje1d24iG2FfxwxTJJt8VSTtYXNc6AAuJwngtL97TJSqqPD3pgRZ7uh4szoU6WDrKyFTBgaswkDrCr7BqWjQqqK - required: - - transactionSignature + $ref: '#/components/schemas/SolanaAccount' '400': description: Invalid request. content: @@ -7496,118 +8035,56 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - invalid_address_format: - value: - errorType: invalid_request - errorMessage: 'request body has an error: doesn''t match schema: Error at "address": string doesn''t match the regular expression "^[1-9A-HJ-NP-Za-km-z]{32,44}$"' invalid_request: value: errorType: invalid_request - errorMessage: Unable to request faucet funds for this address. - '403': - description: Access to resource forbidden. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - examples: - forbidden: - value: - errorType: forbidden - errorMessage: Unable to request faucet funds for this address. - '429': - description: Rate limit exceeded. + errorMessage: 'request body has an error: doesn''t match schema: Error at "name": string doesn''t match the regular expression "^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$".' + '404': + description: Solana account not found. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - faucet_limit_exceeded: + not_found: value: - errorType: faucet_limit_exceeded - errorMessage: Faucet limit reached for this address. Please try again later. + errorType: not_found + errorMessage: Solana account with the given address not found. + '409': + $ref: '#/components/responses/AlreadyExistsError' + '422': + $ref: '#/components/responses/IdempotencyError' '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/solana/token-balances/{network}/{address}: + /v2/solana/accounts/by-name/{name}: get: x-audience: public - summary: List Solana token balances - description: |- - Lists the token balances of a Solana address on a given network. The balances include SPL tokens and the native SOL token. The response is paginated, and by default, returns 20 balances per page. - - **Note:** This endpoint is still under development and does not yet provide strong availability or freshness guarantees. Freshness and availability of new token balances will improve over the coming weeks. - operationId: listSolanaTokenBalances + summary: Get Solana account by name + description: Gets a Solana account by its name. + operationId: getSolanaAccountByName tags: - - Solana Token Balances + - Solana Accounts security: - apiKeyAuth: [] parameters: - - name: address - description: The base58 encoded Solana address to get balances for. - in: path - required: true - schema: - type: string - pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ - example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT - - name: network - description: The human-readable network name to get the balances for. + - name: name + description: The name of the Solana account. in: path required: true - schema: - $ref: '#/components/schemas/ListSolanaTokenBalancesNetwork' - example: solana - - name: pageSize - description: The number of balances to return per page. - in: query - required: false - schema: - type: integer - default: 20 - example: 10 - - name: pageToken - description: The token for the next page of balances. Will be empty if there are no more balances to fetch. - in: query - required: false schema: type: string - example: eyJsYXN0X2lkIjogImFiYzEyMyIsICJ0aW1lc3RhbXAiOiAxNzA3ODIzNzAxfQ== + example: my-account responses: '200': - description: Successfully listed token balances. + description: Successfully got Solana account. content: application/json: schema: - allOf: - - type: object - required: - - balances - properties: - balances: - type: array - items: - $ref: '#/components/schemas/SolanaTokenBalance' - description: The list of Solana token balances. - example: - - amount: - amount: '1250000000' - decimals: 9 - token: - symbol: SOL - name: Solana - mintAddress: So11111111111111111111111111111111111111111 - - amount: - amount: '123456000' - decimals: 6 - token: - symbol: USDC - name: USD Coin - mintAddress: 4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU - - $ref: '#/components/schemas/ListResponse' + $ref: '#/components/schemas/SolanaAccount' '400': description: Invalid request. content: @@ -7618,7 +8095,7 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: string doesn't match the regular expression "^[1-9A-HJ-NP-Za-km-z]{32,44}$" + errorMessage: 'error: parameter "name" must be a string.' '404': description: Not found. content: @@ -7629,327 +8106,336 @@ paths: not_found: value: errorType: not_found - errorMessage: Address not found, or no balances found for the given address on this chain. + errorMessage: Solana account with the given name not found. '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/data/query/run: + /v2/solana/accounts/import: post: - operationId: runSQLQuery - summary: Run SQL Query x-audience: public - description: | - Run a read-only SQL query against indexed blockchain data including transactions, events, and decoded logs. - - This endpoint provides direct SQL access to comprehensive blockchain data across supported networks. - - Queries are executed against optimized data structures for high-performance analytics. - - ### Allowed Queries - - - Standard SQL syntax (CoinbaSeQL dialect, based on ClickHouse dialect) - - Read-only queries (SELECT statements) - - No DDL or DML operations - - Query that follow limits (defined below) - - ### Supported Tables - - - `.events` - Base mainnet decoded event logs with parameters, event signature, topics, and more. - - `.transactions` - Base mainnet transaction data including hash, block number, gas usage. - - `.blocks` - Base mainnet block information. - - `.encoded_logs` - Encoded log data of event logs that aren't able to be decoded by our event decoder (ex: log0 opcode). - - `.decoded_user_operations` - Decoded user operations data including hash, block number, gas usage, builder codes, entrypoint version, and more. - - `.transaction_attributions` - Information about the attributions of a transaction to a builder and associated builder codes. - - ### Supported Networks - - - Base Mainnet: `base` - - Base Sepolia: `base_sepolia` - - So for example, valid tables are: `base.events`, `base_sepolia.events`, `base.transactions`, etc. - - ### Query Limits - - - Maximum result set: 50,000 rows - - Maximum query length: 10,000 characters - - Maximum on-disk data to read: 100GB - - Maximum memory usage: 15GB - - Query timeout: 30 seconds - - Maximum JOINs: 12 - - ### Query Caching - - By default, each query result is returned from cache so long as the result is from an identical query and less than 750ms old. This freshness tolerance can be modified upwards, to a maximum of 900000ms (i.e. 900s, 15m). - This can be helpful for users who wish to reduce expensive calls to the SQL API by reusing cached results. + summary: Import Solana account + description: Import an existing Solana account into the developer's CDP Project. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. + operationId: importSolanaAccount tags: - - SQL API + - Solana Accounts security: - apiKeyAuth: [] + parameters: + - $ref: '#/components/parameters/XWalletAuth' + - $ref: '#/components/parameters/IdempotencyKey' requestBody: - required: true content: application/json: schema: - $ref: '#/components/schemas/OnchainDataQuery' + type: object + properties: + encryptedPrivateKey: + type: string + description: The base64-encoded, encrypted 32-byte private key of the Solana account. The private key must be encrypted using the CDP SDK's encryption scheme. + example: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= + name: + type: string + description: |- + 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. + example: my-solana-wallet + pattern: ^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$ + required: + - encryptedPrivateKey responses: - '200': - description: Query run successfully. + '201': + description: Successfully imported Solana account. content: application/json: schema: - $ref: '#/components/schemas/OnchainDataResult' + $ref: '#/components/schemas/SolanaAccount' '400': - $ref: '#/components/responses/InvalidSQLQueryError' + description: Invalid request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + invalid_request: + value: + errorType: invalid_request + errorMessage: The encrypted private key is invalid. '401': - $ref: '#/components/responses/UnauthorizedError' - '402': - $ref: '#/components/responses/PaymentMethodRequiredError' - '408': - description: Query timeout. + description: Unauthorized. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - query_timeout: + unauthorized: value: - errorType: timed_out - errorMessage: Query execution was cut off by the server. Please try again with a more efficient query. - '429': - description: Rate limit exceeded. + errorType: unauthorized + errorMessage: Wallet authentication error. + '402': + $ref: '#/components/responses/PaymentMethodRequiredError' + '409': + description: Resource already exists. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - rate_limit_exceeded: + already_exists: value: - errorType: rate_limit_exceeded - errorMessage: Too many requests. Please try again later. - '499': - $ref: '#/components/responses/ClientClosedRequestError' + errorType: already_exists + errorMessage: Solana account with the given address already exists. + '422': + $ref: '#/components/responses/IdempotencyError' '500': $ref: '#/components/responses/InternalServerError' - '504': - $ref: '#/components/responses/TimedOutError' - /v2/data/query/grammar: - get: - operationId: getSQLGrammar - summary: Get SQL grammar + '502': + $ref: '#/components/responses/BadGatewayError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + /v2/solana/accounts/{address}/export: + post: x-audience: public - description: | - Retrieve the SQL grammar for the SQL API. - - The SQL queries that are supported by the SQL API are defined in ANTLR4 grammar which is evaluated by server before executing the query. This ensures the safety and soundness of the SQL query before execution. - - This endpoint returns the ANTLR4 grammar that is used to evaluate the SQL queries so that developers can understand the SQL API and build SQL queries with high confidence and correctness. - - LLMs interact well with ANTLR4 grammar. You can feed the grammar directly into the LLMs to help generate SQL queries. + summary: Export Solana account + description: Export an existing Solana account's private key. It is important to store the private key in a secure place after it's exported. + operationId: exportSolanaAccount tags: - - SQL API + - Solana Accounts security: - apiKeyAuth: [] + x-required-api-auth-scopes: + - accounts#export + parameters: + - $ref: '#/components/parameters/XWalletAuth' + - $ref: '#/components/parameters/IdempotencyKey' + - name: address + description: The base58 encoded address of the Solana account. + in: path + required: true + schema: + type: string + pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ + example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + requestBody: + content: + application/json: + schema: + type: object + properties: + exportEncryptionKey: + type: string + description: The base64-encoded, public part of the RSA key in DER format used to encrypt the account private key. + example: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= + required: + - exportEncryptionKey responses: '200': - description: SQL grammar retrieved successfully. + description: Successfully exported Solana account. content: application/json: schema: - type: string - description: The ANTLR4 grammar for the SQL API. - example: 'grammar SqlQuery; query: cteClause? unionStatement SEMICOLON? EOF;' + type: object + properties: + encryptedPrivateKey: + type: string + description: The base64-encoded, encrypted private key of the Solana account which is a 32 byte raw private key. The private key is encrypted in transport using the exportEncryptionKey in the request. + example: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= + required: + - encryptedPrivateKey + '400': + description: Invalid request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + invalid_request: + value: + errorType: invalid_request + errorMessage: Solana account with the given address not found. '401': - $ref: '#/components/responses/UnauthorizedError' - '429': - description: Rate limit exceeded. + description: Unauthorized. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - rate_limit_exceeded: + unauthorized: value: - errorType: rate_limit_exceeded - errorMessage: Too many requests. Please try again later. + errorType: unauthorized + errorMessage: Wallet authentication error. + '402': + $ref: '#/components/responses/PaymentMethodRequiredError' + '404': + description: Not found. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + not_found: + value: + errorType: not_found + errorMessage: Solana account with the given address not found. + '422': + $ref: '#/components/responses/IdempotencyError' '500': $ref: '#/components/responses/InternalServerError' - '504': - $ref: '#/components/responses/TimedOutError' - /v2/data/query/schema: - get: - operationId: getSQLSchema - summary: Get schemas details + '502': + $ref: '#/components/responses/BadGatewayError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + /v2/solana/accounts/export/by-name/{name}: + post: x-audience: public - description: | - Retrieve the schema information for the available tables in the SQL API's indexed data. - - This includes table names, column definitions, data types, and indexed fields. - tags: - - SQL API - security: - - apiKeyAuth: [] - parameters: - - name: database - in: query - required: false - description: The name of the database to query. Defaults to "base" when not specified. - schema: - type: string - enum: - - base - - base_sepolia - default: base - example: base - - name: table - in: query - required: false - description: Get the schema for a specific table. - schema: - type: string - example: events - responses: - '200': - description: Schema information retrieved successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/OnchainDataSchemaResponse' - '401': - $ref: '#/components/responses/UnauthorizedError' - '500': - $ref: '#/components/responses/InternalServerError' - /v2/data/evm/token-ownership/{network}/{address}: - get: - operationId: listTokensForAccount - summary: List token addresses for account - x-audience: public - description: | - Retrieve all ERC-20 token contract addresses that an account has ever received tokens from. - Analyzes transaction history to discover token interactions. + summary: Export Solana account by name + description: Export an existing Solana account's private key by its name. It is important to store the private key in a secure place after it's exported. + operationId: exportSolanaAccountByName tags: - - Onchain Data + - Solana Accounts security: - apiKeyAuth: [] + x-required-api-auth-scopes: + - accounts#export parameters: - - name: network - in: path - required: true - description: The blockchain network to query. - schema: - type: string - enum: - - base - - base-sepolia - example: base - - name: address + - $ref: '#/components/parameters/XWalletAuth' + - $ref: '#/components/parameters/IdempotencyKey' + - name: name + description: The name of the Solana account. in: path required: true - description: The account address to analyze for token interactions. schema: type: string - pattern: ^0x[0-9a-fA-F]{40}$ - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + example: my-account + requestBody: + content: + application/json: + schema: + type: object + properties: + exportEncryptionKey: + type: string + description: The base64-encoded, public part of the RSA key in DER format used to encrypt the account private key. + example: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= + required: + - exportEncryptionKey responses: '200': - description: Token addresses retrieved successfully. + description: Successfully exported Solana account. content: application/json: schema: - $ref: '#/components/schemas/AccountTokenAddressesResponse' + type: object + properties: + encryptedPrivateKey: + type: string + description: The base64-encoded, encrypted private key of the Solana account which is a 32 byte raw private key. The private key is encrypted in transport using the exportEncryptionKey in the request. + example: U2FsdGVkX1+vupppZksvRf5X5YgHq4+da+Q4qf51+Q4= + required: + - encryptedPrivateKey '400': - description: Invalid account address format. + description: Invalid request. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - invalid_address: + invalid_request: value: errorType: invalid_request - errorMessage: Invalid account address format. Address must be 40 hex characters prefixed with '0x' + errorMessage: 'error: parameter "name" must be a string.' '401': - $ref: '#/components/responses/UnauthorizedError' - '429': - description: Rate limit exceeded. + description: Unauthorized. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - rate_limit_exceeded: + unauthorized: value: - errorType: rate_limit_exceeded - errorMessage: Too many requests. Please try again later. + errorType: unauthorized + errorMessage: Wallet authentication error. + '402': + $ref: '#/components/responses/PaymentMethodRequiredError' + '404': + description: Not found. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + not_found: + value: + errorType: not_found + errorMessage: Solana account with the given name not found. + '422': + $ref: '#/components/responses/IdempotencyError' '500': $ref: '#/components/responses/InternalServerError' - /v2/data/evm/token-balances/{network}/{address}: - get: - summary: List EVM token balances + '502': + $ref: '#/components/responses/BadGatewayError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + /v2/solana/accounts/{address}/sign/transaction: + post: x-audience: public + summary: Sign transaction description: |- - Lists the token balances of an EVM address on a given network. The balances include ERC-20 tokens and the native gas token (usually ETH). The response is paginated, and by default, returns 20 balances per page. + Signs a transaction with the given Solana account. + The unsigned transaction should be serialized into a byte array and then encoded as base64. - **Note:** This endpoint provides <1 second freshness from chain tip, <500ms response latency for wallets with reasonable token history, and 99.9% uptime for production use. - operationId: listDataTokenBalances + **Transaction types** + + The following transaction types are supported: + * [Legacy transactions](https://solana-labs.github.io/solana-web3.js/classes/Transaction.html) + * [Versioned transactions](https://solana-labs.github.io/solana-web3.js/classes/VersionedTransaction.html) + + The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. + operationId: signSolanaTransaction tags: - - Onchain Data + - Solana Accounts security: - apiKeyAuth: [] parameters: + - $ref: '#/components/parameters/XWalletAuth' + - $ref: '#/components/parameters/IdempotencyKey' - name: address - description: The 0x-prefixed EVM address to get balances for. The address does not need to be checksummed. + description: The base58 encoded address of the Solana account. in: path required: true schema: type: string - pattern: ^0x[0-9a-fA-F]{40}$ - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - - name: network - description: The human-readable network name to get the balances for. - in: path - required: true - schema: - $ref: '#/components/schemas/ListEvmTokenBalancesNetwork' - example: base - - $ref: '#/components/parameters/PageSize' - - $ref: '#/components/parameters/PageToken' + pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ + example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + requestBody: + content: + application/json: + schema: + type: object + properties: + transaction: + type: string + description: The base64 encoded transaction to sign. + example: AQABAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA= + required: + - transaction responses: '200': - description: Successfully listed token balances. + description: Successfully signed transaction. content: application/json: schema: - allOf: - - type: object - required: - - balances - properties: - balances: - type: array - items: - $ref: '#/components/schemas/TokenBalance' - description: The list of EVM token balances. - example: - - amount: - amount: '1250000000000000000' - decimals: 18 - token: - network: base - symbol: ETH - name: ether - contractAddress: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE' - - amount: - amount: '123456' - decimals: 6 - token: - network: base - symbol: USDC - name: USD Coin - contractAddress: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' - - $ref: '#/components/schemas/ListResponse' + type: object + properties: + signedTransaction: + type: string + description: The base64 encoded signed transaction. + example: AQACAdSOvpk0UJXs/rQRXYKSI9hcR0bkGp24qGv6t0/M1XjcQpHf6AHwLcPjEtKQI7p/U0Zo98lnJ5/PZMfVq/0BAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA= + required: + - signedTransaction '400': description: Invalid request. content: @@ -7957,12 +8443,36 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - invalid_request: + malformed_transaction: value: - errorType: invalid_request - errorMessage: string doesn't match the regular expression "^0x[0-9a-fA-F]{40}$" + errorType: malformed_transaction + errorMessage: Malformed unsigned transaction. + '401': + description: Unauthorized. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + unauthorized: + value: + errorType: unauthorized + errorMessage: Wallet authentication error. + '402': + $ref: '#/components/responses/PaymentMethodRequiredError' + '403': + description: Access to resource forbidden. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + forbidden: + value: + errorType: forbidden + errorMessage: Unable to sign transaction for this address. '404': - description: Not found. + description: Solana account not found. content: application/json: schema: @@ -7971,386 +8481,335 @@ paths: not_found: value: errorType: not_found - errorMessage: Address not found, or no balances found for the given address on this chain. + errorMessage: Solana account with the given address not found. + '409': + $ref: '#/components/responses/AlreadyExistsError' + '422': + $ref: '#/components/responses/IdempotencyError' '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/data/webhooks/subscriptions: - get: - operationId: listWebhookSubscriptions - summary: List webhook subscriptions + /v2/solana/accounts/{address}/sign/message: + post: x-audience: public - x-required-permissions: - permissions: - - accounts:read@entity - enforcement: any - description: | - Retrieve a paginated list of webhook subscriptions for the authenticated project. - Returns subscriptions for all CDP product events (onchain, onramp/offramp, wallet, etc.) - in descending order by creation time. + summary: Sign message + description: |- + Signs an arbitrary message with the given Solana account. - ### Use Cases - - Monitor all active webhook subscriptions across CDP products - - Audit webhook configurations - - Manage subscription lifecycle + **WARNING:** Never sign a message that you didn't generate, as it can be an arbitrary transaction. For example, it might send all of your funds to an attacker. + operationId: signSolanaMessage tags: - - Webhooks + - Solana Accounts security: - apiKeyAuth: [] parameters: - - name: pageSize - description: The number of subscriptions to return per page. - in: query - required: false - schema: - type: integer - default: 20 - minimum: 1 - maximum: 100 - example: 10 - - name: pageToken - description: The token for the next page of subscriptions, if any. - in: query - required: false + - $ref: '#/components/parameters/XWalletAuth' + - $ref: '#/components/parameters/IdempotencyKey' + - name: address + description: The base58 encoded address of the Solana account. + in: path + required: true schema: type: string - example: eyJsYXN0X2lkIjogImFiYzEyMyIsICJ0aW1lc3RhbXAiOiAxNzA3ODIzNzAxfQ== + pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ + example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + requestBody: + content: + application/json: + schema: + type: object + properties: + message: + type: string + description: The arbitrary message to sign. + example: Hello, world! + required: + - message responses: '200': - description: Webhook subscriptions retrieved successfully. + description: Successfully signed message. content: application/json: schema: - $ref: '#/components/schemas/WebhookSubscriptionListResponse' + type: object + properties: + signature: + type: string + description: The signature of the message, as a base58 encoded string. + example: 4YecmNqVT9QFqzuSvE9Zih3toZzNAijjXpj8xupgcC6E4VzwzFjuZBk5P99yz9JQaLRLm1K4L4FpMjxByFxQBe2h + required: + - signature '400': - description: Invalid request parameters. + description: Invalid request. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - invalid_page_size: - value: - errorType: invalid_request - errorMessage: Page size must be between 1 and 100 - invalid_page_token: + invalid_request: value: errorType: invalid_request - errorMessage: Invalid page token format + errorMessage: 'request body has an error: doesn''t match schema: Error at "message": string doesn''t match the regular expression "^0x[0-9a-fA-F]{40}$".' '401': - $ref: '#/components/responses/UnauthorizedError' - '429': - description: Rate limit exceeded. + description: Unauthorized. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - rate_limit_exceeded: + unauthorized: value: - errorType: rate_limit_exceeded - errorMessage: Too many requests. Please try again later. + errorType: unauthorized + errorMessage: Wallet authentication error. + '402': + $ref: '#/components/responses/PaymentMethodRequiredError' + '404': + description: Solana account not found. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + not_found: + value: + errorType: not_found + errorMessage: Solana account with the given address not found. + '409': + $ref: '#/components/responses/AlreadyExistsError' + '422': + $ref: '#/components/responses/IdempotencyError' '500': $ref: '#/components/responses/InternalServerError' + '502': + $ref: '#/components/responses/BadGatewayError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + /v2/solana/accounts/send/transaction: post: - operationId: createWebhookSubscription - summary: Create webhook subscription x-audience: public - x-required-permissions: - permissions: - - accounts:write@entity - enforcement: any - description: | - Subscribe to real-time events across CDP products using flexible filtering. - - ### Event Types - - **Onchain Events** - Monitor Base mainnet with microsecond precision: - - `onchain.activity.detected` - Smart contract events, transfers, swaps, NFT activity - - **Requires** `labels` for filtering (e.g., `contract_address`, `event_name`) - - **Onramp/Offramp Events** - Transaction lifecycle notifications: - - `onramp.transaction.created`, `onramp.transaction.updated` - - `onramp.transaction.success`, `onramp.transaction.failed` - - `offramp.transaction.created`, `offramp.transaction.updated` - - `offramp.transaction.success`, `offramp.transaction.failed` - - **No labels required** - maximum simplicity for transaction monitoring - - **Payments Transfers Events** - Transfer lifecycle notifications: - - `payments.transfers.quoted` - Transfer created and awaiting execution - - `payments.transfers.processing` - Transfer execution in progress - - `payments.transfers.completed` - Transfer completed successfully - - `payments.transfers.failed` - Transfer failed - - `payments.transfers.travel_rule_incomplete` - Travel rule information is missing - - `payments.transfers.travel_rule_completed` - Travel rule information has been provided and the transfer will proceed - - **No labels required** - enable the transfers webhook to monitor status transitions + summary: Send Solana transaction + description: |- + Signs and sends a single Solana transaction using multiple Solana accounts. The transaction may contain contain several instructions, each of which may require signatures from different account keys. - **Wallet Events** - Wallet activity notifications: - - `wallet.activity.detected` + The transaction should be serialized into a byte array and base64 encoded. The API handles recent blockhash management and fee estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. - ### Webhook Signature Verification - All webhooks include cryptographic signatures for security. - The signature secret is returned in `secret` field when creating a subscription. + **Transaction types** - **Note:** Webhooks are in beta and this interface is subject to change. + The following transaction types are supported: + * [Legacy transactions](https://solana.com/developers/guides/advanced/versions#current-transaction-versions) + * [Versioned transactions](https://solana.com/developers/guides/advanced/versions) - See the [verification guide](https://docs.cdp.coinbase.com/onramp-&-offramp/webhooks#webhook-signature-verification) for implementation details. + **Instruction Batching** - ### Onchain Label Filtering + To batch multiple operations, include multiple instructions within a single transaction. All instructions within a transaction are executed atomically - if any instruction fails, the entire transaction fails and is rolled back. - For `onchain.activity.detected` events, use `labels` for precise filtering with AND logic (max 20 labels per webhook). + **Network Support** - **Allowed labels** (all in snake_case format): - - `network` (required) - Blockchain network - - `contract_address` - Smart contract address - - `event_name` - Event name (e.g., "Transfer", "Burn") - - `event_signature` - Event signature hash - - `transaction_from` - Transaction sender address - - `transaction_to` - Transaction recipient address - - `params.*` - Any event parameter (e.g., `params.from`, `params.to`, `params.sender`, `params.tokenId`) + The following Solana networks are supported: + * `solana` - Solana Mainnet + * `solana-devnet` - Solana Devnet - **Examples**: - - **Liquidity Pool Monitor**: `{"network": "base-mainnet", "contract_address": "0xcd1f9777571493aeacb7eae45cd30a226d3e612d", "event_name": "Burn"}` - - **Price Oracle Tracker**: `{"network": "base-mainnet", "contract_address": "0xbac4a9428ea707c51f171ed9890c3c2fa810305d", "event_name": "PriceUpdated"}` - - **DeFi Protocol Activity**: `{"network": "base-mainnet", "contract_address": "0x45c6e6a47a711b14d8357d5243f46704904578e3", "event_name": "Deposit"}` + The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. + operationId: sendSolanaTransaction tags: - - Webhooks + - Solana Accounts security: - apiKeyAuth: [] + parameters: + - $ref: '#/components/parameters/XWalletAuth' + - $ref: '#/components/parameters/IdempotencyKey' requestBody: - required: true content: application/json: schema: - $ref: '#/components/schemas/WebhookSubscriptionRequest' + type: object + properties: + network: + type: string + description: The Solana network to send the transaction to. + enum: + - solana + - solana-devnet + example: solana-devnet + transaction: + type: string + description: The base64 encoded transaction to sign and send. This transaction can contain multiple instructions for native Solana batching. + example: AQABAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA= + useCdpSponsor: + type: boolean + description: Whether transaction fees should be sponsored by CDP. When true, CDP sponsors the transaction fees on behalf of the server wallet. When false, the server wallet is responsible for paying the transaction fees. + example: true + required: + - network + - transaction examples: - onchain_liquidity_pool: - summary: 'Onchain: Monitor liquidity pool burns' - value: - description: Liquidity pool burn events. - eventTypes: - - onchain.activity.detected - labels: - network: base-mainnet - contract_address: '0xcd1f9777571493aeacb7eae45cd30a226d3e612d' - event_name: Burn - target: - url: https://api.example.com/webhooks - isEnabled: true - onramp_transactions: - summary: 'Onramp: Transaction lifecycle' - value: - description: Onramp transaction status webhook. - eventTypes: - - onramp.transaction.created - - onramp.transaction.updated - - onramp.transaction.success - - onramp.transaction.failed - labels: {} - target: - url: https://api.example.com/webhooks - isEnabled: true - offramp_transactions: - summary: 'Offramp: Transaction lifecycle' + send_transaction: + summary: Send a transaction value: - description: Offramp transaction status webhook. - eventTypes: - - offramp.transaction.created - - offramp.transaction.updated - - offramp.transaction.success - - offramp.transaction.failed - labels: {} - target: - url: https://api.example.com/webhooks - isEnabled: true - wallet_outgoing_transactions: - summary: 'Wallet: Monitor outgoing transactions' + network: solana-devnet + transaction: AQABAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA= + send_transaction_sponsored: + summary: Send a transaction with CDP fee sponsorship value: - description: Outgoing transactions. - eventTypes: - - wallet.activity.detected - labels: - network: base-mainnet - params.from: '0xB7f5BF799fB265657c628ef4a13f90f83a3a616A' - target: - url: https://api.example.com/webhooks - isEnabled: true + network: solana-devnet + transaction: AQABAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA= + useCdpSponsor: true responses: - '201': - description: Webhook subscription created successfully. - content: + '200': + description: Successfully signed and sent transaction. + content: application/json: schema: - $ref: '#/components/schemas/WebhookSubscriptionResponse' + type: object + properties: + transactionSignature: + type: string + description: The base58 encoded transaction signature. + example: 5VERv8NMvzbJMEkV8xnrLkEaWRtSz9CosKDYjCJjBRnbJLgp8uirBgmQpjKhoR4tjF3ZpRzrFmBV6UjKdiSZkQUW + required: + - transactionSignature '400': - description: Invalid subscription configuration. + description: Invalid request. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - invalid_url: - value: - errorType: invalid_request - errorMessage: Target URL must be a valid HTTPS endpoint - invalid_event_types: + malformed_transaction: value: - errorType: invalid_request - errorMessage: Event types must be non-empty and contain valid event type names + errorType: malformed_transaction + errorMessage: Malformed unsigned transaction. '401': - $ref: '#/components/responses/UnauthorizedError' - '429': - description: Rate limit exceeded. + description: Unauthorized. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - rate_limit_exceeded: + unauthorized: value: - errorType: rate_limit_exceeded - errorMessage: Too many requests. Please try again later. - '500': - $ref: '#/components/responses/InternalServerError' - /v2/data/webhooks/subscriptions/{subscriptionId}: - get: - operationId: getWebhookSubscription - summary: Get webhook subscription details - x-audience: public - x-required-permissions: - permissions: - - accounts:read@entity - enforcement: any - description: | - Retrieve detailed information about a specific webhook subscription including - configuration, status, creation timestamp, and webhook signature secret. - - ### Response Includes - - Subscription configuration and filters - - Target URL and custom headers - - Webhook signature secret for verification - - Creation timestamp and status - tags: - - Webhooks - security: - - apiKeyAuth: [] - parameters: - - name: subscriptionId - in: path - required: true - description: Unique identifier for the webhook subscription. - schema: - type: string - format: uuid - example: 123e4567-e89b-12d3-a456-426614174000 - responses: - '200': - description: Webhook subscription details retrieved successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/WebhookSubscriptionResponse' - '401': - $ref: '#/components/responses/UnauthorizedError' - '404': - description: Webhook subscription not found. + errorType: unauthorized + errorMessage: Wallet authentication error. + '402': + $ref: '#/components/responses/PaymentMethodRequiredError' + '403': + description: Access to resource forbidden. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - subscription_not_found: + forbidden: value: - errorType: not_found - errorMessage: Webhook subscription not found - '429': - description: Rate limit exceeded. + errorType: forbidden + errorMessage: Unable to sign transaction for this address. + '404': + description: Not found. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - rate_limit_exceeded: + not_found: value: - errorType: rate_limit_exceeded - errorMessage: Too many requests. Please try again later. + errorType: not_found + errorMessage: Solana account with the given address not found. + '422': + $ref: '#/components/responses/IdempotencyError' '500': $ref: '#/components/responses/InternalServerError' - put: - operationId: updateWebhookSubscription - summary: Update webhook subscription + '502': + $ref: '#/components/responses/BadGatewayError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + /v2/solana/faucet: + post: x-audience: public - x-required-permissions: - permissions: - - accounts:write@entity - enforcement: any + summary: Request funds on Solana devnet description: | - Update an existing webhook subscription's configuration including - event types, target URL, filtering criteria, and enabled status. - All required fields must be provided, even if they are not being changed. + Request funds from the CDP Faucet on Solana devnet. - ### Common Updates - - Change target URL or headers - - Add/remove event type filters - - Update multi-label filtering criteria - - Enable/disable subscription + Faucets are available for SOL, USDC, and CBTUSD. + + To prevent abuse, we enforce rate limits within a rolling 24-hour window to control the amount of funds that can be requested. + These limits are applied at both the CDP Project level and the blockchain address level. + A single blockchain address cannot exceed the specified limits, even if multiple users submit requests to the same address. + + | Token | Amount per Faucet Request |Rolling 24-hour window Rate Limits| + |:-----: |:-------------------------:|:--------------------------------:| + | SOL | 0.00125 SOL | 0.0125 SOL | + | USDC | 1 USDC | 10 USDC | + | CBTUSD | 1 CBTUSD | 10 CBTUSD | + operationId: requestSolanaFaucet tags: - - Webhooks + - Faucets security: - apiKeyAuth: [] - parameters: - - name: subscriptionId - in: path - required: true - description: Unique identifier for the webhook subscription. - schema: - type: string - format: uuid - example: 123e4567-e89b-12d3-a456-426614174000 requestBody: - required: true content: application/json: schema: - $ref: '#/components/schemas/WebhookSubscriptionUpdateRequest' + type: object + properties: + address: + type: string + description: The address to request funds to, which is a base58-encoded string. + pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ + example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + token: + type: string + description: The token to request funds for. + enum: + - sol + - usdc + - cbtusd + example: sol + required: + - address + - token responses: '200': - description: Webhook subscription updated successfully. + description: Successfully requested funds. content: application/json: schema: - $ref: '#/components/schemas/WebhookSubscriptionResponse' + type: object + properties: + transactionSignature: + type: string + description: The signature identifying the transaction that requested the funds. + example: 4dje1d24iG2FfxwxTJJt8VSTtYXNc6AAuJwngtL97TJSqqPD3pgRZ7uh4szoU6WDrKyFTBgaswkDrCr7BqWjQqqK + required: + - transactionSignature '400': - description: Invalid subscription update configuration. + description: Invalid request. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - invalid_url: + invalid_address_format: value: errorType: invalid_request - errorMessage: Target URL must be a valid HTTPS endpoint - invalid_event_types: + errorMessage: 'request body has an error: doesn''t match schema: Error at "address": string doesn''t match the regular expression "^[1-9A-HJ-NP-Za-km-z]{32,44}$".' + invalid_request: value: errorType: invalid_request - errorMessage: Event types must be non-empty and contain valid event type names - '401': - $ref: '#/components/responses/UnauthorizedError' - '404': - description: Webhook subscription not found. + errorMessage: Unable to request faucet funds for this address. + '403': + description: Access to resource forbidden. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - subscription_not_found: + forbidden: value: - errorType: not_found - errorMessage: Webhook subscription not found + errorType: forbidden + errorMessage: Unable to request faucet funds for this address. '429': description: Rate limit exceeded. content: @@ -8358,180 +8817,247 @@ paths: schema: $ref: '#/components/schemas/Error' examples: - rate_limit_exceeded: + faucet_limit_exceeded: value: - errorType: rate_limit_exceeded - errorMessage: Too many requests. Please try again later. + errorType: faucet_limit_exceeded + errorMessage: Faucet limit reached for this address. Please try again later. '500': $ref: '#/components/responses/InternalServerError' - delete: - operationId: deleteWebhookSubscription - summary: Delete webhook subscription + '502': + $ref: '#/components/responses/BadGatewayError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + /v2/solana/token-balances/{network}/{address}: + get: x-audience: public - x-required-permissions: - permissions: - - accounts:write@entity - enforcement: any - description: | - Permanently delete a webhook subscription and stop all event deliveries. - This action cannot be undone. + summary: List Solana token balances + description: |- + Lists the token balances of a Solana address on a given network. The balances include SPL tokens and the native SOL token. The response is paginated, and by default, returns 20 balances per page. - ### Important Notes - - All webhook deliveries will cease immediately - - Subscription cannot be recovered after deletion - - Consider disabling instead of deleting for temporary pauses + **Note:** This endpoint is still under development and does not yet provide strong availability or freshness guarantees. Freshness and availability of new token balances will improve over the coming weeks. + operationId: listSolanaTokenBalances tags: - - Webhooks + - Solana Token Balances security: - apiKeyAuth: [] parameters: - - name: subscriptionId + - name: address + description: The base58 encoded Solana address to get balances for. in: path required: true - description: Unique identifier for the webhook subscription. schema: type: string - format: uuid - example: 123e4567-e89b-12d3-a456-426614174000 + pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ + example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + - name: network + description: The human-readable network name to get the balances for. + in: path + required: true + schema: + $ref: '#/components/schemas/ListSolanaTokenBalancesNetwork' + example: solana + - name: pageSize + description: The number of balances to return per page. + in: query + required: false + schema: + type: integer + default: 20 + example: 10 + - name: pageToken + description: The token for the next page of balances. Will be empty if there are no more balances to fetch. + in: query + required: false + schema: + type: string + example: eyJsYXN0X2lkIjogImFiYzEyMyIsICJ0aW1lc3RhbXAiOiAxNzA3ODIzNzAxfQ== responses: - '204': - description: Webhook subscription deleted successfully. - '401': - $ref: '#/components/responses/UnauthorizedError' - '404': - description: Webhook subscription not found. + '200': + description: Successfully listed token balances. + content: + application/json: + schema: + allOf: + - type: object + required: + - balances + properties: + balances: + type: array + items: + $ref: '#/components/schemas/SolanaTokenBalance' + description: The list of Solana token balances. + example: + - amount: + amount: '1250000000' + decimals: 9 + token: + symbol: SOL + name: Solana + mintAddress: So11111111111111111111111111111111111111111 + - amount: + amount: '123456000' + decimals: 6 + token: + symbol: USDC + name: USD Coin + mintAddress: 4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU + - $ref: '#/components/schemas/ListResponse' + '400': + description: Invalid request. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - subscription_not_found: + invalid_request: value: - errorType: not_found - errorMessage: Webhook subscription not found - '429': - description: Rate limit exceeded. + errorType: invalid_request + errorMessage: string doesn't match the regular expression "^[1-9A-HJ-NP-Za-km-z]{32,44}$". + '404': + description: Not found. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - rate_limit_exceeded: + not_found: value: - errorType: rate_limit_exceeded - errorMessage: Too many requests. Please try again later. + errorType: not_found + errorMessage: Address not found, or no balances found for the given address on this chain. '500': $ref: '#/components/responses/InternalServerError' - /v2/data/webhooks/subscriptions/{subscriptionId}/events: - get: - operationId: listWebhookSubscriptionEvents - summary: List webhook subscription events + '502': + $ref: '#/components/responses/BadGatewayError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + /v2/data/query/run: + post: + operationId: runSQLQuery + summary: Run SQL Query x-audience: public - x-required-permissions: - permissions: - - accounts:read@entity - enforcement: any description: | - Retrieve webhook event delivery attempts for a specific subscription. - Returns event deliveries in descending order by creation time (newest first), - including delivery status, retry count, and response details. + Run a read-only SQL query against indexed blockchain data including transactions, events, and decoded logs. - ### Use Cases - - Debug webhook delivery failures and inspect response codes - - Monitor delivery status and retry counts - - Audit event delivery history for a subscription - - Verify that expected events were sent to webhook URLs + This endpoint provides direct SQL access to comprehensive blockchain data across supported networks. - ### Filtering - Use optional query parameters to narrow results: - - `eventId` — find a specific event by ID - - `minCreatedAt` / `maxCreatedAt` — filter by time range - - `eventTypeNames` — filter by event type (comma-separated) + Queries are executed against optimized data structures for high-performance analytics. - **Note:** Results are limited to the 50 most recent events (newest first). No pagination is supported. + ### Allowed Queries + + - Standard SQL syntax (CoinbaSeQL dialect, based on ClickHouse dialect) + - Read-only queries (SELECT statements) + - No DDL or DML operations + - Query that follow limits (defined below) + + ### Supported Tables + + - `.events` - Base mainnet decoded event logs with parameters, event signature, topics, and more. + - `.transactions` - Base mainnet transaction data including hash, block number, gas usage. + - `.blocks` - Base mainnet block information. + - `.encoded_logs` - Encoded log data of event logs that aren't able to be decoded by our event decoder (ex: log0 opcode). + - `.decoded_user_operations` - Decoded user operations data including hash, block number, gas usage, builder codes, entrypoint version, and more. + - `.transaction_attributions` - Information about the attributions of a transaction to a builder and associated builder codes. + + ### Supported Networks + + - Base Mainnet: `base` + - Base Sepolia: `base_sepolia` + + So for example, valid tables are: `base.events`, `base_sepolia.events`, `base.transactions`, etc. + + ### Query Limits + + - Maximum result set: 50,000 rows + - Maximum query length: 10,000 characters + - Maximum on-disk data to read: 100GB + - Maximum memory usage: 15GB + - Query timeout: 30 seconds + - Maximum JOINs: 12 + + ### Query Caching + + By default, each query result is returned from cache so long as the result is from an identical query and less than 750ms old. This freshness tolerance can be modified upwards, to a maximum of 900000ms (i.e. 900s, 15m). + This can be helpful for users who wish to reduce expensive calls to the SQL API by reusing cached results. tags: - - Webhooks + - SQL API security: - apiKeyAuth: [] - parameters: - - name: subscriptionId - in: path - required: true - description: Unique identifier for the webhook subscription. - schema: - type: string - format: uuid - example: 123e4567-e89b-12d3-a456-426614174000 - - name: eventId - in: query - required: false - description: Filter by a specific event ID. - schema: - type: string - format: uuid - example: a1b2c3d4-e5f6-7890-abcd-ef1234567890 - - name: minCreatedAt - in: query - required: false - description: Filter events created at or after this timestamp (RFC 3339 format). - schema: - type: string - format: date-time - example: '2025-01-15T00:00:00Z' - - name: maxCreatedAt - in: query - required: false - description: Filter events created at or before this timestamp (RFC 3339 format). - schema: - type: string - format: date-time - example: '2025-01-16T00:00:00Z' - - name: eventTypeNames - in: query - required: false - description: Filter by event type names (comma-separated). - schema: - type: string - example: onchain.activity.detected + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/OnchainDataQuery' responses: '200': - description: Webhook events retrieved successfully. + description: Query run successfully. content: application/json: schema: - $ref: '#/components/schemas/WebhookEventListResponse' + $ref: '#/components/schemas/OnchainDataResult' '400': - description: Invalid request parameters. + $ref: '#/components/responses/InvalidSQLQueryError' + '401': + $ref: '#/components/responses/UnauthorizedError' + '402': + $ref: '#/components/responses/PaymentMethodRequiredError' + '408': + description: Query timeout. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - invalid_min_created_at: - value: - errorType: invalid_request - errorMessage: minCreatedAt must be a valid RFC 3339 timestamp - invalid_max_created_at: - value: - errorType: invalid_request - errorMessage: maxCreatedAt must be a valid RFC 3339 timestamp - unknown_event_type_names: + query_timeout: value: - errorType: invalid_request - errorMessage: 'Unknown event type names: invalid.event.type' - '401': - $ref: '#/components/responses/UnauthorizedError' - '404': - description: Webhook subscription not found. + errorType: timed_out + errorMessage: Query execution was cut off by the server. Please try again with a more efficient query. + '429': + description: Rate limit exceeded. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - subscription_not_found: + rate_limit_exceeded: value: - errorType: not_found - errorMessage: Webhook subscription not found + errorType: rate_limit_exceeded + errorMessage: Too many requests. Please try again later. + '499': + $ref: '#/components/responses/ClientClosedRequestError' + '500': + $ref: '#/components/responses/InternalServerError' + '504': + $ref: '#/components/responses/TimedOutError' + /v2/data/query/grammar: + get: + operationId: getSQLGrammar + summary: Get SQL grammar + x-audience: public + description: | + Retrieve the SQL grammar for the SQL API. + + The SQL queries that are supported by the SQL API are defined in ANTLR4 grammar which is evaluated by server before executing the query. This ensures the safety and soundness of the SQL query before execution. + + This endpoint returns the ANTLR4 grammar that is used to evaluate the SQL queries so that developers can understand the SQL API and build SQL queries with high confidence and correctness. + + LLMs interact well with ANTLR4 grammar. You can feed the grammar directly into the LLMs to help generate SQL queries. + tags: + - SQL API + security: + - apiKeyAuth: [] + responses: + '200': + description: SQL grammar retrieved successfully. + content: + application/json: + schema: + type: string + description: The ANTLR4 grammar for the SQL API. + example: 'grammar SqlQuery; query: cteClause? unionStatement SEMICOLON? EOF;' + '401': + $ref: '#/components/responses/UnauthorizedError' '429': description: Rate limit exceeded. content: @@ -8545,380 +9071,182 @@ paths: errorMessage: Too many requests. Please try again later. '500': $ref: '#/components/responses/InternalServerError' - /v2/x402/verify: - post: + '504': + $ref: '#/components/responses/TimedOutError' + /v2/data/query/schema: + get: + operationId: getSQLSchema + summary: Get schema details x-audience: public - summary: Verify a payment - description: Verify an x402 protocol payment with a specific scheme and network. - operationId: verifyX402Payment + description: | + Retrieve the schema information for the available tables in the SQL API's indexed data. + + This includes table names, column definitions, data types, and indexed fields. tags: - - x402 Facilitator + - SQL API security: - apiKeyAuth: [] - requestBody: - required: true - content: - application/json: - schema: - type: object - properties: - x402Version: - $ref: '#/components/schemas/X402Version' - paymentPayload: - $ref: '#/components/schemas/x402PaymentPayload' - paymentRequirements: - $ref: '#/components/schemas/x402PaymentRequirements' - required: - - x402Version - - paymentPayload - - paymentRequirements - responses: - '200': - $ref: '#/components/responses/x402VerifyResponse' - '400': - $ref: '#/components/responses/x402VerifyInvalidError' - '500': - $ref: '#/components/responses/InternalServerError' - '502': - $ref: '#/components/responses/BadGatewayError' - '503': - $ref: '#/components/responses/ServiceUnavailableError' - /v2/x402/settle: - post: - x-audience: public - summary: Settle a payment - description: Settle an x402 protocol payment with a specific scheme and network. - operationId: settleX402Payment - tags: - - x402 Facilitator - security: - - apiKeyAuth: [] - requestBody: - required: true - content: - application/json: - schema: - type: object - properties: - x402Version: - $ref: '#/components/schemas/X402Version' - paymentPayload: - $ref: '#/components/schemas/x402PaymentPayload' - paymentRequirements: - $ref: '#/components/schemas/x402PaymentRequirements' - required: - - x402Version - - paymentPayload - - paymentRequirements - responses: - '200': - $ref: '#/components/responses/x402SettleResponse' - '400': - $ref: '#/components/responses/x402SettleError' - '402': - $ref: '#/components/responses/PaymentMethodRequiredError' - '500': - $ref: '#/components/responses/InternalServerError' - '502': - $ref: '#/components/responses/BadGatewayError' - '503': - $ref: '#/components/responses/ServiceUnavailableError' - /v2/x402/supported: - get: - x-audience: public - summary: Get supported payment schemes and networks - description: Get the supported x402 protocol payment schemes and networks that the facilitator is able to verify and settle payments for. - operationId: supportedX402PaymentKinds - tags: - - x402 Facilitator - security: - - apiKeyAuth: [] - responses: - '200': - $ref: '#/components/responses/x402SupportedPaymentKindsResponse' - '500': - $ref: '#/components/responses/InternalServerError' - '502': - $ref: '#/components/responses/BadGatewayError' - '503': - $ref: '#/components/responses/ServiceUnavailableError' - /v2/x402/discovery/resources: - get: - x-audience: public - summary: List discovered x402 resources - description: |- - Lists all active discovered x402 resources. - This endpoint returns resources that have been discovered and cached by the x402 facilitator, including their payment requirements and metadata. - The response is paginated, and by default, returns 100 items per page. - operationId: listX402DiscoveryResources - tags: - - x402 Facilitator - security: - - unauthenticated: [] parameters: - - name: type + - name: database in: query - description: |- - Filter by protocol type (e.g., "http", "mcp"). - Currently, the only supported protocol type is "http". required: false + description: The name of the database to query. Defaults to "base" when not specified. schema: type: string - example: http - - name: limit - in: query - description: The number of discovered x402 resources to return per page. - required: false - schema: - type: integer - default: 100 - example: 50 - - name: offset + enum: + - base + - base_sepolia + default: base + example: base + - name: table in: query - description: The offset of the first discovered x402 resource to return. required: false + description: Get the schema for a specific table. schema: - type: integer - default: 0 - example: 0 + type: string + example: events responses: '200': - description: Successfully retrieved discovery list. - content: - application/json: - schema: - $ref: '#/components/schemas/x402DiscoveryResourcesResponse' - '400': - description: Invalid request. + description: Schema information retrieved successfully. content: application/json: schema: - $ref: '#/components/schemas/Error' - examples: - invalid_request: - value: - errorType: invalid_request - errorMessage: Invalid request. Please check the request parameters. + $ref: '#/components/schemas/OnchainDataSchemaResponse' + '401': + $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - '502': - $ref: '#/components/responses/BadGatewayError' - '503': - $ref: '#/components/responses/ServiceUnavailableError' - /v2/x402/discovery/merchant: + /v2/data/evm/token-ownership/{network}/{address}: get: + operationId: listTokensForAccount + summary: List token addresses for account x-audience: public - summary: List merchant discovery info - description: |- - Gets x402 merchant discovery information for a given merchant payment address. - This endpoint returns all active x402 resources associated with the specified `payTo` address, allowing clients to discover what payment-gated resources a merchant exposes and their corresponding payment requirements. - The response is paginated, and by default, returns 20 items per page. - operationId: listX402DiscoveryMerchant + description: | + Retrieve all ERC-20 token contract addresses that an account has ever received tokens from. + Analyzes transaction history to discover token interactions. tags: - - x402 Facilitator + - Onchain Data security: - - unauthenticated: [] + - apiKeyAuth: [] parameters: - - name: payTo - in: query - description: |- - The merchant's payment address to look up. - This is the onchain address that payment requirements route funds to. + - name: network + in: path required: true + description: The blockchain network to query. schema: - $ref: '#/components/schemas/BlockchainAddress' - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - - name: limit - in: query - description: The number of resources to return per page. - required: false - schema: - type: integer - default: 20 - example: 20 - - name: offset - in: query - description: The offset of the first resource to return. - required: false + type: string + enum: + - base + - base-sepolia + example: base + - name: address + in: path + required: true + description: The account address to analyze for token interactions. schema: - type: integer - default: 0 - example: 0 + type: string + pattern: ^0x[0-9a-fA-F]{40}$ + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' responses: '200': - description: Successfully retrieved merchant discovery info. + description: Token addresses retrieved successfully. content: application/json: schema: - $ref: '#/components/schemas/x402DiscoveryMerchantResponse' + $ref: '#/components/schemas/AccountTokenAddressesResponse' '400': - description: Invalid request. + description: Invalid account address format. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - invalid_request: + invalid_address: value: errorType: invalid_request - errorMessage: Invalid request. Please check the request parameters. - '404': - description: Merchant not found. + errorMessage: Invalid account address format. Address must be 40 hex characters prefixed with '0x'. + '401': + $ref: '#/components/responses/UnauthorizedError' + '429': + description: Rate limit exceeded. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - not_found: + rate_limit_exceeded: value: - errorType: not_found - errorMessage: No resources found for the specified payTo address. + errorType: rate_limit_exceeded + errorMessage: Too many requests. Please try again later. '500': $ref: '#/components/responses/InternalServerError' - '502': - $ref: '#/components/responses/BadGatewayError' - '503': - $ref: '#/components/responses/ServiceUnavailableError' - /v2/x402/discovery/search: + /v2/data/evm/token-balances/{network}/{address}: get: + summary: List EVM token balances x-audience: public - summary: Search x402 resources description: |- - Searches for active x402 resources using a text query and optional filters. - Supports both text-based and vector-based search depending on availability. Results are sorted by relevance and quality score. - Legacy network names (e.g., `base`, `base-sepolia`, `solana`) are automatically normalized to their CAIP-2 equivalents. - The response is limited to 20 items per request. If more results exist, `partialResults` will be `true`. - operationId: searchX402Resources + Lists the token balances of an EVM address on a given network. The balances include ERC-20 tokens and the native gas token (usually ETH). The response is paginated, and by default, returns 20 balances per page. + + **Note:** This endpoint provides <1 second freshness from chain tip, <500ms response latency for wallets with reasonable token history, and 99.9% uptime for production use. + operationId: listDataTokenBalances tags: - - x402 Facilitator + - Onchain Data security: - - unauthenticated: [] + - apiKeyAuth: [] parameters: - - name: query - in: query - description: Full-text or semantic search query to find matching resources. - required: false + - name: address + description: The 0x-prefixed EVM address to get balances for. The address does not need to be checksummed. + in: path + required: true schema: type: string - maxLength: 400 - example: weather forecast + pattern: ^0x[0-9a-fA-F]{40}$ + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - name: network - in: query - description: |- - Filter results by network in CAIP-2 format (e.g., `eip155:8453`) or legacy name (e.g., `base`, `base-sepolia`, `solana`). - Legacy names are normalized to their CAIP-2 equivalents before filtering. - required: false - schema: - type: string - example: eip155:8453 - - name: asset - in: query - description: |- - Filter results by asset address. - For EVM networks, provide a 0x-prefixed EVM address. For Solana networks, provide a base58-encoded address. - Matching is case-insensitive. - required: false - schema: - type: string - example: '0x036CbD53842c5426634e7929541eC2318f3dCF7e' - - name: scheme - in: query - description: Filter results by payment scheme (e.g., `exact`). - required: false - schema: - type: string - example: exact - - name: payTo - in: query - description: |- - Filter results by the merchant's payment address. - For EVM networks, provide a 0x-prefixed EVM address. For Solana networks, provide a base58-encoded address. - required: false - schema: - $ref: '#/components/schemas/BlockchainAddress' - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - - name: urlSubstring - in: query - description: |- - Filter results to resources whose URL contains this value (case-insensitive substring match against the resource URL). - Useful for narrowing results to a specific domain, subdomain, or path segment. Combine with `query` to perform semantic search restricted to a URL subset. - Tip: include enough of the URL to disambiguate (e.g. `api.example.com` rather than `example`) — a short substring may also match resources whose path contains the same string. - required: false - schema: - type: string - minLength: 3 - maxLength: 2048 - example: api.example.com - - name: maxUsdPrice - in: query - description: Filter results to resources with a USD price at or below this value. - required: false - schema: - type: string - example: '1.00' - - name: extensions - in: query - description: Filter results to resources that support the specified protocol extensions. Can be specified multiple times to filter by multiple extensions. - required: false - schema: - type: array - items: - type: string - example: - - bazaar - style: form - explode: true - - name: limit - in: query - description: |- - Maximum number of resources to return. Must be a positive integer no greater than 20. - Defaults to 20. - required: false + description: The human-readable network name to get the balances for. + in: path + required: true schema: - type: integer - default: 20 - maximum: 20 - minimum: 1 - example: 20 + $ref: '#/components/schemas/ListEvmTokenBalancesNetwork' + example: base + - $ref: '#/components/parameters/PageSize' + - $ref: '#/components/parameters/PageToken' responses: '200': - description: Successfully retrieved matching x402 resources. + description: Successfully listed token balances. content: application/json: schema: - $ref: '#/components/schemas/x402SearchResourcesResponse' - examples: - search_results: - value: - x402Version: 2 - resources: - - resource: https://api.example.com/weather/forecast - description: Real-time weather forecast data. - type: http - x402Version: 2 - lastUpdated: '2024-01-15T10:30:00Z' - extensions: - bazaar: - info: - input: - type: http - method: GET - schema: {} - accepts: - - scheme: exact - network: eip155:8453 - amount: '1000000' - payTo: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - asset: '0x036CbD53842c5426634e7929541eC2318f3dCF7e' - maxTimeoutSeconds: 60 - quality: - l30DaysTotalCalls: 42 - l30DaysUniquePayers: 15 - lastCalledAt: '2024-01-15T10:30:00Z' - partialResults: false - searchMethod: text + allOf: + - type: object + required: + - balances + properties: + balances: + type: array + items: + $ref: '#/components/schemas/TokenBalance' + description: The list of EVM token balances. + example: + - amount: + amount: '1250000000000000000' + decimals: 18 + token: + network: base + symbol: ETH + name: ether + contractAddress: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE' + - amount: + amount: '123456' + decimals: 6 + token: + network: base + symbol: USDC + name: USD Coin + contractAddress: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' + - $ref: '#/components/schemas/ListResponse' '400': - description: Invalid request parameters. + description: Invalid request. content: application/json: schema: @@ -8927,917 +9255,1815 @@ paths: invalid_request: value: errorType: invalid_request - errorMessage: limit must be a positive integer + errorMessage: string doesn't match the regular expression "^0x[0-9a-fA-F]{40}$". + '404': + description: Not found. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + not_found: + value: + errorType: not_found + errorMessage: Address not found, or no balances found for the given address on this chain. '500': $ref: '#/components/responses/InternalServerError' '502': $ref: '#/components/responses/BadGatewayError' '503': $ref: '#/components/responses/ServiceUnavailableError' - /v2/x402/discovery/mcp: - post: + /v2/data/webhooks/subscriptions: + get: + operationId: listWebhookSubscriptions + summary: List webhook subscriptions x-audience: public - summary: Handle MCP JSON-RPC request - description: Handles JSON-RPC requests for the Model Context Protocol (MCP). Supports MCP methods for discovering x402 payment resources and tools. - operationId: postX402DiscoveryMcp + x-required-permissions: + permissions: + - accounts:read@entity + enforcement: any + description: | + Retrieve a paginated list of webhook subscriptions for the authenticated project. + Returns subscriptions for all CDP product events (onchain, onramp/offramp, wallet, etc.) + in descending order by creation time. + + ### Use Cases + - Monitor all active webhook subscriptions across CDP products + - Audit webhook configurations + - Manage subscription lifecycle tags: - - x402 Facilitator + - Webhooks security: - - unauthenticated: [] - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/x402McpRequest' + - apiKeyAuth: [] + parameters: + - name: pageSize + description: The number of subscriptions to return per page. + in: query + required: false + schema: + type: integer + default: 20 + minimum: 1 + maximum: 100 + example: 10 + - name: pageToken + description: The token for the next page of subscriptions, if any. + in: query + required: false + schema: + type: string + example: eyJsYXN0X2lkIjogImFiYzEyMyIsICJ0aW1lc3RhbXAiOiAxNzA3ODIzNzAxfQ== responses: '200': - description: MCP response. + description: Webhook subscriptions retrieved successfully. content: application/json: schema: - $ref: '#/components/schemas/x402McpResponse' + $ref: '#/components/schemas/WebhookSubscriptionListResponse' '400': - description: Invalid request. + description: Invalid request parameters. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - invalid_request: + invalid_page_size: value: errorType: invalid_request - errorMessage: Invalid JSON-RPC request. Please check the request format. + errorMessage: Page size must be between 1 and 100. + invalid_page_token: + value: + errorType: invalid_request + errorMessage: Invalid page token format. + '401': + $ref: '#/components/responses/UnauthorizedError' + '429': + description: Rate limit exceeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + rate_limit_exceeded: + value: + errorType: rate_limit_exceeded + errorMessage: Too many requests. Please try again later. '500': $ref: '#/components/responses/InternalServerError' - /v2/onramp/orders: post: + operationId: createWebhookSubscription + summary: Create webhook subscription x-audience: public - summary: Create an onramp order - description: |- - Create a new Onramp order or get a quote for an Onramp order. Either `paymentAmount` or `purchaseAmount` must be provided. + x-required-permissions: + permissions: + - accounts:write@entity + enforcement: any + description: | + Subscribe to real-time events across CDP products using flexible filtering. - This API currently only supports the payment method `GUEST_CHECKOUT_APPLE_PAY`. + ### Event Types - For detailed integration instructions and to get access to this API, refer to the [Apple Pay Onramp API docs](https://docs.cdp.coinbase.com/onramp-&-offramp/onramp-apis/apple-pay-onramp-api). - operationId: createOnrampOrder - tags: - - Onramp - security: - - apiKeyAuth: [] - requestBody: - content: - application/json: - schema: - type: object - properties: - agreementAcceptedAt: - description: The timestamp of when the user acknowledged that by using Coinbase Onramp they are accepting the Coinbase Terms (https://www.coinbase.com/legal/guest-checkout/us), User Agreement (https://www.coinbase.com/legal/user_agreement), and Privacy Policy (https://www.coinbase.com/legal/privacy). - format: date-time - type: string - example: '2025-04-24T00:00:00Z' - destinationAddress: - allOf: - - $ref: '#/components/schemas/BlockchainAddress' - description: The address the purchased crypto will be sent to. - destinationNetwork: - description: |- - The name of the crypto network the purchased currency will be sent on. + **Onchain Events** - Monitor Base mainnet with microsecond precision: + - `onchain.activity.detected` - Smart contract events, transfers, swaps, NFT activity + - **Requires** `labels` for filtering (e.g., `contract_address`, `event_name`) - Use the [Onramp Buy Options API](https://docs.cdp.coinbase.com/api-reference/rest-api/onramp-offramp/get-buy-options) to discover the supported networks for your user's location. - type: string - example: base - email: - description: The verified email address of the user requesting the onramp transaction. This email must be verified by your app (via OTP) before being used with the Onramp API. - type: string - example: test@example.com - isQuote: - description: If true, this API will return a quote without creating any transaction. - type: boolean - default: false - partnerOrderRef: - description: Optional partner order reference ID. - type: string - example: order-1234 - partnerUserRef: - description: |- - A unique string that represents the user in your app. This can be used to link individual transactions together so you can retrieve the transaction history for your users. Prefix this string with “sandbox-” (e.g. "sandbox-user-1234") to perform a sandbox transaction which will allow you to test your integration without any real transfer of funds. + **Onramp/Offramp Events** - Transaction lifecycle notifications: + - `onramp.transaction.created`, `onramp.transaction.updated` + - `onramp.transaction.success`, `onramp.transaction.failed` + - `offramp.transaction.created`, `offramp.transaction.updated` + - `offramp.transaction.success`, `offramp.transaction.failed` + - **No labels required** - maximum simplicity for transaction monitoring - This value can be used with with [Onramp User Transactions API](https://docs.cdp.coinbase.com/api-reference/rest-api/onramp-offramp/get-onramp-transactions-by-id) to retrieve all transactions created by the user. - type: string - example: user-1234 - paymentAmount: - description: A string representing the amount of fiat the user wishes to pay in exchange for crypto. When using this parameter, the returned quote will be inclusive of fees i.e. the user will pay this exact amount of the payment currency. - type: string - example: '100.00' - paymentCurrency: - description: The fiat currency to be converted to crypto. - type: string - example: USD - paymentMethod: - $ref: '#/components/schemas/OnrampOrderPaymentMethodTypeId' - phoneNumber: - description: |- - The phone number of the user requesting the onramp transaction in E.164 format. This phone number must be verified by your app (via OTP) before being used with the Onramp API. + **Payments Transfers Events** - Transfer lifecycle notifications: + - `payments.transfers.quoted` - Transfer created and awaiting execution + - `payments.transfers.processing` - Transfer execution in progress + - `payments.transfers.completed` - Transfer completed successfully + - `payments.transfers.failed` - Transfer failed + - `payments.transfers.travel_rule_incomplete` - Travel rule information is missing + - `payments.transfers.travel_rule_completed` - Travel rule information has been provided and the transfer will proceed + - **No labels required** - enable the transfers webhook to monitor status transitions - Please refer to the [Onramp docs](https://docs.cdp.coinbase.com/onramp-&-offramp/onramp-apis/apple-pay-onramp-api) for more details on phone number verification requirements and best practices. - type: string - example: '+12055555555' - phoneNumberVerifiedAt: - description: Timestamp of when the user's phone number was verified via OTP. User phone number must be verified every 60 days. If this timestamp is older than 60 days, an error will be returned. - format: date-time - type: string - example: '2025-04-24T00:00:00Z' - purchaseAmount: - description: A string representing the amount of crypto the user wishes to purchase. When using this parameter the returned quote will be exclusive of fees i.e. the user will receive this exact amount of the purchase currency. - type: string - example: '10.000000' - purchaseCurrency: - description: |- - The ticker (e.g. `BTC`, `USDC`, `SOL`) or the Coinbase UUID (e.g. `d85dce9b-5b73-5c3c-8978-522ce1d1c1b4`) of the crypto asset to be purchased. + **Wallet Events** - Wallet activity notifications: + - `wallet.activity.detected` - Use the [Onramp Buy Options API](https://docs.cdp.coinbase.com/api-reference/rest-api/onramp-offramp/get-buy-options) to discover the supported purchase currencies for your user's location. - type: string - example: USDC - clientIp: - description: The IP address of the end user requesting the onramp transaction. - type: string - example: 127.0.0.1 - domain: - description: The domain that the Apple Pay button will be rendered on. Required when using the `GUEST_CHECKOUT_APPLE_PAY` payment method and embedding the payment link in an iframe. - type: string - example: pay.coinbase.com - required: - - paymentCurrency - - purchaseCurrency - - paymentMethod - - destinationAddress - - destinationNetwork - - phoneNumber - - email - - agreementAcceptedAt - - phoneNumberVerifiedAt - - partnerUserRef + ### Webhook Signature Verification + All webhooks include cryptographic signatures for security. + The signature secret is returned in `secret` field when creating a subscription. + + **Note:** Webhooks are in beta and this interface is subject to change. + + See the [verification guide](https://docs.cdp.coinbase.com/onramp-&-offramp/webhooks#webhook-signature-verification) for implementation details. + + ### Onchain Label Filtering + + For `onchain.activity.detected` events, use `labels` for precise filtering with AND logic (max 20 labels per webhook). + + **Allowed labels** (all in snake_case format): + - `network` (required) - Blockchain network + - `contract_address` - Smart contract address + - `event_name` - Event name (e.g., "Transfer", "Burn") + - `event_signature` - Event signature hash + - `transaction_from` - Transaction sender address + - `transaction_to` - Transaction recipient address + - `params.*` - Any event parameter (e.g., `params.from`, `params.to`, `params.sender`, `params.tokenId`) + + **Examples**: + - **Liquidity Pool Monitor**: `{"network": "base-mainnet", "contract_address": "0xcd1f9777571493aeacb7eae45cd30a226d3e612d", "event_name": "Burn"}` + - **Price Oracle Tracker**: `{"network": "base-mainnet", "contract_address": "0xbac4a9428ea707c51f171ed9890c3c2fa810305d", "event_name": "PriceUpdated"}` + - **DeFi Protocol Activity**: `{"network": "base-mainnet", "contract_address": "0x45c6e6a47a711b14d8357d5243f46704904578e3", "event_name": "Deposit"}` + tags: + - Webhooks + security: + - apiKeyAuth: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/WebhookSubscriptionRequest' + examples: + onchain_liquidity_pool: + summary: 'Onchain: Monitor liquidity pool burns' + value: + description: Liquidity pool burn events. + eventTypes: + - onchain.activity.detected + labels: + network: base-mainnet + contract_address: '0xcd1f9777571493aeacb7eae45cd30a226d3e612d' + event_name: Burn + target: + url: https://api.example.com/webhooks + isEnabled: true + onramp_transactions: + summary: 'Onramp: Transaction lifecycle' + value: + description: Onramp transaction status webhook. + eventTypes: + - onramp.transaction.created + - onramp.transaction.updated + - onramp.transaction.success + - onramp.transaction.failed + labels: {} + target: + url: https://api.example.com/webhooks + isEnabled: true + offramp_transactions: + summary: 'Offramp: Transaction lifecycle' + value: + description: Offramp transaction status webhook. + eventTypes: + - offramp.transaction.created + - offramp.transaction.updated + - offramp.transaction.success + - offramp.transaction.failed + labels: {} + target: + url: https://api.example.com/webhooks + isEnabled: true + wallet_outgoing_transactions: + summary: 'Wallet: Monitor outgoing transactions' + value: + description: Outgoing transactions. + eventTypes: + - wallet.activity.detected + labels: + network: base-mainnet + params.from: '0xB7f5BF799fB265657c628ef4a13f90f83a3a616A' + target: + url: https://api.example.com/webhooks + isEnabled: true responses: '201': - description: Successfully created an onramp order. + description: Webhook subscription created successfully. content: application/json: schema: - type: object - properties: - order: - $ref: '#/components/schemas/OnrampOrder' - paymentLink: - $ref: '#/components/schemas/OnrampPaymentLink' - required: - - order + $ref: '#/components/schemas/WebhookSubscriptionResponse' '400': - description: Invalid request. + description: Invalid subscription configuration. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - invalid_request: + invalid_url: value: errorType: invalid_request - errorMessage: Missing required params. - network_not_tradable: - value: - errorType: network_not_tradable - errorMessage: The selected asset cannot be purchased on the selected network in the user's location. - guest_permission_denied: - value: - errorType: guest_permission_denied - errorMessage: The user is not allowed to complete onramp transactions as a guest. - guest_region_forbidden: - value: - errorType: guest_region_forbidden - errorMessage: Guest onramp transactions are not allowed in the user's region. - guest_transaction_limit: - value: - errorType: guest_transaction_limit - errorMessage: This transaction would exceed the user's weekly guest onramp transaction limit. - guest_transaction_count: - value: - errorType: guest_transaction_count - errorMessage: The user has reached the lifetime guest onramp transaction count limit (15). - phone_number_verification_expired: + errorMessage: Target URL must be a valid HTTPS endpoint. + invalid_event_types: value: - errorType: phone_number_verification_expired - errorMessage: The user's phone number verification has expired. Please re-verify the user's phone number + errorType: invalid_request + errorMessage: Event types must be non-empty and contain valid event type names. '401': $ref: '#/components/responses/UnauthorizedError' '429': - $ref: '#/components/responses/RateLimitExceeded' + description: Rate limit exceeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + rate_limit_exceeded: + value: + errorType: rate_limit_exceeded + errorMessage: Too many requests. Please try again later. '500': $ref: '#/components/responses/InternalServerError' - /v2/onramp/orders/{orderId}: + /v2/data/webhooks/subscriptions/{subscriptionId}: get: + operationId: getWebhookSubscription + summary: Get webhook subscription x-audience: public - summary: Get an onramp order by ID - description: Get an onramp order by ID. - operationId: getOnrampOrderById + x-required-permissions: + permissions: + - accounts:read@entity + enforcement: any + description: | + Retrieve detailed information about a specific webhook subscription including + configuration, status, creation timestamp, and webhook signature secret. + + ### Response Includes + - Subscription configuration and filters + - Target URL and custom headers + - Webhook signature secret for verification + - Creation timestamp and status tags: - - Onramp + - Webhooks security: - apiKeyAuth: [] parameters: - - name: orderId + - name: subscriptionId in: path required: true - description: The ID of the onramp order to retrieve. + description: Unique identifier for the webhook subscription. schema: type: string + format: uuid example: 123e4567-e89b-12d3-a456-426614174000 responses: '200': - description: Successfully retrieved an onramp order. + description: Webhook subscription details retrieved successfully. content: application/json: schema: - type: object - properties: - order: - $ref: '#/components/schemas/OnrampOrder' - required: - - order + $ref: '#/components/schemas/WebhookSubscriptionResponse' '401': $ref: '#/components/responses/UnauthorizedError' '404': - description: Order not found. + description: Webhook subscription not found. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - not_found: + subscription_not_found: value: errorType: not_found - errorMessage: Order with the given ID does not exist. + errorMessage: Webhook subscription not found. '429': - $ref: '#/components/responses/RateLimitExceeded' - /v2/onramp/sessions: - post: + description: Rate limit exceeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + rate_limit_exceeded: + value: + errorType: rate_limit_exceeded + errorMessage: Too many requests. Please try again later. + '500': + $ref: '#/components/responses/InternalServerError' + put: + operationId: updateWebhookSubscription + summary: Update webhook subscription x-audience: public - summary: Create an onramp session - description: |- - Returns a single-use URL for an Onramp session. This API provides flexible functionality based on the parameters provided, supporting three cases: - - **Important**: The returned URL is single-use only. Once a user visits the URL, no one else can access it. - ## Use Cases - ### 1. Basic Session (Minimum Parameters) - **Required**: `destinationAddress`, `purchaseCurrency`, `destinationNetwork` - - **Returns**: Basic single-use onramp URL. The `quote` object will not be included in the response. - ### 2. One-Click Onramp URL - **Required**: Basic parameters + (`paymentAmount` OR `purchaseAmount`), `paymentCurrency` - - **Returns**: One-click onramp URL for streamlined checkout. The `quote` object will not be included in the response. - ### 3. One-Click Onramp URL with Quote - **Required**: One-Click Onramp parameters + `paymentMethod`, `country`, `subdivision` - - **Returns**: Complete pricing quote and one-click onramp URL. Both `session` and `quote` objects will be included in the response. + x-required-permissions: + permissions: + - accounts:write@entity + enforcement: any + description: | + Update an existing webhook subscription's configuration including + event types, target URL, filtering criteria, and enabled status. + All required fields must be provided, even if they are not being changed. - **Note**: Only one of `paymentAmount` or `purchaseAmount` should be provided, not both. Providing both will result in an error. When `paymentAmount` is provided, the quote shows how much crypto the user will receive for the specified fiat amount (fee-inclusive). When `purchaseAmount` is provided, the quote shows how much fiat the user needs to pay for the specified crypto amount (fee-exclusive). - operationId: createOnrampSession + ### Common Updates + - Change target URL or headers + - Add/remove event type filters + - Update multi-label filtering criteria + - Enable/disable subscription tags: - - Onramp + - Webhooks security: - apiKeyAuth: [] + parameters: + - name: subscriptionId + in: path + required: true + description: Unique identifier for the webhook subscription. + schema: + type: string + format: uuid + example: 123e4567-e89b-12d3-a456-426614174000 requestBody: + required: true content: application/json: schema: - type: object - properties: - purchaseCurrency: - description: |- - The ticker (e.g. `BTC`, `USDC`, `SOL`) or the Coinbase UUID (e.g. `d85dce9b-5b73-5c3c-8978-522ce1d1c1b4`) of the crypto asset to be purchased. - - Use the [Onramp Buy Options API](https://docs.cdp.coinbase.com/api-reference/rest-api/onramp-offramp/get-buy-options) to discover the supported purchase currencies for your user's location. - type: string - example: USDC - destinationNetwork: - description: |- - The name of the crypto network the purchased currency will be sent on. - - Use the [Onramp Buy Options API](https://docs.cdp.coinbase.com/api-reference/rest-api/onramp-offramp/get-buy-options) to discover the supported networks for your user's location. - type: string - example: base - destinationAddress: - allOf: - - $ref: '#/components/schemas/BlockchainAddress' - description: The address the purchased crypto will be sent to. - paymentAmount: - description: A string representing the amount of fiat the user wishes to pay in exchange for crypto. When using this parameter, the returned quote will be inclusive of fees i.e. the user will pay this exact amount of the payment currency. - type: string - example: '100.00' - purchaseAmount: - description: A string representing the amount of crypto the user wishes to purchase. When using this parameter, the returned quote will be exclusive of fees i.e. the user will receive this exact amount of the purchase currency. - type: string - example: '10.000000' - paymentCurrency: - description: The fiat currency to be converted to crypto. - type: string - example: USD - paymentMethod: - $ref: '#/components/schemas/OnrampQuotePaymentMethodTypeId' - country: - description: The ISO 3166-1 two letter country code (e.g. US). - type: string - example: US - subdivision: - description: The ISO 3166-2 two letter state code (e.g. NY). Only required for US. - type: string - example: NY - redirectUrl: - allOf: - - $ref: '#/components/schemas/Uri' - description: URI to redirect the user to when they successfully complete a transaction. This URI will be embedded in the returned onramp URI as a query parameter. - example: https://example.com/success - clientIp: - description: The IP address of the end user requesting the onramp transaction. - type: string - example: 127.0.0.1 - partnerUserRef: - description: |- - A unique string that represents the user in your app. This can be used to link individual transactions together so you can retrieve the transaction history for your users. Prefix this string with “sandbox-” (e.g. "sandbox-user-1234") to perform a sandbox transaction which will allow you to test your integration without any real transfer of funds. - - This value can be used with with [Onramp User Transactions API](https://docs.cdp.coinbase.com/api-reference/rest-api/onramp-offramp/get-onramp-transactions-by-id) to retrieve all transactions created by the user. - type: string - example: user-1234 - required: - - destinationAddress - - purchaseCurrency - - destinationNetwork + $ref: '#/components/schemas/WebhookSubscriptionUpdateRequest' responses: - '201': - description: Onramp session created successfully. + '200': + description: Webhook subscription updated successfully. content: application/json: schema: - type: object - properties: - session: - $ref: '#/components/schemas/OnrampSession' - quote: - $ref: '#/components/schemas/OnrampQuote' - required: - - session + $ref: '#/components/schemas/WebhookSubscriptionResponse' '400': - description: Invalid request. + description: Invalid subscription update configuration. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - invalid_request: + invalid_url: value: errorType: invalid_request - errorMessage: Missing required parameters. - invalid_destination_address: + errorMessage: Target URL must be a valid HTTPS endpoint. + invalid_event_types: value: errorType: invalid_request - errorMessage: The destination address is not valid for the specified network. + errorMessage: Event types must be non-empty and contain valid event type names. '401': $ref: '#/components/responses/UnauthorizedError' - '429': - $ref: '#/components/responses/RateLimitExceeded' - '500': - $ref: '#/components/responses/InternalServerError' - /v2/onramp/limits: - post: - summary: Get onramp user limits - x-audience: public - description: |- - Returns the transaction limits for an onramp user based on their payment method and user identifier. Use this API to show users their remaining purchase capacity before initiating an onramp transaction. - Currently supports `GUEST_CHECKOUT_APPLE_PAY` payment method with phone number identification. The phone number must have been previously verified via OTP. - operationId: getOnrampUserLimits - tags: - - Onramp - security: - - apiKeyAuth: [] - requestBody: - content: - application/json: - schema: - type: object - properties: - paymentMethodType: - $ref: '#/components/schemas/OnrampOrderPaymentMethodTypeId' - userId: - type: string - description: The user identifier value. For `phone_number` type, this must be in E.164 format. - example: '+12055555555' - userIdType: - $ref: '#/components/schemas/OnrampUserIdType' - required: - - paymentMethodType - - userId - - userIdType - responses: - '200': - description: Successfully retrieved user limits. + '404': + description: Webhook subscription not found. content: application/json: schema: - type: object - properties: - limits: - type: array - description: The list of limits applicable to the user. - items: - $ref: '#/components/schemas/OnrampUserLimit' - required: - - limits + $ref: '#/components/schemas/Error' examples: - default: + subscription_not_found: value: - limits: - - limitType: weekly_spending - currency: USD - limit: '500' - remaining: '400' - - limitType: lifetime_transactions - limit: '15' - remaining: '12' - '400': - description: Invalid request. + errorType: not_found + errorMessage: Webhook subscription not found. + '429': + description: Rate limit exceeded. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - invalid_request: + rate_limit_exceeded: value: - errorType: invalid_request - errorMessage: Must provide a valid payment method type and user identifier. - '401': - $ref: '#/components/responses/UnauthorizedError' - '429': - $ref: '#/components/responses/RateLimitExceeded' + errorType: rate_limit_exceeded + errorMessage: Too many requests. Please try again later. '500': $ref: '#/components/responses/InternalServerError' - /v2/onramp/limits/upgrade: - post: - summary: Request limit upgrade + delete: + operationId: deleteWebhookSubscription + summary: Delete webhook subscription x-audience: public - description: |- - Requests a limit upgrade for an onramp user by submitting identity information. Only phone number is currently supported as a userId. - - The verification process is asynchronous. After calling this endpoint, use the [Get Onramp User Limits](https://docs.cdp.coinbase.com/api-reference/v2/rest-api/onramp/get-onramp-user-limits) endpoint to check the status in the `limitUpgradeOptions` array. - - **Prerequisites:** - - The phone number must have been previously verified by your app via OTP. - Upgrades may not be available until a certain number of successful transactions by the user. - - **Supported fields:** - - `ssnLast4`: Last 4 digits of the Social Security Number (no dashes or spaces). - - `dateOfBirth`: Date of birth (day, month, year as zero-padded strings). - operationId: requestLimitsUpgrade + x-required-permissions: + permissions: + - accounts:write@entity + enforcement: any + description: | + Permanently delete a webhook subscription and stop all event deliveries. + This action cannot be undone. + + ### Important Notes + - All webhook deliveries will cease immediately + - Subscription cannot be recovered after deletion + - Consider disabling instead of deleting for temporary pauses tags: - - Onramp + - Webhooks security: - apiKeyAuth: [] - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/OnrampLimitUpgradeRequest' - example: - userId: '+12055555555' - userIdType: phone_number - fields: - ssnLast4: '5678' - dateOfBirth: - day: '15' - month: '08' - year: '1990' + parameters: + - name: subscriptionId + in: path + required: true + description: Unique identifier for the webhook subscription. + schema: + type: string + format: uuid + example: 123e4567-e89b-12d3-a456-426614174000 responses: - '202': - description: Limit upgrade request accepted. + '204': + description: Webhook subscription deleted successfully. + '401': + $ref: '#/components/responses/UnauthorizedError' + '404': + description: Webhook subscription not found. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + subscription_not_found: + value: + errorType: not_found + errorMessage: Webhook subscription not found. + '429': + description: Rate limit exceeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + rate_limit_exceeded: + value: + errorType: rate_limit_exceeded + errorMessage: Too many requests. Please try again later. + '500': + $ref: '#/components/responses/InternalServerError' + /v2/data/webhooks/subscriptions/{subscriptionId}/events: + get: + operationId: listWebhookSubscriptionEvents + summary: List webhook subscription events + x-audience: public + x-required-permissions: + permissions: + - accounts:read@entity + enforcement: any + description: | + Retrieve webhook event delivery attempts for a specific subscription. + Returns event deliveries in descending order by creation time (newest first), + including delivery status, retry count, and response details. + + ### Use Cases + - Debug webhook delivery failures and inspect response codes + - Monitor delivery status and retry counts + - Audit event delivery history for a subscription + - Verify that expected events were sent to webhook URLs + + ### Filtering + Use optional query parameters to narrow results: + - `eventId` — find a specific event by ID + - `minCreatedAt` / `maxCreatedAt` — filter by time range + - `eventTypeNames` — filter by event type (comma-separated) + + **Note:** Results are limited to the 50 most recent events (newest first). No pagination is supported. + tags: + - Webhooks + security: + - apiKeyAuth: [] + parameters: + - name: subscriptionId + in: path + required: true + description: Unique identifier for the webhook subscription. + schema: + type: string + format: uuid + example: 123e4567-e89b-12d3-a456-426614174000 + - name: eventId + in: query + required: false + description: Filter by a specific event ID. + schema: + type: string + format: uuid + example: a1b2c3d4-e5f6-7890-abcd-ef1234567890 + - name: minCreatedAt + in: query + required: false + description: Filter events created at or after this timestamp (RFC 3339 format). + schema: + type: string + format: date-time + example: '2025-01-15T00:00:00Z' + - name: maxCreatedAt + in: query + required: false + description: Filter events created at or before this timestamp (RFC 3339 format). + schema: + type: string + format: date-time + example: '2025-01-16T00:00:00Z' + - name: eventTypeNames + in: query + required: false + description: Filter by event type names (comma-separated). + schema: + type: string + example: onchain.activity.detected + responses: + '200': + description: Webhook events retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/WebhookEventListResponse' '400': - description: Invalid request. + description: Invalid request parameters. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - invalid_request: + invalid_min_created_at: value: errorType: invalid_request - errorMessage: Invalid user identifier or fields. + errorMessage: minCreatedAt must be a valid RFC 3339 timestamp. + invalid_max_created_at: + value: + errorType: invalid_request + errorMessage: maxCreatedAt must be a valid RFC 3339 timestamp. + unknown_event_type_names: + value: + errorType: invalid_request + errorMessage: 'Unknown event type names: invalid.event.type.' '401': $ref: '#/components/responses/UnauthorizedError' + '404': + description: Webhook subscription not found. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + subscription_not_found: + value: + errorType: not_found + errorMessage: Webhook subscription not found. '429': - $ref: '#/components/responses/RateLimitExceeded' + description: Rate limit exceeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + rate_limit_exceeded: + value: + errorType: rate_limit_exceeded + errorMessage: Too many requests. Please try again later. '500': $ref: '#/components/responses/InternalServerError' -webhooks: {} -components: - securitySchemes: - apiKeyAuth: - type: http - scheme: bearer - bearerFormat: JWT - description: A JWT signed using your CDP API Key Secret, encoded in base64. Refer to the [Generate Bearer Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-bearer-token) section of our Authentication docs for information on how to generate your Bearer Token. - endUserAuth: + /v2/x402/verify: + post: x-audience: public - type: http - scheme: bearer - bearerFormat: JWT - description: A JWT signed using the developer's own JWT private key (in the case of JWT authentication), or an end user JWT signed by CDP, encoded in base64. This is used for End User Account APIs. - unauthenticated: + summary: Verify payment + description: Verify an x402 protocol payment with a specific scheme and network. + operationId: verifyX402Payment + tags: + - x402 Facilitator + security: + - apiKeyAuth: [] + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + x402Version: + $ref: '#/components/schemas/X402Version' + paymentPayload: + $ref: '#/components/schemas/x402PaymentPayload' + paymentRequirements: + $ref: '#/components/schemas/x402PaymentRequirements' + required: + - x402Version + - paymentPayload + - paymentRequirements + responses: + '200': + $ref: '#/components/responses/x402VerifyResponse' + '400': + $ref: '#/components/responses/x402VerifyInvalidError' + '500': + $ref: '#/components/responses/InternalServerError' + '502': + $ref: '#/components/responses/BadGatewayError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + /v2/x402/settle: + post: x-audience: public - type: http - scheme: none - description: This security scheme is used for APIs that do not require authentication, such as End User Auth flows used to initiate authentication or public, read-only endpoints. - schemas: - EmailAuthentication: - type: object - title: EmailAuthentication - description: Information about an end user who authenticates using a one-time password sent to their email address. - properties: - type: - type: string - description: The type of authentication information. - example: email - enum: - - email - email: - type: string - description: The email address of the end user. - example: user@example.com - format: email - required: - - type - - email - SmsAuthentication: - type: object - title: SmsAuthentication - description: Information about an end user who authenticates using a one-time password sent to their phone number via SMS. - properties: - type: - type: string - description: The type of authentication information. - example: sms - enum: - - sms - phoneNumber: - type: string - description: The phone number of the end user in E.164 format. - example: '+12055555555' - pattern: ^\+[1-9]\d{1,14}$ - required: - - type - - phoneNumber - DeveloperJWTAuthentication: - type: object - title: DeveloperJWTAuthentication - description: Information about an end user who authenticates using a JWT issued by the developer. - properties: - type: - type: string - description: The type of authentication information. - enum: - - jwt - example: jwt - kid: - type: string - description: The key ID of the JWK used to sign the JWT. - example: NjVBRjY5MDlCMUIwNzU4RTA2QzZFMDQ4QzQ2MDAyQjVDNjk1RTM2Qg - sub: - type: string - description: The unique identifier for the end user that is captured in the `sub` claim of the JWT. - example: e051beeb-7163-4527-a5b6-35e301529ff2 - required: - - type - - sub - - kid - OAuth2ProviderType: - type: string - description: The type of OAuth2 provider. - enum: - - google - - apple - - x - - telegram - - github - example: google - OAuth2Authentication: - type: object - title: OAuth2Authentication - description: Information about an end user who authenticates using a third-party provider. - properties: - type: - $ref: '#/components/schemas/OAuth2ProviderType' - sub: - type: string - description: The unique identifier for the end user that is captured in the `sub` claim of the JWT. - example: e051beeb-7163-4527-a5b6-35e301529ff2 - email: - type: string - description: The email address of the end user contained within the user's ID token, if available from third-party OAuth2 provider's token exchange. - example: test.user@gmail.com - name: - type: string - description: The full name of the end user if available from third-party OAuth2 provider's token exchange. - example: Test User - username: - type: string - description: The username of the end user if available from third-party OAuth2 provider's token exchange. - example: test.user - required: - - type - - sub - TelegramAuthentication: - type: object - description: Information about an end user who authenticates using Telegram. - properties: - type: - $ref: '#/components/schemas/OAuth2ProviderType' - id: - type: integer - description: The Telegram ID for the end user. - example: 123456 - firstName: - type: string - description: The Telegram user's first name. - example: Satoshi - lastName: - type: string - description: The Telegram user's last name. - example: Nakamoto - photoUrl: - type: string - description: The Telegram user's profile picture. - example: https://image.url/profile.png - authDate: - type: integer - description: The Telegram user's last login as a Unix timestamp. - example: 1770681412 - username: - type: string - description: The Telegram user's username. - example: satoshinakamoto - required: - - type - - id - - authDate - BlockchainAddress: - type: string - minLength: 1 - maxLength: 128 - description: A blockchain address. Format varies by network (e.g., 0x-prefixed for EVM, base58 for Solana). - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - SiweAuthentication: - type: object - title: SiweAuthentication - description: Information about an end user who authenticates using Sign In With Ethereum (EIP-4361). - properties: - type: - type: string - description: The type of authentication information. - example: siwe - enum: - - siwe - address: - allOf: - - $ref: '#/components/schemas/BlockchainAddress' - description: The ERC-55 checksummed Ethereum address of the end user. + summary: Settle payment + description: Settle an x402 protocol payment with a specific scheme and network. + operationId: settleX402Payment + tags: + - x402 Facilitator + security: + - apiKeyAuth: [] + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + x402Version: + $ref: '#/components/schemas/X402Version' + paymentPayload: + $ref: '#/components/schemas/x402PaymentPayload' + paymentRequirements: + $ref: '#/components/schemas/x402PaymentRequirements' + required: + - x402Version + - paymentPayload + - paymentRequirements + responses: + '200': + $ref: '#/components/responses/x402SettleResponse' + '400': + $ref: '#/components/responses/x402SettleError' + '402': + $ref: '#/components/responses/PaymentMethodRequiredError' + '500': + $ref: '#/components/responses/InternalServerError' + '502': + $ref: '#/components/responses/BadGatewayError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + /v2/x402/supported: + get: + x-audience: public + summary: Get supported payment schemes and networks + description: Get the supported x402 protocol payment schemes and networks that the facilitator is able to verify and settle payments for. + operationId: supportedX402PaymentKinds + tags: + - x402 Facilitator + security: + - apiKeyAuth: [] + responses: + '200': + $ref: '#/components/responses/x402SupportedPaymentKindsResponse' + '500': + $ref: '#/components/responses/InternalServerError' + '502': + $ref: '#/components/responses/BadGatewayError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + /v2/x402/discovery/resources: + get: + x-audience: public + summary: List x402 resources + description: |- + Lists all active discovered x402 resources. + This endpoint returns resources that have been discovered and cached by the x402 facilitator, including their payment requirements and metadata. + The response is paginated, and by default, returns 100 items per page. + operationId: listX402DiscoveryResources + tags: + - x402 Facilitator + security: + - unauthenticated: [] + parameters: + - name: type + in: query + description: |- + Filter by protocol type (e.g., "http", "mcp"). + Currently, the only supported protocol type is "http". + required: false + schema: + type: string + example: http + - name: limit + in: query + description: The number of discovered x402 resources to return per page. + required: false + schema: + type: integer + default: 100 + example: 50 + - name: offset + in: query + description: The offset of the first discovered x402 resource to return. + required: false + schema: + type: integer + default: 0 + example: 0 + responses: + '200': + description: Successfully retrieved discovery list. + content: + application/json: + schema: + $ref: '#/components/schemas/x402DiscoveryResourcesResponse' + '400': + description: Invalid request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + invalid_request: + value: + errorType: invalid_request + errorMessage: Invalid request. Please check the request parameters. + '500': + $ref: '#/components/responses/InternalServerError' + '502': + $ref: '#/components/responses/BadGatewayError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + /v2/x402/discovery/merchant: + get: + x-audience: public + summary: List merchant discovery info + description: |- + Gets x402 merchant discovery information for a given merchant payment address. + This endpoint returns all active x402 resources associated with the specified `payTo` address, allowing clients to discover what payment-gated resources a merchant exposes and their corresponding payment requirements. + The response is paginated, and by default, returns 20 items per page. + operationId: listX402DiscoveryMerchant + tags: + - x402 Facilitator + security: + - unauthenticated: [] + parameters: + - name: payTo + in: query + description: |- + The merchant's payment address to look up. + This is the onchain address that payment requirements route funds to. + required: true + schema: + $ref: '#/components/schemas/BlockchainAddress' example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - required: - - type - - address - AuthenticationMethod: - description: Information about how the end user is authenticated. - oneOf: - - $ref: '#/components/schemas/EmailAuthentication' - - $ref: '#/components/schemas/SmsAuthentication' - - $ref: '#/components/schemas/DeveloperJWTAuthentication' - - $ref: '#/components/schemas/OAuth2Authentication' - - $ref: '#/components/schemas/TelegramAuthentication' - - $ref: '#/components/schemas/SiweAuthentication' - AuthenticationMethods: - type: array - description: The list of valid authentication methods linked to the end user. - items: - $ref: '#/components/schemas/AuthenticationMethod' - example: - - type: email - email: user@example.com - - type: sms - phoneNumber: '+12055555555' - - type: jwt - sub: e051beeb-7163-4527-a5b6-35e301529ff2 - kid: NjVBRjY5MDlCMUIwNzU4RTA2QzZFMDQ4QzQ2MDAyQjVDNjk1RTM2Qg - - type: google - sub: '115346410074741490243' - email: test.user@gmail.com - - type: telegram - id: 1223456 - firstName: Satoshi - lastName: Nakamoto - photoUrl: https://image.url/profile.jpg - authDate: 1770681412 - username: satoshinakamoto - - type: siwe - address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - MFAMethods: + - name: limit + in: query + description: The number of resources to return per page. + required: false + schema: + type: integer + default: 20 + example: 20 + - name: offset + in: query + description: The offset of the first resource to return. + required: false + schema: + type: integer + default: 0 + example: 0 + responses: + '200': + description: Successfully retrieved merchant discovery info. + content: + application/json: + schema: + $ref: '#/components/schemas/x402DiscoveryMerchantResponse' + '400': + description: Invalid request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + invalid_request: + value: + errorType: invalid_request + errorMessage: Invalid request. Please check the request parameters. + '404': + description: Merchant not found. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + not_found: + value: + errorType: not_found + errorMessage: No resources found for the specified payTo address. + '500': + $ref: '#/components/responses/InternalServerError' + '502': + $ref: '#/components/responses/BadGatewayError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + /v2/x402/discovery/search: + get: + x-audience: public + summary: Search x402 resources + description: |- + Searches for active x402 resources using a text query and optional filters. + Supports both text-based and vector-based search depending on availability. Results are sorted by relevance and quality score. + Legacy network names (e.g., `base`, `base-sepolia`, `solana`) are automatically normalized to their CAIP-2 equivalents. + The response is limited to 20 items per request. If more results exist, `partialResults` will be `true`. + operationId: searchX402Resources + tags: + - x402 Facilitator + security: + - unauthenticated: [] + parameters: + - name: query + in: query + description: Full-text or semantic search query to find matching resources. + required: false + schema: + type: string + maxLength: 400 + example: weather forecast + - name: network + in: query + description: |- + Filter results by network in CAIP-2 format (e.g., `eip155:8453`) or legacy name (e.g., `base`, `base-sepolia`, `solana`). + Legacy names are normalized to their CAIP-2 equivalents before filtering. + required: false + schema: + type: string + example: eip155:8453 + - name: asset + in: query + description: |- + Filter results by asset address. + For EVM networks, provide a 0x-prefixed EVM address. For Solana networks, provide a base58-encoded address. + Matching is case-insensitive. + required: false + schema: + type: string + example: '0x036CbD53842c5426634e7929541eC2318f3dCF7e' + - name: scheme + in: query + description: Filter results by payment scheme (e.g., `exact`). + required: false + schema: + type: string + example: exact + - name: payTo + in: query + description: |- + Filter results by the merchant's payment address. + For EVM networks, provide a 0x-prefixed EVM address. For Solana networks, provide a base58-encoded address. + required: false + schema: + $ref: '#/components/schemas/BlockchainAddress' + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + - name: urlSubstring + in: query + description: |- + Filter results to resources whose URL contains this value (case-insensitive substring match against the resource URL). + Useful for narrowing results to a specific domain, subdomain, or path segment. Combine with `query` to perform semantic search restricted to a URL subset. + Tip: include enough of the URL to disambiguate (e.g. `api.example.com` rather than `example`) — a short substring may also match resources whose path contains the same string. + required: false + schema: + type: string + minLength: 3 + maxLength: 2048 + example: api.example.com + - name: maxUsdPrice + in: query + description: Filter results to resources with a USD price at or below this value. + required: false + schema: + type: string + example: '1.00' + - name: extensions + in: query + description: Filter results to resources that support the specified protocol extensions. Can be specified multiple times to filter by multiple extensions. + required: false + schema: + type: array + items: + type: string + example: + - bazaar + style: form + explode: true + - name: limit + in: query + description: |- + Maximum number of resources to return. Must be a positive integer no greater than 20. + Defaults to 20. + required: false + schema: + type: integer + default: 20 + maximum: 20 + minimum: 1 + example: 20 + responses: + '200': + description: Successfully retrieved matching x402 resources. + content: + application/json: + schema: + $ref: '#/components/schemas/x402SearchResourcesResponse' + examples: + search_results: + value: + x402Version: 2 + resources: + - resource: https://api.example.com/weather/forecast + description: Real-time weather forecast data. + type: http + x402Version: 2 + lastUpdated: '2024-01-15T10:30:00Z' + extensions: + bazaar: + info: + input: + type: http + method: GET + schema: {} + accepts: + - scheme: exact + network: eip155:8453 + amount: '1000000' + payTo: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + asset: '0x036CbD53842c5426634e7929541eC2318f3dCF7e' + maxTimeoutSeconds: 60 + quality: + l30DaysTotalCalls: 42 + l30DaysUniquePayers: 15 + lastCalledAt: '2024-01-15T10:30:00Z' + partialResults: false + searchMethod: text + '400': + description: Invalid request parameters. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + invalid_request: + value: + errorType: invalid_request + errorMessage: limit must be a positive integer. + '500': + $ref: '#/components/responses/InternalServerError' + '502': + $ref: '#/components/responses/BadGatewayError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + /v2/x402/discovery/mcp: + post: + x-audience: public + summary: Handle MCP JSON-RPC request + description: Handles JSON-RPC requests for the Model Context Protocol (MCP). Supports MCP methods for discovering x402 payment resources and tools. + operationId: postX402DiscoveryMcp + tags: + - x402 Facilitator + security: + - unauthenticated: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/x402McpRequest' + responses: + '200': + description: MCP response. + content: + application/json: + schema: + $ref: '#/components/schemas/x402McpResponse' + '400': + description: Invalid request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + invalid_request: + value: + errorType: invalid_request + errorMessage: Invalid JSON-RPC request. Please check the request format. + '500': + $ref: '#/components/responses/InternalServerError' + /v2/onramp/orders: + post: + x-audience: public + summary: Create an onramp order + description: |- + Create a new Onramp order or get a quote for an Onramp order. Either `paymentAmount` or `purchaseAmount` must be provided. + + This API currently only supports the payment method `GUEST_CHECKOUT_APPLE_PAY`. + + For detailed integration instructions and to get access to this API, refer to the [Apple Pay Onramp API docs](https://docs.cdp.coinbase.com/onramp-&-offramp/onramp-apis/apple-pay-onramp-api). + operationId: createOnrampOrder + tags: + - Onramp + security: + - apiKeyAuth: [] + requestBody: + content: + application/json: + schema: + type: object + properties: + agreementAcceptedAt: + description: The timestamp of when the user acknowledged that by using Coinbase Onramp they are accepting the Coinbase Terms (https://www.coinbase.com/legal/guest-checkout/us), User Agreement (https://www.coinbase.com/legal/user_agreement), and Privacy Policy (https://www.coinbase.com/legal/privacy). + format: date-time + type: string + example: '2025-04-24T00:00:00Z' + destinationAddress: + allOf: + - $ref: '#/components/schemas/BlockchainAddress' + description: The address the purchased crypto will be sent to. + destinationNetwork: + description: |- + The name of the crypto network the purchased currency will be sent on. + + Use the [Onramp Buy Options API](https://docs.cdp.coinbase.com/api-reference/rest-api/onramp-offramp/get-buy-options) to discover the supported networks for your user's location. + type: string + example: base + email: + description: The verified email address of the user requesting the onramp transaction. This email must be verified by your app (via OTP) before being used with the Onramp API. + type: string + example: test@example.com + isQuote: + description: If true, this API will return a quote without creating any transaction. + type: boolean + default: false + partnerOrderRef: + description: Optional partner order reference ID. + type: string + example: order-1234 + partnerUserRef: + description: |- + A unique string that represents the user in your app. This can be used to link individual transactions together so you can retrieve the transaction history for your users. Prefix this string with “sandbox-” (e.g. "sandbox-user-1234") to perform a sandbox transaction which will allow you to test your integration without any real transfer of funds. + + This value can be used with with [Onramp User Transactions API](https://docs.cdp.coinbase.com/api-reference/rest-api/onramp-offramp/get-onramp-transactions-by-id) to retrieve all transactions created by the user. + type: string + example: user-1234 + paymentAmount: + description: A string representing the amount of fiat the user wishes to pay in exchange for crypto. When using this parameter, the returned quote will be inclusive of fees i.e. the user will pay this exact amount of the payment currency. + type: string + example: '100.00' + paymentCurrency: + description: The fiat currency to be converted to crypto. + type: string + example: USD + paymentMethod: + $ref: '#/components/schemas/OnrampOrderPaymentMethodTypeId' + phoneNumber: + description: |- + The phone number of the user requesting the onramp transaction in E.164 format. This phone number must be verified by your app (via OTP) before being used with the Onramp API. + + Please refer to the [Onramp docs](https://docs.cdp.coinbase.com/onramp-&-offramp/onramp-apis/apple-pay-onramp-api) for more details on phone number verification requirements and best practices. + type: string + example: '+12055555555' + phoneNumberVerifiedAt: + description: Timestamp of when the user's phone number was verified via OTP. User phone number must be verified every 60 days. If this timestamp is older than 60 days, an error will be returned. + format: date-time + type: string + example: '2025-04-24T00:00:00Z' + purchaseAmount: + description: A string representing the amount of crypto the user wishes to purchase. When using this parameter the returned quote will be exclusive of fees i.e. the user will receive this exact amount of the purchase currency. + type: string + example: '10.000000' + purchaseCurrency: + description: |- + The ticker (e.g. `BTC`, `USDC`, `SOL`) or the Coinbase UUID (e.g. `d85dce9b-5b73-5c3c-8978-522ce1d1c1b4`) of the crypto asset to be purchased. + + Use the [Onramp Buy Options API](https://docs.cdp.coinbase.com/api-reference/rest-api/onramp-offramp/get-buy-options) to discover the supported purchase currencies for your user's location. + type: string + example: USDC + clientIp: + description: The IP address of the end user requesting the onramp transaction. + type: string + example: 127.0.0.1 + domain: + description: The domain that the Apple Pay button will be rendered on. Required when using the `GUEST_CHECKOUT_APPLE_PAY` payment method and embedding the payment link in an iframe. + type: string + example: pay.coinbase.com + required: + - paymentCurrency + - purchaseCurrency + - paymentMethod + - destinationAddress + - destinationNetwork + - phoneNumber + - email + - agreementAcceptedAt + - phoneNumberVerifiedAt + - partnerUserRef + responses: + '201': + description: Successfully created an onramp order. + content: + application/json: + schema: + type: object + properties: + order: + $ref: '#/components/schemas/OnrampOrder' + paymentLink: + $ref: '#/components/schemas/OnrampPaymentLink' + required: + - order + '400': + description: Invalid request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + invalid_request: + value: + errorType: invalid_request + errorMessage: Missing required params. + network_not_tradable: + value: + errorType: network_not_tradable + errorMessage: The selected asset cannot be purchased on the selected network in the user's location. + guest_permission_denied: + value: + errorType: guest_permission_denied + errorMessage: The user is not allowed to complete onramp transactions as a guest. + guest_region_forbidden: + value: + errorType: guest_region_forbidden + errorMessage: Guest onramp transactions are not allowed in the user's region. + guest_transaction_limit: + value: + errorType: guest_transaction_limit + errorMessage: This transaction would exceed the user's weekly guest onramp transaction limit. + guest_transaction_count: + value: + errorType: guest_transaction_count + errorMessage: The user has reached the lifetime guest onramp transaction count limit (15). + phone_number_verification_expired: + value: + errorType: phone_number_verification_expired + errorMessage: The user's phone number verification has expired. Please re-verify the user's phone number. + '401': + $ref: '#/components/responses/UnauthorizedError' + '429': + $ref: '#/components/responses/RateLimitExceeded' + '500': + $ref: '#/components/responses/InternalServerError' + /v2/onramp/orders/{orderId}: + get: + x-audience: public + summary: Get an onramp order by ID + description: Get an onramp order by ID. + operationId: getOnrampOrderById + tags: + - Onramp + security: + - apiKeyAuth: [] + parameters: + - name: orderId + in: path + required: true + description: The ID of the onramp order to retrieve. + schema: + type: string + example: 123e4567-e89b-12d3-a456-426614174000 + responses: + '200': + description: Successfully retrieved an onramp order. + content: + application/json: + schema: + type: object + properties: + order: + $ref: '#/components/schemas/OnrampOrder' + required: + - order + '401': + $ref: '#/components/responses/UnauthorizedError' + '404': + description: Order not found. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + not_found: + value: + errorType: not_found + errorMessage: Order with the given ID does not exist. + '429': + $ref: '#/components/responses/RateLimitExceeded' + /v2/onramp/sessions: + post: + x-audience: public + summary: Create an onramp session + description: |- + Returns a single-use URL for an Onramp session. This API provides flexible functionality based on the parameters provided, supporting three cases: + + **Important**: The returned URL is single-use only. Once a user visits the URL, no one else can access it. + ## Use Cases + ### 1. Basic Session (Minimum Parameters) + **Required**: `destinationAddress`, `purchaseCurrency`, `destinationNetwork` + + **Returns**: Basic single-use onramp URL. The `quote` object will not be included in the response. + ### 2. One-Click Onramp URL + **Required**: Basic parameters + (`paymentAmount` OR `purchaseAmount`), `paymentCurrency` + + **Returns**: One-click onramp URL for streamlined checkout. The `quote` object will not be included in the response. + ### 3. One-Click Onramp URL with Quote + **Required**: One-Click Onramp parameters + `paymentMethod`, `country`, `subdivision` + + **Returns**: Complete pricing quote and one-click onramp URL. Both `session` and `quote` objects will be included in the response. + + **Note**: Only one of `paymentAmount` or `purchaseAmount` should be provided, not both. Providing both will result in an error. When `paymentAmount` is provided, the quote shows how much crypto the user will receive for the specified fiat amount (fee-inclusive). When `purchaseAmount` is provided, the quote shows how much fiat the user needs to pay for the specified crypto amount (fee-exclusive). + operationId: createOnrampSession + tags: + - Onramp + security: + - apiKeyAuth: [] + requestBody: + content: + application/json: + schema: + type: object + properties: + purchaseCurrency: + description: |- + The ticker (e.g. `BTC`, `USDC`, `SOL`) or the Coinbase UUID (e.g. `d85dce9b-5b73-5c3c-8978-522ce1d1c1b4`) of the crypto asset to be purchased. + + Use the [Onramp Buy Options API](https://docs.cdp.coinbase.com/api-reference/rest-api/onramp-offramp/get-buy-options) to discover the supported purchase currencies for your user's location. + type: string + example: USDC + destinationNetwork: + description: |- + The name of the crypto network the purchased currency will be sent on. + + Use the [Onramp Buy Options API](https://docs.cdp.coinbase.com/api-reference/rest-api/onramp-offramp/get-buy-options) to discover the supported networks for your user's location. + type: string + example: base + destinationAddress: + allOf: + - $ref: '#/components/schemas/BlockchainAddress' + description: The address the purchased crypto will be sent to. + paymentAmount: + description: A string representing the amount of fiat the user wishes to pay in exchange for crypto. When using this parameter, the returned quote will be inclusive of fees i.e. the user will pay this exact amount of the payment currency. + type: string + example: '100.00' + purchaseAmount: + description: A string representing the amount of crypto the user wishes to purchase. When using this parameter, the returned quote will be exclusive of fees i.e. the user will receive this exact amount of the purchase currency. + type: string + example: '10.000000' + paymentCurrency: + description: The fiat currency to be converted to crypto. + type: string + example: USD + paymentMethod: + $ref: '#/components/schemas/OnrampQuotePaymentMethodTypeId' + country: + description: The ISO 3166-1 two letter country code (e.g. US). + type: string + example: US + subdivision: + description: The ISO 3166-2 two letter state code (e.g. NY). Only required for US. + type: string + example: NY + redirectUrl: + allOf: + - $ref: '#/components/schemas/Uri' + description: URI to redirect the user to when they successfully complete a transaction. This URI will be embedded in the returned onramp URI as a query parameter. + example: https://example.com/success + clientIp: + description: The IP address of the end user requesting the onramp transaction. + type: string + example: 127.0.0.1 + partnerUserRef: + description: |- + A unique string that represents the user in your app. This can be used to link individual transactions together so you can retrieve the transaction history for your users. Prefix this string with “sandbox-” (e.g. "sandbox-user-1234") to perform a sandbox transaction which will allow you to test your integration without any real transfer of funds. + + This value can be used with with [Onramp User Transactions API](https://docs.cdp.coinbase.com/api-reference/rest-api/onramp-offramp/get-onramp-transactions-by-id) to retrieve all transactions created by the user. + type: string + example: user-1234 + required: + - destinationAddress + - purchaseCurrency + - destinationNetwork + responses: + '201': + description: Onramp session created successfully. + content: + application/json: + schema: + type: object + properties: + session: + $ref: '#/components/schemas/OnrampSession' + quote: + $ref: '#/components/schemas/OnrampQuote' + required: + - session + '400': + description: Invalid request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + invalid_request: + value: + errorType: invalid_request + errorMessage: Missing required parameters. + invalid_destination_address: + value: + errorType: invalid_request + errorMessage: The destination address is not valid for the specified network. + '401': + $ref: '#/components/responses/UnauthorizedError' + '429': + $ref: '#/components/responses/RateLimitExceeded' + '500': + $ref: '#/components/responses/InternalServerError' + /v2/onramp/limits: + post: + summary: Get onramp user limits + x-audience: public + description: |- + Returns the transaction limits for an onramp user based on their payment method and user identifier. Use this API to show users their remaining purchase capacity before initiating an onramp transaction. + Currently supports `GUEST_CHECKOUT_APPLE_PAY` payment method with phone number identification. The phone number must have been previously verified via OTP. + operationId: getOnrampUserLimits + tags: + - Onramp + security: + - apiKeyAuth: [] + requestBody: + content: + application/json: + schema: + type: object + properties: + paymentMethodType: + $ref: '#/components/schemas/OnrampOrderPaymentMethodTypeId' + userId: + type: string + description: The user identifier value. For `phone_number` type, this must be in E.164 format. + example: '+12055555555' + userIdType: + $ref: '#/components/schemas/OnrampUserIdType' + required: + - paymentMethodType + - userId + - userIdType + responses: + '200': + description: Successfully retrieved user limits. + content: + application/json: + schema: + type: object + properties: + limits: + type: array + description: The list of limits applicable to the user. + items: + $ref: '#/components/schemas/OnrampUserLimit' + required: + - limits + examples: + default: + value: + limits: + - limitType: weekly_spending + currency: USD + limit: '500' + remaining: '400' + - limitType: lifetime_transactions + limit: '15' + remaining: '12' + '400': + description: Invalid request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + invalid_request: + value: + errorType: invalid_request + errorMessage: Must provide a valid payment method type and user identifier. + '401': + $ref: '#/components/responses/UnauthorizedError' + '429': + $ref: '#/components/responses/RateLimitExceeded' + '500': + $ref: '#/components/responses/InternalServerError' + /v2/onramp/limits/upgrade: + post: + summary: Request limit upgrade + x-audience: public + description: |- + Requests a limit upgrade for an onramp user by submitting identity information. Only phone number is currently supported as a userId. + + The verification process is asynchronous. After calling this endpoint, use the [Get Onramp User Limits](https://docs.cdp.coinbase.com/api-reference/v2/rest-api/onramp/get-onramp-user-limits) endpoint to check the status in the `limitUpgradeOptions` array. + + **Prerequisites:** + - The phone number must have been previously verified by your app via OTP. - Upgrades may not be available until a certain number of successful transactions by the user. + + **Supported fields:** + - `ssnLast4`: Last 4 digits of the Social Security Number (no dashes or spaces). + - `dateOfBirth`: Date of birth (day, month, year as zero-padded strings). + operationId: requestLimitsUpgrade + tags: + - Onramp + security: + - apiKeyAuth: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OnrampLimitUpgradeRequest' + example: + userId: '+12055555555' + userIdType: phone_number + fields: + ssnLast4: '5678' + dateOfBirth: + day: '15' + month: '08' + year: '1990' + responses: + '202': + description: Limit upgrade request accepted. + '400': + description: Invalid request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + invalid_request: + value: + errorType: invalid_request + errorMessage: Invalid user identifier or fields. + '401': + $ref: '#/components/responses/UnauthorizedError' + '429': + $ref: '#/components/responses/RateLimitExceeded' + '500': + $ref: '#/components/responses/InternalServerError' + /v2/payment-methods: + get: + x-audience: public + summary: List payment methods + description: |- + List payment methods linked to your entity. Payment methods represent external financial instruments that can be used as a target for transfers. The list will not include disabled or deleted payment methods. + + **Currently Supported Types:** + - `fedwire`: Domestic USD wire transfers + - `swift`: International wire transfers + - `sepa`: SEPA EUR transfers + + **Note:** Payment methods are created and verified through your linked CDP entity. Currently, fetching payment methods is only supported for Prime investment vehicles linked to CDP. + operationId: listPaymentMethods + tags: + - Payment Methods + security: + - apiKeyAuth: [] + x-required-permissions: + permissions: + - accounts:read@entity + enforcement: any + parameters: + - $ref: '#/components/parameters/PageSize' + - $ref: '#/components/parameters/PageToken' + responses: + '200': + description: Successfully listed payment methods. + content: + application/json: + schema: + allOf: + - type: object + required: + - paymentMethods + properties: + paymentMethods: + type: array + description: The list of payment methods. + items: + $ref: '#/components/schemas/payment-methods_PaymentMethod' + - $ref: '#/components/schemas/ListResponse' + example: + paymentMethods: + - paymentMethodId: paymentMethod_8e03978e-40d5-43e8-bc93-6894a57f9324 + paymentRail: fedwire + active: true + createdAt: '2024-01-15T10:30:00Z' + updatedAt: '2024-01-15T10:30:00Z' + fedwire: + asset: usd + bankName: ALLY BANK + accountLast4: '1234' + routingNumber: '124003116' + - paymentMethodId: paymentMethod_def45678-1234-5678-9abc-def012345678 + paymentRail: swift + active: true + createdAt: '2024-01-15T10:30:00Z' + updatedAt: '2024-01-15T10:30:00Z' + swift: + asset: eur + bankName: Deutsche Bank + accountLast4: '5678' + ibanLast4: '5678' + bic: DEUTDEFF + - paymentMethodId: paymentMethod_abc12345-6789-0abc-def0-123456789abc + paymentRail: sepa + active: true + createdAt: '2024-01-15T10:30:00Z' + updatedAt: '2024-01-15T10:30:00Z' + sepa: + asset: eur + bankName: ING Bank + ibanLast4: '4300' + bic: INGBNL2A + nextPageToken: eyJsYXN0X2lkIjogImFiYzEyMyJ9 + '400': + description: Invalid request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + invalid_request: + value: + errorType: invalid_request + errorMessage: Invalid page token format. + '401': + $ref: '#/components/responses/UnauthorizedError' + '500': + $ref: '#/components/responses/InternalServerError' + /v2/payment-methods/{paymentMethodId}: + get: + x-audience: public + summary: Get payment method + description: Get details of a specific payment method by its ID. Returns 404 if the payment method is not found or not owned by the requesting entity. + operationId: getPaymentMethod + security: + - apiKeyAuth: [] + x-required-permissions: + permissions: + - accounts:read@entity + enforcement: any + tags: + - Payment Methods + parameters: + - name: paymentMethodId + in: path + required: true + description: The unique identifier of the payment method. + schema: + $ref: '#/components/schemas/PaymentMethodId' + example: paymentMethod_8e03978e-40d5-43e8-bc93-6894a57f9324 + responses: + '200': + description: Successfully retrieved payment method. + content: + application/json: + schema: + $ref: '#/components/schemas/payment-methods_PaymentMethod' + examples: + fedwire: + summary: Fedwire payment method + value: + paymentMethodId: paymentMethod_8e03978e-40d5-43e8-bc93-6894a57f9324 + paymentRail: fedwire + active: true + createdAt: '2024-01-15T10:30:00Z' + updatedAt: '2024-01-15T10:30:00Z' + fedwire: + asset: usd + bankName: ALLY BANK + accountLast4: '1234' + routingNumber: '124003116' + swift: + summary: SWIFT payment method + value: + paymentMethodId: paymentMethod_def45678-1234-5678-9abc-def012345678 + paymentRail: swift + active: true + createdAt: '2024-01-15T10:30:00Z' + updatedAt: '2024-01-15T10:30:00Z' + swift: + asset: eur + bankName: Deutsche Bank + accountLast4: '5678' + ibanLast4: '5678' + bic: DEUTDEFF + sepa: + summary: SEPA payment method + value: + paymentMethodId: paymentMethod_abc12345-6789-0abc-def0-123456789abc + paymentRail: sepa + active: true + createdAt: '2024-01-15T10:30:00Z' + updatedAt: '2024-01-15T10:30:00Z' + sepa: + asset: eur + bankName: ING Bank + ibanLast4: '4300' + bic: INGBNL2A + '400': + description: Invalid request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + invalid_request: + value: + errorType: invalid_request + errorMessage: Invalid payment method ID format. + '401': + $ref: '#/components/responses/UnauthorizedError' + '404': + description: Payment method not found. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + not_found: + value: + errorType: not_found + errorMessage: Payment method not found. + '500': + $ref: '#/components/responses/InternalServerError' +webhooks: {} +components: + securitySchemes: + apiKeyAuth: + type: http + scheme: bearer + bearerFormat: JWT + description: A JWT signed using your CDP API Key Secret, encoded in base64. Refer to the [Generate Bearer Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-bearer-token) section of our Authentication docs for information on how to generate your Bearer Token. + endUserAuth: + x-audience: public + type: http + scheme: bearer + bearerFormat: JWT + description: A JWT signed using the developer's own JWT private key (in the case of JWT authentication), or an end user JWT signed by CDP, encoded in base64. This is used for End User Account APIs. + unauthenticated: x-audience: public + type: http + scheme: none + description: This security scheme is used for APIs that do not require authentication, such as End User Auth flows used to initiate authentication or public, read-only endpoints. + parameters: + PageSize: + name: pageSize + description: The number of resources to return per page. + in: query + required: false + schema: + type: integer + default: 20 + example: 10 + PageToken: + name: pageToken + description: The token for the next page of resources, if any. + in: query + required: false + schema: + type: string + example: eyJsYXN0X2lkIjogImFiYzEyMyIsICJ0aW1lc3RhbXAiOiAxNzA3ODIzNzAxfQ== + IdempotencyKey: + name: X-Idempotency-Key + in: header + required: false description: | - Information about the end user's MFA enrollments. - type: object - properties: - enrollmentPromptedAt: - type: string - format: date-time - description: The date and time when the end user was prompted for MFA enrollment, in ISO 8601 format. If the this field exists, and the user has no other enrolled MFA methods, then the user skipped MFA enrollment. - example: '2025-01-15T10:30:00Z' - totp: - type: object - description: An object containing information about the end user's TOTP enrollment. - required: - - enrolledAt - properties: - enrolledAt: - type: string - format: date-time - description: The date and time when the method was enrolled, in ISO 8601 format. - example: '2025-01-15T10:30:00Z' - sms: - type: object - description: An object containing information about the end user's SMS MFA enrollment. - required: - - enrolledAt - properties: - enrolledAt: - type: string - format: date-time - description: The date and time when the method was enrolled, in ISO 8601 format. - example: '2025-01-15T10:30:00Z' - example: - enrollmentPromptedAt: '2025-01-15T10:30:00Z' - totp: - enrolledAt: '2025-01-15T10:30:00Z' - sms: - enrolledAt: '2025-01-15T10:30:00Z' - EndUserEvmAccount: - type: object - description: Information about an EVM account associated with an end user. - properties: - address: - type: string - description: The address of the EVM account. - pattern: ^0x[0-9a-fA-F]{40}$ - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - createdAt: - type: string - format: date-time - description: The date and time when the account was created, in ISO 8601 format. - example: '2025-01-15T10:30:00Z' - required: - - address - - createdAt - EndUserEvmSmartAccount: - type: object - description: Information about an EVM smart account associated with an end user. - properties: - address: - type: string - description: The address of the EVM smart account. - pattern: ^0x[0-9a-fA-F]{40}$ - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - ownerAddresses: - type: array - description: The addresses of the EVM EOA accounts that own this smart account. Smart accounts can have multiple owners, such as when spend permissions are enabled. - items: - type: string - description: The address of an EVM EOA account that owns this smart account. - pattern: ^0x[0-9a-fA-F]{40}$ - example: '0x1234567890abcdef1234567890abcdef12345678' - example: - - '0x1234567890abcdef1234567890abcdef12345678' - - '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd' - createdAt: - type: string - format: date-time - description: The date and time when the account was created, in ISO 8601 format. - example: '2025-01-15T10:30:00Z' - required: - - address - - ownerAddresses - - createdAt - EndUserSolanaAccount: + An optional string request header for making requests safely retryable. + When included, duplicate requests with the same key will return identical responses. + Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + schema: + type: string + maxLength: 128 + minLength: 1 + example: 8e03978e-40d5-43e8-bc93-6894a57f9324 + XWalletAuth: + name: X-Wallet-Auth + in: header + required: true + description: | + A JWT signed using your Wallet Secret, encoded in base64. Refer to the + [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) + section of our Authentication docs for more details on how to generate your Wallet Token. + schema: + type: string + example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEyMywicm9sZSI6ImFkbWluIiwiZXhwIjoxNzAxOTgwMDAwfQ.HWvMTKmCCTxHaxjvZyLaC6UQ6TV3ErTDWBf7zmdH0Lw + XWalletAuthOptional: + name: X-Wallet-Auth + in: header + required: false + description: | + A JWT signed using your Wallet Secret, encoded in base64. Refer to the + [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) + section of our Authentication docs for more details on how to generate your Wallet Token. + schema: + type: string + example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEyMywicm9sZSI6ImFkbWluIiwiZXhwIjoxNzAxOTgwMDAwfQ.HWvMTKmCCTxHaxjvZyLaC6UQ6TV3ErTDWBf7zmdH0Lw + XDeveloperAuth: + name: X-Developer-Auth + in: header + required: false + description: | + A JWT signed using your Wallet Secret, encoded in base64. Refer to the + [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) + section of our Authentication docs for more details on how to generate your Wallet Token. + schema: + type: string + example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEyMywicm9sZSI6ImFkbWluIiwiZXhwIjoxNzAxOTgwMDAwfQ.HWvMTKmCCTxHaxjvZyLaC6UQ6TV3ErTDWBf7zmdH0Lw + ProjectIDOptional: + name: projectID + in: query + required: false + description: The ID of the CDP Project. Required for end users authenticated using custom auth (i.e. a non-CDP JWT provider). + schema: + type: string + pattern: ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$ + example: 8e03978e-40d5-43e8-bc93-6894a57f9324 + schemas: + AccountType: + type: string + description: The type of the Account. + enum: + - prime + - business + - cdp + example: prime + AccountId: + type: string + pattern: ^account_[a-f0-9\-]{36}$ + description: The ID of the Account, which is a UUID prefixed by the string `account_`. + example: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + Owner: + type: string + description: |- + The Owner ID of the Account. + Owner IDs are UUIDs prefixed with the Owner Type as follows: + * **Entity**: `entity_` - If the Owner is your Entity, e.g. `entity_af2937b0-9846-4fe7-bfe9-ccc22d935114`. + Support for Customer-owned accounts (`customer_` prefix) is in development. + pattern: ^(entity|customer)_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$ + example: entity_af2937b0-9846-4fe7-bfe9-ccc22d935114 + AccountName: + type: string + pattern: ^[a-zA-Z0-9 -]{1,64}$ + maxLength: 64 + description: An optional name for the account. Must be 1-64 characters and can only contain alphanumeric characters, hyphens, and spaces. + example: My Business Account + Account: type: object - description: Information about a Solana account associated with an end user. properties: - address: - type: string - description: The base58 encoded address of the Solana account. - pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ - example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + accountId: + $ref: '#/components/schemas/AccountId' + type: + $ref: '#/components/schemas/AccountType' + owner: + $ref: '#/components/schemas/Owner' + name: + $ref: '#/components/schemas/AccountName' createdAt: type: string format: date-time - description: The date and time when the account was created, in ISO 8601 format. - example: '2025-01-15T10:30:00Z' - required: - - address - - createdAt - EndUser: - type: object - description: Information about the end user. - properties: - userId: - description: A stable, unique identifier for the end user. The `userId` must be unique across all end users in the developer's CDP Project. It must be between 1 and 100 characters long and can only contain alphanumeric characters and hyphens. - type: string - pattern: ^[a-zA-Z0-9-]{1,100}$ - example: e051beeb-7163-4527-a5b6-35e301529ff2 - authenticationMethods: - $ref: '#/components/schemas/AuthenticationMethods' - mfaMethods: - $ref: '#/components/schemas/MFAMethods' - evmAccounts: - type: array - deprecated: true - description: '**DEPRECATED**: Use `evmAccountObjects` instead for richer account information. The list of EVM account addresses associated with the end user. End users can have up to 10 EVM accounts.' - items: - type: string - description: The address of the EVM account associated with the end user. - pattern: ^0x[0-9a-fA-F]{40}$ - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - example: - - '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - evmAccountObjects: - type: array - description: The list of EVM accounts associated with the end user. End users can have up to 10 EVM accounts. - items: - $ref: '#/components/schemas/EndUserEvmAccount' - example: - - address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - createdAt: '2025-01-15T10:30:00Z' - - address: '0x1234567890abcdef1234567890abcdef12345678' - createdAt: '2025-01-15T11:00:00Z' - evmSmartAccounts: - type: array - deprecated: true - description: '**DEPRECATED**: Use `evmSmartAccountObjects` instead for richer account information including owner relationships. The list of EVM smart account addresses associated with the end user. Each EVM EOA can own one smart account.' - items: - type: string - description: The address of the EVM smart account associated with the end user. - pattern: ^0x[0-9a-fA-F]{40}$ - example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - example: - - '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - evmSmartAccountObjects: - type: array - description: The list of EVM smart accounts associated with the end user. Each EVM EOA can own one smart account. - items: - $ref: '#/components/schemas/EndUserEvmSmartAccount' - example: - - address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' - ownerAddresses: - - '0x1234567890abcdef1234567890abcdef12345678' - - '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd' - createdAt: '2025-01-15T12:00:00Z' - solanaAccounts: - type: array - deprecated: true - description: '**DEPRECATED**: Use `solanaAccountObjects` instead for richer account information. The list of Solana account addresses associated with the end user. End users can have up to 10 Solana accounts.' - items: - type: string - description: The base58 encoded address of the Solana account associated with the end user. - pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ - example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT - example: - - HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT - solanaAccountObjects: - type: array - description: The list of Solana accounts associated with the end user. End users can have up to 10 Solana accounts. - items: - $ref: '#/components/schemas/EndUserSolanaAccount' - example: - - address: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT - createdAt: '2025-01-15T10:30:00Z' - - address: 9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin - createdAt: '2025-01-15T11:30:00Z' - createdAt: + description: The timestamp when the account was created. + example: '2023-10-08T14:30:00Z' + updatedAt: type: string format: date-time - description: The date and time when the end user was created, in ISO 8601 format. - example: '2025-01-15T10:30:00Z' + description: The timestamp when the account was last updated. + example: '2023-10-08T14:30:00Z' required: - - userId - - authenticationMethods - - evmAccounts - - evmAccountObjects - - evmSmartAccounts - - evmSmartAccountObjects - - solanaAccounts - - solanaAccountObjects + - accountId + - type + - owner - createdAt + - updatedAt ListResponse: type: object properties: @@ -9855,6 +11081,7 @@ components: - bad_gateway - capture_expired - client_closed_request + - endpoint_unavailable - faucet_limit_exceeded - forbidden - idempotency_error @@ -9872,6 +11099,7 @@ components: - service_unavailable - timed_out - unauthorized + - unsupported_tos_language - policy_violation - policy_in_use - account_limit_exceeded @@ -9896,6 +11124,7 @@ components: - target_onchain_address_invalid - transfer_amount_invalid - transfer_asset_not_supported + - transfer_quote_expired - insufficient_balance - metadata_too_many_entries - metadata_key_too_long @@ -9914,6 +11143,11 @@ components: - insufficient_liquidity - insufficient_allowance - transaction_simulation_failed + - delegation_not_found + - delegation_expired + - delegation_revoked + - delegation_not_authorized + - delegation_not_enabled x-error-instructions: already_exists: |- This error occurs when trying to create a resource that already exists. @@ -9947,6 +11181,16 @@ components: 1. Increase client-side timeout settings if applicable 2. Implement retry logic with exponential backoff for long-running queries 3. Consider optimizing the request to reduce server processing time + endpoint_unavailable: |- + This error occurs when a specific endpoint has been temporarily disabled by an operator (e.g. a kill switch). The CDP API as a whole is still healthy; only this endpoint is unavailable. Distinct from `service_unavailable`, which indicates the API itself is down. + + Re-enabling is a manual operator action, so the endpoint may remain unavailable for an extended period. + + **Steps to resolve:** + 1. Check the [CDP status page](https://cdpstatus.coinbase.com/) for an active incident. + 2. If persistent, contact CDP support with: + - The timestamp of the error + - Request details faucet_limit_exceeded: |- This error occurs when you've exceeded the faucet request limits. @@ -10221,6 +11465,13 @@ components: - X-Wallet-Auth header included when required **Security note:** Never share your Wallet Secret or API keys. + unsupported_tos_language: |- + A submitted Terms of Service acceptance used a `language` that is not published for the referenced `versionId`. + + **Steps to resolve:** + 1. Read `Customer.requirements.tos.tosVersions[]` and find the entry whose `versionId` matches your acceptance. + 2. Choose a `language` from that entry's `languages` list (BCP 47 tags). + 3. Retry with `tosAcceptances[].language` set to a supported tag. policy_in_use: |- This error occurs when trying to delete a Policy that is currently in use by at least one project or account. @@ -10432,6 +11683,15 @@ components: **Common causes:** - Asset not supported for transfers - Incorrect asset symbol + transfer_quote_expired: |- + This error occurs when the transfer quote has expired. Quotes are valid for a limited time. + + **Steps to resolve:** + 1. Create a new transfer to obtain a fresh quote + 2. Execute the transfer promptly after creation + + **Common causes:** + - Too much time elapsed between creating and executing the transfer insufficient_balance: |- This error occurs when the source account does not have enough funds to complete the transfer including fees. @@ -10449,158 +11709,1708 @@ components: This error occurs when the transfer metadata contains more entries than allowed. **Steps to resolve:** - 1. Reduce the number of metadata entries (maximum 10 allowed) - 2. Consolidate related data into fewer keys - 3. Store additional data externally and reference it with a single metadata entry + 1. Reduce the number of metadata entries (maximum 10 allowed) + 2. Consolidate related data into fewer keys + 3. Store additional data externally and reference it with a single metadata entry + + **Limits:** + - Maximum entries: 10 + metadata_key_too_long: |- + This error occurs when a metadata key exceeds the maximum allowed length. + + **Steps to resolve:** + 1. Shorten the metadata key to 40 characters or less + 2. Use abbreviations or shorter naming conventions + 3. Consider using a key-value structure where the value contains the longer identifier + + **Limits:** + - Maximum key length: 40 characters + metadata_value_too_long: |- + This error occurs when a metadata value exceeds the maximum allowed length. + + **Steps to resolve:** + 1. Shorten the metadata value to 500 characters or less + 2. Store longer data externally and reference it with a shorter identifier + 3. Consider compressing or encoding the data if appropriate + + **Limits:** + - Maximum value length: 500 characters + travel_rules_field_missing: |- + This error occurs when required travel rule fields are missing from the transfer request. + + **Steps to resolve:** + 1. Include the `travelRule` object in your transfer request + 2. Supply the required missing fields prompted by the error message + 3. Review the travel rule requirements for your jurisdiction + + Note: Required fields may vary by region. + asset_mismatch: |- + This error occurs when the assets specified in the transfer are incompatible or don't match expected values. + + **Steps to resolve:** + 1. Ensure the `asset` field matches either the source or target asset + 2. Verify that the source and target assets are compatible for conversion (if different) + 3. Check that the asset symbols are correctly specified + + **Common causes:** + - Transfer asset doesn't match source or target + - Attempting an unsupported asset conversion + - Typo in asset symbols + order_quote_expired: |- + This error occurs when attempting to execute an order whose quote has expired. + + **Steps to resolve:** + 1. Create a new order with `execute: false` to get an updated quote. + 2. Execute the new order before the quote expires (check the `expiresAt` field). + 3. Alternatively, create a new order with `execute: true` to skip the quote step and execute immediately. + order_already_filled: |- + This error occurs when attempting to cancel or modify an order that has already been filled. + + **Steps to resolve:** + 1. Check the current status of the order using `GET /v2/orders/{orderId}`. + 2. A filled order cannot be canceled or re-executed. + order_already_canceled: |- + This error occurs when attempting to cancel or execute an order that has already been canceled. + + **Steps to resolve:** + 1. Check the current status of the order using `GET /v2/orders/{orderId}`. + 2. Create a new order if you still want to trade. + account_not_ready: |- + This error occurs when an operation is attempted on an account that is still being provisioned. + + **Steps to resolve:** + 1. Wait a few moments and retry the request + 2. If the error persists, the account may still be completing setup — retry with exponential backoff + insufficient_liquidity: |- + This error occurs when no swap route is available for the requested token pair or amount. + + **Steps to resolve:** + 1. Try a smaller `fromAmount` — large orders may exceed available liquidity + 2. Try a different token pair + 3. Retry after a short delay; liquidity conditions change with market activity + insufficient_allowance: |- + This error occurs when the taker has not approved the Permit2 contract to spend the `fromToken` + on their behalf. ERC-20 swaps require a Permit2 allowance. Native ETH swaps do not. + + **Steps to resolve:** + 1. Submit an ERC-20 `approve` transaction on the `fromToken` contract, granting the Permit2 + contract (`0x000000000022D473030F116dDEE9F6B43aC78BA3`) an allowance of at least `fromAmount` + 2. Wait for the approval transaction to be confirmed on-chain + 3. Retry the swap + + **Example:** + ```typescript lines wrap + // Approve Permit2 to spend fromToken + await walletClient.writeContract({ + address: fromToken, + abi: erc20Abi, + functionName: "approve", + args: ["0x000000000022D473030F116dDEE9F6B43aC78BA3", fromAmount], + }); + ``` + transaction_simulation_failed: |- + This error occurs when the pre-broadcast simulation of the swap transaction predicted a revert. + No transaction was submitted and no gas was spent. + + **Common causes:** + - The on-chain price moved past the `slippageBps` tolerance between the price estimate and execution + - Taker balance changed between the price estimate and execution + + **Steps to resolve:** + 1. Retry immediately — prices change quickly and a new quote may succeed + 2. Increase `slippageBps` if retries continue to fail (e.g. from 100 to 200) + 3. For large swaps, consider splitting into smaller amounts to reduce price impact + delegation_not_found: |- + This error occurs when a delegated signing operation is attempted but no active + delegation grant exists for the end user (or account). + + **Steps to resolve:** + 1. Create a delegation grant using `createDelegationForEndUser` (user-scoped) + or `createDelegationForEndUserAccount` (account-scoped) before calling + the signing or sending operation + 2. If you previously created a grant, it may have expired or been revoked — + in those cases you would receive a `delegation_expired` or + `delegation_revoked` error instead + 3. For account-scoped grants, verify the address in the request matches the + granted address (EVM addresses are compared case-insensitively; + Solana addresses must match exactly) + delegation_expired: |- + This error occurs when the delegation grant used for signing has expired. + Delegation grants have a limited lifetime set at creation. - **Limits:** - - Maximum entries: 10 - metadata_key_too_long: |- - This error occurs when a metadata key exceeds the maximum allowed length. + **Steps to resolve:** + 1. Create a new delegation grant using `createDelegationForEndUser` or + `createDelegationForEndUserAccount` + 2. Retry the signing operation with the new grant active + 3. Consider creating grants with a longer TTL if expiry is frequent + delegation_revoked: |- + This error occurs when the delegation grant has been explicitly revoked. **Steps to resolve:** - 1. Shorten the metadata key to 40 characters or less - 2. Use abbreviations or shorter naming conventions - 3. Consider using a key-value structure where the value contains the longer identifier + 1. Create a new delegation grant using `createDelegationForEndUser` or + `createDelegationForEndUserAccount` + 2. Confirm with the end user before recreating, since revocation is + typically intentional + delegation_not_authorized: |- + This error occurs when a delegation grant exists but does not authorize the + requested operation. - **Limits:** - - Maximum key length: 40 characters - metadata_value_too_long: |- - This error occurs when a metadata value exceeds the maximum allowed length. + **Steps to resolve:** + 1. For account-scoped grants, verify the signing address matches the address + the grant was created for + 2. Check that the operation is permitted for delegated signing on your project + 3. Create a grant with the correct scope if needed + delegation_not_enabled: |- + This error occurs when delegated signing is attempted on a project that has + not enabled the feature. **Steps to resolve:** - 1. Shorten the metadata value to 500 characters or less - 2. Store longer data externally and reference it with a shorter identifier - 3. Consider compressing or encoding the data if appropriate + 1. Enable delegated signing in your project configuration via the CDP Portal + 2. Contact support if you believe delegated signing should already be enabled + for your project + Url: + type: string + format: uri + minLength: 11 + maxLength: 2048 + pattern: ^https?://.*$ + description: A valid HTTP or HTTPS URL. + example: https://example.com + Error: + description: An error response including the code for the type of error and a human-readable message describing the error. + type: object + properties: + errorType: + $ref: '#/components/schemas/ErrorType' + errorMessage: + description: The error message. + type: string + example: Unable to create EVM account + correlationId: + description: A unique identifier for the request that generated the error. This can be used to help debug issues with the API. + type: string + example: 41deb8d59a9dc9a7-IAD + errorLink: + allOf: + - $ref: '#/components/schemas/Url' + description: A link to the corresponding error documentation. + example: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request + required: + - errorType + - errorMessage + example: + errorType: invalid_request + errorMessage: Invalid request. + correlationId: 41deb8d59a9dc9a7-IAD + errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request + CreateAccountRequest: + type: object + properties: + name: + $ref: '#/components/schemas/AccountName' + Asset: + type: string + minLength: 1 + maxLength: 42 + description: The symbol of the asset (e.g., eth, usd, usdc, usdt). + example: usd + AssetType: + type: string + description: The type of the asset. + enum: + - fiat + - crypto + example: crypto + balances_Asset: + type: object + description: An asset, e.g. fiat or crypto. + properties: + symbol: + $ref: '#/components/schemas/Asset' + type: + $ref: '#/components/schemas/AssetType' + name: + type: string + description: The name of the asset. + decimals: + type: integer + description: The number of decimals (i.e. significant digits to the right of the decimal point) supported for the asset. + required: + - symbol + - type + - name + - decimals + example: + symbol: btc + type: crypto + name: Bitcoin + decimals: 8 + AmountDetail: + type: object + description: Available and total amounts for a specific currency. + properties: + available: + type: string + description: The amount that is currently available to be used. + example: '2.5' + total: + type: string + description: The total amount, including the amount that is currently on hold. + example: '3.0' + required: + - available + - total + Balance: + type: object + description: A balance of an asset. + properties: + asset: + $ref: '#/components/schemas/balances_Asset' + amount: + type: object + description: |- + Amount details denominated in different assets. + - The keys represent the asset symbols (e.g., "btc", "usd"), - Each value contains available and total amounts. - There will always be an entry for the asset specified in the `asset` field. + additionalProperties: + $ref: '#/components/schemas/AmountDetail' + required: + - asset + - amount + example: + asset: + symbol: btc + type: crypto + name: Bitcoin + decimals: 8 + amount: + btc: + available: '2.5' + total: '3.0' + usd: + available: '252705.4' + total: '303246.48' + Balances: + type: object + description: A list of balances for an account. + properties: + balances: + type: array + description: The list of balances. + items: + $ref: '#/components/schemas/Balance' + example: + - asset: + symbol: btc + type: crypto + name: Bitcoin + decimals: 8 + amount: + btc: + available: '2.5' + total: '3.0' + usd: + available: '252705.4' + total: '303246.48' + required: + - balances + example: + balances: + - asset: + symbol: btc + type: crypto + name: Bitcoin + decimals: 8 + amount: + btc: + available: '2.5' + total: '3.0' + usd: + available: '252705.4' + total: '303246.48' + - asset: + symbol: usd + type: fiat + name: United States Dollar + decimals: 2 + amount: + usd: + available: '90' + total: '100' + DepositDestinationType: + type: string + description: The type of deposit destination. + oneOf: + - enum: + - crypto + example: crypto + DepositDestinationId: + type: string + pattern: ^depositDestination_[a-f0-9\-]{36}$ + description: The ID of the Deposit Destination, which is a UUID prefixed by the string `depositDestination_`. + example: depositDestination_af2937b0-9846-4fe7-bfe9-ccc22d935114 + Network: + type: string + description: The blockchain network for the payment. Supported networks depend on the account type. See [API and Network Support](https://docs.cdp.coinbase.com/api-reference/payment-apis/supported-networks-assets#by-asset-and-network) for more details. + enum: + - base + - ethereum + - solana + - aptos + - arbitrum + - arbitrum-sepolia + - optimism + - polygon + - world + - world-sepolia + example: base + BlockchainAddress: + type: string + minLength: 1 + maxLength: 128 + description: A blockchain address. Format varies by network (e.g., 0x-prefixed for EVM, base58 for Solana). + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + DepositDestinationCrypto: + type: object + description: Crypto-specific deposit destination details. In responses, this object is always present. Contains the network and address for the deposit destination. + properties: + network: + $ref: '#/components/schemas/Network' + address: + $ref: '#/components/schemas/BlockchainAddress' + required: + - network + - address + example: + network: base + address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + DepositDestinationTargetAccount: + type: object + title: Target Account + description: The account and asset where incoming deposits should be credited. + additionalProperties: false + properties: + accountId: + allOf: + - $ref: '#/components/schemas/AccountId' + description: The ID of the CDP Account to which deposited funds should be transferred. + asset: + allOf: + - $ref: '#/components/schemas/Asset' + description: The symbol of the asset that should land in the target account. + example: usd + required: + - asset + example: + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + asset: usd + DepositDestinationTarget: + description: The intended target for deposited funds. + oneOf: + - $ref: '#/components/schemas/DepositDestinationTargetAccount' + DepositDestinationStatus: + type: string + description: The status of the deposit destination. + enum: + - active + - inactive + - pending + example: active + Metadata: + type: object + description: Optional metadata as key-value pairs. Use this to store additional structured information on a resource, such as customer IDs, order references, or any application-specific data. Up to 10 key/value pairs may be provided. Keys and values are both strings. Keys must be ≤ 40 characters; values must be ≤ 500 characters. + additionalProperties: + type: string + minLength: 0 + maxLength: 500 + maxProperties: 10 + example: + customer_id: cust_12345 + order_reference: order-67890 + CryptoDepositDestination: + type: object + description: A cryptocurrency deposit destination. + properties: + depositDestinationId: + $ref: '#/components/schemas/DepositDestinationId' + accountId: + $ref: '#/components/schemas/AccountId' + type: + type: string + description: The type of deposit destination. + enum: + - crypto + example: crypto + crypto: + allOf: + - $ref: '#/components/schemas/DepositDestinationCrypto' + description: Crypto-specific details for this deposit destination. Always populated in responses. Contains the network and address. + target: + $ref: '#/components/schemas/DepositDestinationTarget' + status: + $ref: '#/components/schemas/DepositDestinationStatus' + metadata: + $ref: '#/components/schemas/Metadata' + createdAt: + type: string + format: date-time + description: The timestamp when the deposit destination was created. + example: '2023-10-08T14:30:00Z' + updatedAt: + type: string + format: date-time + description: The timestamp when the deposit destination was last updated. + example: '2023-10-08T14:30:00Z' + required: + - depositDestinationId + - accountId + - type + - crypto + - status + - createdAt + - updatedAt + example: + depositDestinationId: depositDestination_af2937b0-9846-4fe7-bfe9-ccc22d935114 + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + type: crypto + crypto: + network: base + address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + target: + accountId: account_bf3847c1-a957-5ae8-cfa0-ddd33e046225 + asset: usd + status: active + metadata: + customer_id: 123e4567-e89b-12d3-a456-426614174000 + reference: order-12345 + createdAt: '2023-10-08T14:30:00Z' + updatedAt: '2023-10-08T14:30:00Z' + DepositDestination: + description: A deposit destination for receiving funds to an account. + oneOf: + - $ref: '#/components/schemas/CryptoDepositDestination' + discriminator: + propertyName: type + mapping: + crypto: '#/components/schemas/CryptoDepositDestination' + CreateDepositDestinationRequestBase: + type: object + description: Common fields for creating a deposit destination. + properties: + accountId: + description: The ID of the Account, which is a UUID prefixed by the string `account_`, that owns the deposit destination. + $ref: '#/components/schemas/AccountId' + type: + $ref: '#/components/schemas/DepositDestinationType' + target: + $ref: '#/components/schemas/DepositDestinationTarget' + metadata: + $ref: '#/components/schemas/Metadata' + required: + - accountId + - type + example: + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + type: crypto + target: + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + asset: usd + CreateDepositDestinationCrypto: + type: object + description: Crypto-specific details for creating a deposit destination. + properties: + network: + $ref: '#/components/schemas/Network' + required: + - network + example: + network: base + CreateCryptoDepositDestinationRequest: + allOf: + - $ref: '#/components/schemas/CreateDepositDestinationRequestBase' + - type: object + properties: + type: + type: string + enum: + - crypto + crypto: + allOf: + - $ref: '#/components/schemas/CreateDepositDestinationCrypto' + description: Crypto-specific details. Required when `type` is `crypto`. + required: + - crypto + example: + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + type: crypto + crypto: + network: base + target: + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + asset: usd + metadata: + customer_id: 123e4567-e89b-12d3-a456-426614174000 + reference: order-12345 + CreateDepositDestinationRequest: + description: Request to create a new deposit destination. Provide the type-specific details matching the chosen `type`. + discriminator: + propertyName: type + mapping: + crypto: '#/components/schemas/CreateCryptoDepositDestinationRequest' + oneOf: + - $ref: '#/components/schemas/CreateCryptoDepositDestinationRequest' + TransferStatus: + type: string + description: The current status of the transfer, indicating what action you need to take next. Required when validateOnly is false. + enum: + - quoted + - processing + - completed + - failed + example: quoted + x-enum-descriptions: + - 'Transfer was created with `execute: true`, but is momentarily being quoted before executing _or_ the transfer was created with `execute: false`. It can be executed by calling `/v2/transfers/{transferId}/execute` with `execute: true`.' + - Transfer is executing after being quoted. No action needed - monitor progress via the transfers webhook. + - Transfer completed successfully. + - Transfer failed. See `failureReason` for details. + transfers_Account: + type: object + title: Account + description: The Account specific details for the transfer. + properties: + accountId: + type: string + description: The ID of the Account. + asset: + $ref: '#/components/schemas/Asset' + required: + - accountId + - asset + example: + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + asset: usd + PaymentMethod: + type: object + title: Payment Method + description: The Payment Method specific details for the transfer. + properties: + paymentMethodId: + type: string + description: The ID of the Payment Method. + asset: + $ref: '#/components/schemas/Asset' + required: + - paymentMethodId + - asset + example: + paymentMethodId: pm_af2937b0-9846-4fe7-bfe9-ccc22d935114 + asset: usd + OnchainAddress: + type: object + title: Onchain Address + description: The target of the payment is an onchain address. + properties: + address: + allOf: + - $ref: '#/components/schemas/BlockchainAddress' + description: | + The onchain crypto address of the recipient. - **Limits:** - - Maximum value length: 500 characters - travel_rules_field_missing: |- - This error occurs when required travel rule fields are missing from the transfer request. + Examples: + - EVM address: 0xabc1234567890abcdef1234567890abcdef123456 + - Solana address: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + - XRP address: rhccc5p23aKiCGFcEqqnjEfLRZ6xEvfy3s + network: + $ref: '#/components/schemas/Network' + destinationTag: + type: string + description: | + The destination tag of the onchain address. Destination tags are used by certain networks + (primarily XRP/Ripple) to identify specific recipients when multiple users share a single address. + The tag ensures funds are credited to the correct account within the shared address. + + Examples by network: + - XRP/Ripple: Numeric values like "1234567890" or "123456" + - Stellar (XLM): Memos which can be text, ID, or hash format + + Note: Most networks (Ethereum, Bitcoin, Solana) do not use destination tags. + asset: + allOf: + - $ref: '#/components/schemas/Asset' + description: Asset symbol of the payment received by the recipient. + example: btc + required: + - address + - network + - asset + example: + address: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' + network: base + asset: usdc + OriginatingBankAccountUS: + type: object + title: Originating Bank Account (US) + description: The originating US bank account details for the transfer source. Present when funds were deposited from an external bank account into a deposit destination. Only the last 4 digits of the account number are exposed. + properties: + bankName: + type: string + description: The name of the bank that originated the deposit. + example: Citibank, N.A. + accountLast4: + type: string + description: The last 4 digits of the originating bank account number. + pattern: ^[0-9]{4}$ + example: '6789' + currency: + type: string + description: The fiat currency of the deposit (e.g., `usd`). + example: usd + required: + - bankName + - accountLast4 + - currency + example: + bankName: Citibank, N.A. + accountLast4: '6789' + currency: usd + TransferSource: + description: The source of the transfer. + oneOf: + - $ref: '#/components/schemas/transfers_Account' + - $ref: '#/components/schemas/PaymentMethod' + - $ref: '#/components/schemas/OnchainAddress' + - $ref: '#/components/schemas/OriginatingBankAccountUS' + example: {} + EmailAddress: + type: object + title: Email Address + description: The target of the payment is an email address. + properties: + email: + type: string + format: email + description: The email address of the recipient. The recipient will need to have an account with Coinbase or onboard to Coinbase to receive the payment. + required: + - email + example: + email: recipient@example.com + EmailInstrument: + title: Email Instrument + description: The target of the payment is an email address. + allOf: + - $ref: '#/components/schemas/EmailAddress' + - type: object + properties: + asset: + allOf: + - $ref: '#/components/schemas/Asset' + description: Asset symbol of the payment received by the recipient. + required: + - asset + example: + email: recipient@example.com + asset: usd + TransferTarget: + description: The target of the transfer. + oneOf: + - $ref: '#/components/schemas/transfers_Account' + - $ref: '#/components/schemas/PaymentMethod' + - $ref: '#/components/schemas/OnchainAddress' + - $ref: '#/components/schemas/EmailInstrument' + example: {} + TransferExchangeRate: + type: object + description: Exchange rate information for currency conversion. The rate indicates how much of the target asset is equivalent to one unit of the source asset. + properties: + sourceAsset: + allOf: + - $ref: '#/components/schemas/Asset' + description: The asset being converted from. + example: usd + targetAsset: + allOf: + - $ref: '#/components/schemas/Asset' + description: The asset being converted to. + example: usdc + rate: + type: string + description: The exchange rate value as a decimal string. Indicates how many units of the target asset equal one unit of the source asset. + example: '1' + required: + - sourceAsset + - targetAsset + - rate + example: + sourceAsset: usd + targetAsset: usdc + rate: '1' + TransferFee: + type: object + description: A single fee for a transfer. + properties: + type: + type: string + description: The type of the fee, indicating its purpose. + enum: + - bank + - conversion + - network + - other + x-enum-varnames: + - BankFee + - ConversionFee + - NetworkFee + - OtherFee + example: network + amount: + type: string + description: The amount of the fee in units of the asset specified by `asset`. + example: '1500000' + asset: + allOf: + - $ref: '#/components/schemas/Asset' + description: The asset symbol. + example: usd + required: + - type + - amount + - asset + TransferFees: + type: array + description: |- + The fees associated with this transfer. Different transfer types have different fee structures. - **Steps to resolve:** - 1. Include the `travelRule` object in your transfer request - 2. Supply the required missing fields prompted by the error message - 3. Review the travel rule requirements for your jurisdiction + **NOTE:** These examples are not exhaustive. - Note: Required fields may vary by region. - asset_mismatch: |- - This error occurs when the assets specified in the transfer are incompatible or don't match expected values. + Common examples: + * **Crypto transfers**: Network fees (gas) paid in the native token + * **Fiat conversions**: Processing fees + exchange fees in USD + * **Wire transfers**: Wire fees ($15) + processing fees ($5) in USD + * **Crypto conversions**: Spread fees paid in the source asset. + example: + - type: bank + amount: '20' + asset: usd + - type: conversion + amount: '1.00' + asset: usdc + - type: network + amount: '0.01' + asset: usdc + items: + $ref: '#/components/schemas/TransferFee' + TransferEstimate: + type: object + description: |- + A point-in-time snapshot of estimated values for a transfer where exact amounts cannot be locked in at quote time (e.g., when the executed rate is determined at execution time and moves with the market). - **Steps to resolve:** - 1. Ensure the `asset` field matches either the source or target asset - 2. Verify that the source and target assets are compatible for conversion (if different) - 3. Check that the asset symbols are correctly specified + Present in both pre-execution and post-execution states: + * **Quoted state:** top-level fields whose values cannot be guaranteed are absent; + `estimate` holds their estimated values. - **Common causes:** - - Transfer asset doesn't match source or target - - Attempting an unsupported asset conversion - - Typo in asset symbols - order_quote_expired: |- - This error occurs when attempting to execute an order whose quote has expired. + * **Completed state:** top-level fields contain the actual executed values; + `estimate` is retained as an immutable audit snapshot of the pre-execution estimate. + properties: + exchangeRate: + $ref: '#/components/schemas/TransferExchangeRate' + targetAmount: + type: string + description: Estimated amount of the target asset that will be received, as a decimal string in standard unit denomination. + example: '85.00' + targetAsset: + allOf: + - $ref: '#/components/schemas/Asset' + description: The asset symbol of the estimated target amount. + example: eur + fees: + $ref: '#/components/schemas/TransferFees' + estimatedAt: + type: string + format: date-time + description: The date and time when this estimate was captured. + example: '2023-10-08T14:30:00Z' + required: + - estimatedAt + example: + exchangeRate: + sourceAsset: usdc + targetAsset: eur + rate: '0.85' + targetAmount: '85.00' + targetAsset: eur + fees: + - type: conversion + amount: '0.01' + asset: usdc + estimatedAt: '2023-10-08T14:30:00Z' + DepositDestinationReference: + type: object + description: A reference to the deposit destination associated with the transfer. + properties: + id: + $ref: '#/components/schemas/DepositDestinationId' + required: + - id + example: + id: depositDestination_af2937b0-9846-4fe7-bfe9-ccc22d935114 + TravelRuleStatus: + type: string + description: The status of a travel rule submission. + enum: + - incomplete + - completed + x-enum-varnames: + - TravelRuleStatusIncomplete + - TravelRuleStatusCompleted + x-enum-descriptions: + - Additional fields are required before the transfer can proceed. + - All requirements are satisfied and the transfer will proceed. + example: incomplete + TransferDetails: + type: object + description: Additional details about the transfer. For example, if the transfer was sent to a deposit destination, the information about that destination will be included in this field. + properties: + depositDestination: + $ref: '#/components/schemas/DepositDestinationReference' + onchainTransactions: + type: array + description: The onchain transactions associated with the transfer. + items: + type: object + description: An onchain transaction associated with the transfer. + properties: + transactionHash: + type: string + description: The transaction hash. + example: '0x363cd3b3d4f49497cf5076150cd709307b90e9fc897fdd623546ea7b9313cecb' + network: + $ref: '#/components/schemas/Network' + required: + - transactionHash + - network + example: + - transactionHash: '0x363cd3b3d4f49497cf5076150cd709307b90e9fc897fdd623546ea7b9313cecb' + network: base + travelRule: + type: object + description: Travel rule compliance status for deposit transfers. Present when the transfer requires travel rule information. + properties: + status: + $ref: '#/components/schemas/TravelRuleStatus' + statusMessage: + type: string + description: Additional details about the current travel rule status. For example, when status is `incomplete`, this may indicate the specific missing information required to proceed. + example: Originator date of birth is required. + example: + status: incomplete + statusMessage: Originator date of birth is required. + example: + depositDestination: + id: depositDestination_af2937b0-9846-4fe7-bfe9-ccc22d935114 + onchainTransactions: + - transactionHash: '0x363cd3b3d4f49497cf5076150cd709307b90e9fc897fdd623546ea7b9313cecb' + network: base + Transfer: + type: object + description: A Transfer represents all the information needed to execute a transfer and tracks the lifecycle of a transfer from initiation through completion or failure. + properties: + transferId: + type: string + description: The ID of the transfer. Required when validateOnly is false. + example: transfer_af2937b0-9846-4fe7-bfe9-ccc22d935114 + status: + $ref: '#/components/schemas/TransferStatus' + source: + $ref: '#/components/schemas/TransferSource' + target: + $ref: '#/components/schemas/TransferTarget' + sourceAmount: + type: string + description: The amount of the source asset that will be transferred out, as a decimal string in standard unit denomination. + example: '103.50' + sourceAsset: + allOf: + - $ref: '#/components/schemas/Asset' + description: The asset symbol of the source amount. + example: usd + targetAmount: + type: string + description: The amount of the target asset that will be received, as a decimal string in standard unit denomination. + example: '100.00' + targetAsset: + allOf: + - $ref: '#/components/schemas/Asset' + description: The asset symbol of the target amount. + example: usdc + exchangeRate: + $ref: '#/components/schemas/TransferExchangeRate' + fees: + $ref: '#/components/schemas/TransferFees' + estimate: + $ref: '#/components/schemas/TransferEstimate' + completedAt: + type: string + format: date-time + description: The date and time the transfer was completed. + example: '2025-01-01T00:05:00Z' + failureReason: + type: string + description: The reason for failure, if the transfer failed. Only present when status is `failed`. + example: Insufficient balance to complete this transfer. + expiresAt: + type: string + format: date-time + description: The date and time when this transfer will expire if not executed. Only present for `quoted` status. A new transfer must be created to obtain an updated quote after expiration. Required when validateOnly is false. + example: '2025-01-01T00:15:00Z' + executedAt: + type: string + format: date-time + description: The date and time the transfer was executed and moved to processing. Only present when status has progressed beyond `quoted`. + example: '2025-01-01T00:01:30Z' + createdAt: + type: string + format: date-time + description: The date and time the transfer was created. Required when validateOnly is false. + example: '2025-01-01T00:00:00Z' + updatedAt: + type: string + format: date-time + description: The date and time the transfer was last updated. Required when validateOnly is false. + example: '2025-01-01T00:00:00Z' + metadata: + $ref: '#/components/schemas/Metadata' + details: + $ref: '#/components/schemas/TransferDetails' + required: + - source + - target + CreateTransferSource: + description: The source of the transfer. + oneOf: + - $ref: '#/components/schemas/transfers_Account' + - $ref: '#/components/schemas/PaymentMethod' + example: {} + PhysicalAddress: + type: object + description: A physical address with standard address components including street, city, state/province, postal code, and country. + properties: + line1: + type: string + description: Primary street address. + example: 123 Market St + line2: + type: string + description: Secondary address information. + example: Suite 400 + city: + type: string + description: City or locality. + example: San Francisco + state: + type: string + description: State, province, or region. + example: CA + postCode: + type: string + description: Postal or ZIP code. + example: '94105' + countryCode: + type: string + minLength: 2 + maxLength: 2 + description: ISO 3166-1 alpha-2 country code (2 characters). See https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes. + example: US + TravelRuleParty: + type: object + description: Information about a party (originator or beneficiary) for travel rule compliance. + properties: + financialInstitution: + type: string + description: Name of the financial institution. + example: PayPal, Inc. + name: + type: string + description: Full name of the party. + example: John Doe + address: + $ref: '#/components/schemas/PhysicalAddress' + example: + name: John Doe + address: + line1: 123 Main St + line2: Unit 201 + city: San Francisco + state: California + postCode: '94105' + countryCode: US + TravelRuleOriginator: + allOf: + - $ref: '#/components/schemas/TravelRuleParty' + - type: object + properties: + virtualAssetServiceProvider: + type: object + description: Information about the originating Virtual Asset Service Provider (VASP) that handles cryptocurrency or other virtual assets on behalf of customers. + properties: + name: + type: string + description: The name of the originating Virtual Asset Service Provider (VASP). + example: Fidelity Digital Asset Services, LLC + address: + description: The address of the originating Virtual Asset Service Provider (VASP). + $ref: '#/components/schemas/PhysicalAddress' + identifier: + type: string + description: The Legal Entity Identifier of the originating Virtual Asset Service Provider (VASP). + example: 5493001KJTIIGC8Y1R17 + description: Originator (sender) party. + TravelRuleBeneficiary: + allOf: + - $ref: '#/components/schemas/TravelRuleParty' + - type: object + properties: + walletType: + type: string + description: The type of the beneficiary's wallet. + enum: + - custodial + - self_custody + example: custodial + description: Beneficiary (receiver) party. + TravelRule: + type: object + description: Required Travel Rule fields differ by region. These requirements are determined based on which Coinbase entity the customer has signed the service agreement for. + properties: + isSelf: + type: boolean + description: Indicates whether the user attests that the receiving wallet belongs to them. + example: true + isIntermediary: + type: boolean + description: | + Indicates whether Coinbase is being used as an intermediary Virtual Asset Service Provider (VASP) to send crypto on behalf of your customer. - **Steps to resolve:** - 1. Create a new order with `execute: false` to get an updated quote. - 2. Execute the new order before the quote expires (check the `expiresAt` field). - 3. Alternatively, create a new order with `execute: true` to skip the quote step and execute immediately. - order_already_filled: |- - This error occurs when attempting to cancel or modify an order that has already been filled. + **Background:** - **Steps to resolve:** - 1. Check the current status of the order using `GET /v2/orders/{orderId}`. - 2. A filled order cannot be canceled or re-executed. - order_already_canceled: |- - This error occurs when attempting to cancel or execute an order that has already been canceled. + The Travel Rule (FATF Recommendation 16) requires VASPs to share originator and beneficiary information for virtual asset transfers. When Coinbase acts as an intermediary, additional Travel Rule data must be provided to satisfy compliance requirements. - **Steps to resolve:** - 1. Check the current status of the order using `GET /v2/orders/{orderId}`. - 2. Create a new order if you still want to trade. - account_not_ready: |- - This error occurs when an operation is attempted on an account that is still being provisioned. + **Set to `true` when:** - **Steps to resolve:** - 1. Wait a few moments and retry the request - 2. If the error persists, the account may still be completing setup — retry with exponential backoff - insufficient_liquidity: |- - This error occurs when no swap route is available for the requested token pair or amount. + - Your organization is a VASP using Coinbase to send crypto **on behalf of your end customer** + - In this scenario, Coinbase acts as an intermediary in the transfer chain and handles Travel Rule data exchange with the beneficiary VASP - **Steps to resolve:** - 1. Try a smaller `fromAmount` — large orders may exceed available liquidity - 2. Try a different token pair - 3. Retry after a short delay; liquidity conditions change with market activity - insufficient_allowance: |- - This error occurs when the taker has not approved the Permit2 contract to spend the `fromToken` - on their behalf. ERC-20 swaps require a Permit2 allowance. Native ETH swaps do not. + **Set to `false` (or omit) when:** - **Steps to resolve:** - 1. Submit an ERC-20 `approve` transaction on the `fromToken` contract, granting the Permit2 - contract (`0x000000000022D473030F116dDEE9F6B43aC78BA3`) an allowance of at least `fromAmount` - 2. Wait for the approval transaction to be confirmed on-chain - 3. Retry the swap + - You are transferring funds directly from your own Coinbase account, where **Coinbase is your primary VASP** rather than an intermediary for another institution - **Example:** - ```typescript lines wrap - // Approve Permit2 to spend fromToken - await walletClient.writeContract({ - address: fromToken, - abi: erc20Abi, - functionName: "approve", - args: ["0x000000000022D473030F116dDEE9F6B43aC78BA3", fromAmount], - }); - ``` - transaction_simulation_failed: |- - This error occurs when the pre-broadcast simulation of the swap transaction predicted a revert. - No transaction was submitted and no gas was spent. + **Impact on required fields:** - **Common causes:** - - The on-chain price moved past the `slippageBps` tolerance between the price estimate and execution - - Taker balance changed between the price estimate and execution + When `isIntermediary` is `true`, you must provide the `originator` object with details about the original sender, including: + - Originator name + - Originator address + - Your VASP information (`virtualAssetServiceProvider` object with `name`, `address`, and `identifier`) + example: true + originator: + $ref: '#/components/schemas/TravelRuleOriginator' + beneficiary: + $ref: '#/components/schemas/TravelRuleBeneficiary' + example: + isSelf: false + isIntermediary: true + originator: + name: John Doe + address: + line1: 123 Main St + line2: Unit 201 + city: Luxembourg + postCode: L-1234 + countryCode: LU + financialInstitution: PayPal, Inc. + vasp: + name: Fidelity Digital Asset Services, LLC + address: + line1: 123 Market St + line2: Suite 400 + city: San Francisco + state: California + postCode: '94105' + countryCode: US + identifier: 5493001KJTIIGC8Y1R17 + beneficiary: + name: Jane Smith + address: + line1: 456 Oak Ave + city: Paris + postCode: '75001' + countryCode: FR + walletType: custodial + TransferRequest: + type: object + description: A request to create a transfer. + properties: + source: + $ref: '#/components/schemas/CreateTransferSource' + target: + $ref: '#/components/schemas/TransferTarget' + amount: + type: string + description: The amount of the transfer, as a decimal string in standard unit denomination of the asset specified by `asset` (e.g., "100.00" for 100 USD, "0.05" for 0.05 ETH). + example: '100.00' + asset: + allOf: + - $ref: '#/components/schemas/Asset' + description: The symbol of the asset for the amount. This must be one of the assets of the source or target. + example: usd + amountType: + type: string + default: source + description: | + Specifies whether the given amount is to be received by the target or taken from the source. - **Steps to resolve:** - 1. Retry immediately — prices change quickly and a new quote may succeed - 2. Increase `slippageBps` if retries continue to fail (e.g. from 100 to 200) - 3. For large swaps, consider splitting into smaller amounts to reduce price impact - Url: + - `target`: The transfer `target` receives the exact value specified in `amount`. Fees are added to the amount taken from the transfer `source`. + - `source`: The transfer `target` receives the value specified in `amount`, minus any fees. + enum: + - target + - source + example: source + validateOnly: + type: boolean + default: false + description: If true, validates the transfer without initiating it. If the request is valid, a 2xx will be returned. If the request is invalid, a 4xx error will be returned. The response will include an errorType, for e.g. invalid_target if the specified target cannot receive funds. + example: false + execute: + type: boolean + description: Whether to immediately execute the transfer. If false, the transfer will be created in quoted status and must be executed manually via the /execute endpoint. + example: true + metadata: + $ref: '#/components/schemas/Metadata' + travelRule: + $ref: '#/components/schemas/TravelRule' + required: + - source + - target + - amount + - asset + - execute + DepositTravelRuleVasp: + type: object + description: Information about the Virtual Asset Service Provider (VASP) for a deposit travel rule submission. + properties: + identifier: + type: string + description: The Legal Entity Identifier (LEI) of the Virtual Asset Service Provider (VASP). + example: 5493001KJTIIGC8Y1R17 + name: + type: string + description: The name of the Virtual Asset Service Provider (VASP). + example: Fidelity Digital Asset Services, LLC + example: + identifier: 5493001KJTIIGC8Y1R17 + name: Fidelity Digital Asset Services, LLC + DateOfBirth: + type: object + description: Date of birth. + properties: + day: + type: string + description: Day of birth (01-31). + minLength: 2 + maxLength: 2 + pattern: ^[0-9]{2}$ + example: '15' + month: + type: string + description: Month of birth (01-12). + minLength: 2 + maxLength: 2 + pattern: ^[0-9]{2}$ + example: '08' + year: + type: string + description: Year of birth (four digits). + minLength: 4 + maxLength: 4 + pattern: ^[0-9]{4}$ + example: '1990' + example: + day: '15' + month: '08' + year: '1990' + DepositTravelRuleOriginator: + type: object + description: Originator information for a deposit travel rule submission. + properties: + name: + type: string + description: Full name of the originator. + example: John Doe + address: + $ref: '#/components/schemas/PhysicalAddress' + walletType: + type: string + description: The type of the originator's wallet. + enum: + - custodial + - self_custody + x-enum-descriptions: + - The originator's wallet is held by a custodial service. + - The originator's wallet is self-custodied. + example: custodial + virtualAssetServiceProvider: + $ref: '#/components/schemas/DepositTravelRuleVasp' + personalId: + type: string + description: Government-issued personal identification number for the originator. + example: 123-45-6789 + dateOfBirth: + $ref: '#/components/schemas/DateOfBirth' + example: + name: John Doe + address: + line1: 123 Main St + city: San Francisco + state: CA + postCode: '94105' + countryCode: US + walletType: custodial + vasp: + identifier: 5493001KJTIIGC8Y1R17 + name: Fidelity Digital Asset Services, LLC + DepositTravelRuleBeneficiary: + type: object + description: Beneficiary information for a deposit travel rule submission. + properties: + name: + type: string + description: Full name of the beneficiary. + example: Jane Smith + example: + name: Jane Smith + DepositTravelRuleRequest: + type: object + description: Request body for submitting travel rule information for a deposit transfer. Required fields vary by jurisdiction. + properties: + originator: + $ref: '#/components/schemas/DepositTravelRuleOriginator' + beneficiary: + $ref: '#/components/schemas/DepositTravelRuleBeneficiary' + isSelf: + type: boolean + description: Indicates whether the user attests that the originating wallet belongs to them. + example: false + example: + originator: + name: John Doe + address: + line1: 123 Main St + city: San Francisco + state: CA + postCode: '94105' + countryCode: US + beneficiary: + name: Jane Smith + isSelf: false + DepositTravelRuleResponse: + type: object + description: Response from submitting travel rule information for a deposit transfer. + properties: + status: + $ref: '#/components/schemas/TravelRuleStatus' + missingFields: + type: array + description: List of field paths that are still required to complete travel rule compliance. Each entry is a dot-separated path (e.g., "originator.name", "originator.address.countryCode"). Empty when status is "completed". + items: + type: string + example: originator.name + example: + - originator.address.countryCode + reason: + type: string + description: Additional context about the current status. Present when status is `incomplete` to explain what needs to be fixed before the transfer can proceed. + example: Originator date of birth is required. + required: + - status + example: + status: incomplete + missingFields: + - originator.address.countryCode + EmailAuthentication: + type: object + title: EmailAuthentication + description: Information about an end user who authenticates using a one-time password sent to their email address. + properties: + type: + type: string + description: The type of authentication information. + example: email + enum: + - email + email: + type: string + description: The email address of the end user. + example: user@example.com + format: email + required: + - type + - email + SmsAuthentication: + type: object + title: SmsAuthentication + description: Information about an end user who authenticates using a one-time password sent to their phone number via SMS. + properties: + type: + type: string + description: The type of authentication information. + example: sms + enum: + - sms + phoneNumber: + type: string + description: The phone number of the end user in E.164 format. + example: '+12055555555' + pattern: ^\+[1-9]\d{1,14}$ + required: + - type + - phoneNumber + DeveloperJWTAuthentication: + type: object + title: DeveloperJWTAuthentication + description: Information about an end user who authenticates using a JWT issued by the developer. + properties: + type: + type: string + description: The type of authentication information. + enum: + - jwt + example: jwt + kid: + type: string + description: The key ID of the JWK used to sign the JWT. + example: NjVBRjY5MDlCMUIwNzU4RTA2QzZFMDQ4QzQ2MDAyQjVDNjk1RTM2Qg + sub: + type: string + description: The unique identifier for the end user that is captured in the `sub` claim of the JWT. + example: e051beeb-7163-4527-a5b6-35e301529ff2 + required: + - type + - sub + - kid + OAuth2ProviderType: type: string - format: uri - minLength: 11 - maxLength: 2048 - pattern: ^https?://.*$ - description: A valid HTTP or HTTPS URL. - example: https://example.com - Error: - description: An error response including the code for the type of error and a human-readable message describing the error. + description: The type of OAuth2 provider. + enum: + - google + - apple + - x + - telegram + - github + example: google + OAuth2Authentication: + type: object + title: OAuth2Authentication + description: Information about an end user who authenticates using a third-party provider. + properties: + type: + $ref: '#/components/schemas/OAuth2ProviderType' + sub: + type: string + description: The unique identifier for the end user that is captured in the `sub` claim of the JWT. + example: e051beeb-7163-4527-a5b6-35e301529ff2 + email: + type: string + description: The email address of the end user contained within the user's ID token, if available from third-party OAuth2 provider's token exchange. + example: test.user@gmail.com + name: + type: string + description: The full name of the end user if available from third-party OAuth2 provider's token exchange. + example: Test User + username: + type: string + description: The username of the end user if available from third-party OAuth2 provider's token exchange. + example: test.user + required: + - type + - sub + TelegramAuthentication: + type: object + description: Information about an end user who authenticates using Telegram. + properties: + type: + $ref: '#/components/schemas/OAuth2ProviderType' + id: + type: integer + description: The Telegram ID for the end user. + example: 123456 + firstName: + type: string + description: The Telegram user's first name. + example: Satoshi + lastName: + type: string + description: The Telegram user's last name. + example: Nakamoto + photoUrl: + type: string + description: The Telegram user's profile picture. + example: https://image.url/profile.png + authDate: + type: integer + description: The Telegram user's last login as a Unix timestamp. + example: 1770681412 + username: + type: string + description: The Telegram user's username. + example: satoshinakamoto + required: + - type + - id + - authDate + SiweAuthentication: + type: object + title: SiweAuthentication + description: Information about an end user who authenticates using Sign In With Ethereum (EIP-4361). + properties: + type: + type: string + description: The type of authentication information. + example: siwe + enum: + - siwe + address: + allOf: + - $ref: '#/components/schemas/BlockchainAddress' + description: The ERC-55 checksummed Ethereum address of the end user. + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + required: + - type + - address + AuthenticationMethod: + description: Information about how the end user is authenticated. + oneOf: + - $ref: '#/components/schemas/EmailAuthentication' + - $ref: '#/components/schemas/SmsAuthentication' + - $ref: '#/components/schemas/DeveloperJWTAuthentication' + - $ref: '#/components/schemas/OAuth2Authentication' + - $ref: '#/components/schemas/TelegramAuthentication' + - $ref: '#/components/schemas/SiweAuthentication' + AuthenticationMethods: + type: array + description: The list of valid authentication methods linked to the end user. + items: + $ref: '#/components/schemas/AuthenticationMethod' + example: + - type: email + email: user@example.com + - type: sms + phoneNumber: '+12055555555' + - type: jwt + sub: e051beeb-7163-4527-a5b6-35e301529ff2 + kid: NjVBRjY5MDlCMUIwNzU4RTA2QzZFMDQ4QzQ2MDAyQjVDNjk1RTM2Qg + - type: google + sub: '115346410074741490243' + email: test.user@gmail.com + - type: telegram + id: 1223456 + firstName: Satoshi + lastName: Nakamoto + photoUrl: https://image.url/profile.jpg + authDate: 1770681412 + username: satoshinakamoto + - type: siwe + address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + MFAMethods: + x-audience: public + description: | + Information about the end user's MFA enrollments. + type: object + properties: + enrollmentPromptedAt: + type: string + format: date-time + description: The date and time when the end user was prompted for MFA enrollment, in ISO 8601 format. If the this field exists, and the user has no other enrolled MFA methods, then the user skipped MFA enrollment. + example: '2025-01-15T10:30:00Z' + totp: + type: object + description: An object containing information about the end user's TOTP enrollment. + required: + - enrolledAt + properties: + enrolledAt: + type: string + format: date-time + description: The date and time when the method was enrolled, in ISO 8601 format. + example: '2025-01-15T10:30:00Z' + sms: + type: object + description: An object containing information about the end user's SMS MFA enrollment. + required: + - enrolledAt + properties: + enrolledAt: + type: string + format: date-time + description: The date and time when the method was enrolled, in ISO 8601 format. + example: '2025-01-15T10:30:00Z' + example: + enrollmentPromptedAt: '2025-01-15T10:30:00Z' + totp: + enrolledAt: '2025-01-15T10:30:00Z' + sms: + enrolledAt: '2025-01-15T10:30:00Z' + EndUserEvmAccount: type: object + description: Information about an EVM account associated with an end user. properties: - errorType: - $ref: '#/components/schemas/ErrorType' - errorMessage: - description: The error message. + address: type: string - example: Unable to create EVM account - correlationId: - description: A unique identifier for the request that generated the error. This can be used to help debug issues with the API. + description: The address of the EVM account. + pattern: ^0x[0-9a-fA-F]{40}$ + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + createdAt: type: string - example: 41deb8d59a9dc9a7-IAD - errorLink: - allOf: - - $ref: '#/components/schemas/Url' - description: A link to the corresponding error documentation. - example: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request + format: date-time + description: The date and time when the account was created, in ISO 8601 format. + example: '2025-01-15T10:30:00Z' required: - - errorType - - errorMessage - example: - errorType: invalid_request - errorMessage: Invalid request. - correlationId: 41deb8d59a9dc9a7-IAD - errorLink: https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request - Asset: - type: string - minLength: 1 - maxLength: 42 - description: The symbol of the asset (e.g., eth, usd, usdc, usdt). - example: usd + - address + - createdAt + EndUserEvmSmartAccount: + type: object + description: Information about an EVM smart account associated with an end user. + properties: + address: + type: string + description: The address of the EVM smart account. + pattern: ^0x[0-9a-fA-F]{40}$ + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + ownerAddresses: + type: array + description: The addresses of the EVM EOA accounts that own this smart account. Smart accounts can have multiple owners, such as when spend permissions are enabled. + items: + type: string + description: The address of an EVM EOA account that owns this smart account. + pattern: ^0x[0-9a-fA-F]{40}$ + example: '0x1234567890abcdef1234567890abcdef12345678' + example: + - '0x1234567890abcdef1234567890abcdef12345678' + - '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd' + createdAt: + type: string + format: date-time + description: The date and time when the account was created, in ISO 8601 format. + example: '2025-01-15T10:30:00Z' + required: + - address + - ownerAddresses + - createdAt + EndUserSolanaAccount: + type: object + description: Information about a Solana account associated with an end user. + properties: + address: + type: string + description: The base58 encoded address of the Solana account. + pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ + example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + createdAt: + type: string + format: date-time + description: The date and time when the account was created, in ISO 8601 format. + example: '2025-01-15T10:30:00Z' + required: + - address + - createdAt + EndUser: + type: object + description: Information about the end user. + properties: + userId: + description: A stable, unique identifier for the end user. The `userId` must be unique across all end users in the developer's CDP Project. It must be between 1 and 100 characters long and can only contain alphanumeric characters and hyphens. + type: string + pattern: ^[a-zA-Z0-9-]{1,100}$ + example: e051beeb-7163-4527-a5b6-35e301529ff2 + authenticationMethods: + $ref: '#/components/schemas/AuthenticationMethods' + mfaMethods: + $ref: '#/components/schemas/MFAMethods' + evmAccounts: + type: array + deprecated: true + description: '**DEPRECATED**: Use `evmAccountObjects` instead for richer account information. The list of EVM account addresses associated with the end user. End users can have up to 10 EVM accounts.' + items: + type: string + description: The address of the EVM account associated with the end user. + pattern: ^0x[0-9a-fA-F]{40}$ + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + example: + - '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + evmAccountObjects: + type: array + description: The list of EVM accounts associated with the end user. End users can have up to 10 EVM accounts. + items: + $ref: '#/components/schemas/EndUserEvmAccount' + example: + - address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + createdAt: '2025-01-15T10:30:00Z' + - address: '0x1234567890abcdef1234567890abcdef12345678' + createdAt: '2025-01-15T11:00:00Z' + evmSmartAccounts: + type: array + deprecated: true + description: '**DEPRECATED**: Use `evmSmartAccountObjects` instead for richer account information including owner relationships. The list of EVM smart account addresses associated with the end user. Each EVM EOA can own one smart account.' + items: + type: string + description: The address of the EVM smart account associated with the end user. + pattern: ^0x[0-9a-fA-F]{40}$ + example: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + example: + - '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + evmSmartAccountObjects: + type: array + description: The list of EVM smart accounts associated with the end user. Each EVM EOA can own one smart account. + items: + $ref: '#/components/schemas/EndUserEvmSmartAccount' + example: + - address: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + ownerAddresses: + - '0x1234567890abcdef1234567890abcdef12345678' + - '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd' + createdAt: '2025-01-15T12:00:00Z' + solanaAccounts: + type: array + deprecated: true + description: '**DEPRECATED**: Use `solanaAccountObjects` instead for richer account information. The list of Solana account addresses associated with the end user. End users can have up to 10 Solana accounts.' + items: + type: string + description: The base58 encoded address of the Solana account associated with the end user. + pattern: ^[1-9A-HJ-NP-Za-km-z]{32,44}$ + example: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + example: + - HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + solanaAccountObjects: + type: array + description: The list of Solana accounts associated with the end user. End users can have up to 10 Solana accounts. + items: + $ref: '#/components/schemas/EndUserSolanaAccount' + example: + - address: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + createdAt: '2025-01-15T10:30:00Z' + - address: 9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin + createdAt: '2025-01-15T11:30:00Z' + createdAt: + type: string + format: date-time + description: The date and time when the end user was created, in ISO 8601 format. + example: '2025-01-15T10:30:00Z' + required: + - userId + - authenticationMethods + - evmAccounts + - evmAccountObjects + - evmSmartAccounts + - evmSmartAccountObjects + - solanaAccounts + - solanaAccountObjects + - createdAt EIP712Domain: type: object description: The domain of the EIP-712 typed data. @@ -13151,6 +15961,7 @@ components: oneOf: - $ref: '#/components/schemas/EthValueCriterion' - $ref: '#/components/schemas/EvmAddressCriterion' + - $ref: '#/components/schemas/EvmNetworkCriterion' - $ref: '#/components/schemas/EvmDataCriterion' - $ref: '#/components/schemas/NetUSDChangeCriterion' example: @@ -14195,17 +17006,6 @@ components: description: Total number of unique token addresses discovered. example: 15 minimum: 0 - Metadata: - type: object - description: Optional metadata as key-value pairs. Use this to store additional structured information on a resource, such as customer IDs, order references, or any application-specific data. Up to 10 key/value pairs may be provided. Keys and values are both strings. Keys must be ≤ 40 characters; values must be ≤ 500 characters. - additionalProperties: - type: string - minLength: 0 - maxLength: 500 - maxProperties: 10 - example: - customer_id: cust_12345 - order_reference: order-67890 WebhookTarget: type: object description: | @@ -15314,6 +18114,35 @@ components: schema: {} quality: $ref: '#/components/schemas/x402ResourceQuality' + serviceName: + type: string + description: | + Provider-supplied display name of the service this resource belongs to. This is a free-form + label for grouping and presentation only — it is not a stable identifier, and two resources + sharing the same `serviceName` are not guaranteed to belong to the same logical service. + example: Weather API + tags: + type: array + description: | + Provider-supplied, low-cardinality string labels associated with the resource for client-side + filtering and display. Values are free-form (no controlled vocabulary) and case-sensitive. + Order is not significant and duplicates are not expected. + items: + type: string + example: + - weather + - data + iconUrl: + allOf: + - $ref: '#/components/schemas/Url' + description: | + URL of a square icon representing the service this resource belongs to. Distinct from a + brand logo: this is intended for compact, list-view rendering (favicon-style) and is + normalized to a square aspect ratio at ingestion. The image is moderated and re-hosted by + Coinbase, so the URL is stable and safe to render directly in clients. Omitted when the + provider did not supply an icon, when the supplied icon failed moderation, or when image + processing was unavailable at ingestion time. + example: https://res.cloudinary.com/bdb-prod/image/upload/... required: - resource - type @@ -15329,7 +18158,35 @@ components: description: List of discovered x402 resources. items: $ref: '#/components/schemas/x402DiscoveryResource' - example: [] + example: + - resource: https://api.example.com/weather/forecast + description: Real-time weather forecast data. + type: http + x402Version: 2 + lastUpdated: '2024-01-15T10:30:00Z' + accepts: + - scheme: exact + network: eip155:8453 + amount: '1000000' + payTo: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + asset: '0x036CbD53842c5426634e7929541eC2318f3dCF7e' + maxTimeoutSeconds: 60 + extensions: + bazaar: + info: + input: + type: http + method: GET + schema: {} + quality: + l30DaysTotalCalls: 42 + l30DaysUniquePayers: 15 + lastCalledAt: '2024-01-15T10:30:00Z' + serviceName: Weather API + tags: + - weather + - data + iconUrl: https://res.cloudinary.com/bdb-prod/image/upload/... pagination: type: object description: Pagination information for the response. @@ -15391,6 +18248,11 @@ components: l30DaysTotalCalls: 42 l30DaysUniquePayers: 15 lastCalledAt: '2024-01-15T10:30:00Z' + serviceName: Premium Data API + tags: + - data + - analytics + iconUrl: https://res.cloudinary.com/bdb-prod/image/upload/... pagination: type: object description: Pagination information for the response. @@ -15425,7 +18287,35 @@ components: description: List of x402 resources matching the search query and filters. items: $ref: '#/components/schemas/x402DiscoveryResource' - example: [] + example: + - resource: https://api.example.com/weather/forecast + description: Real-time weather forecast data. + type: http + x402Version: 2 + lastUpdated: '2024-01-15T10:30:00Z' + accepts: + - scheme: exact + network: eip155:8453 + amount: '1000000' + payTo: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + asset: '0x036CbD53842c5426634e7929541eC2318f3dCF7e' + maxTimeoutSeconds: 60 + extensions: + bazaar: + info: + input: + type: http + method: GET + schema: {} + quality: + l30DaysTotalCalls: 42 + l30DaysUniquePayers: 15 + lastCalledAt: '2024-01-15T10:30:00Z' + serviceName: Weather API + tags: + - weather + - data + iconUrl: https://res.cloudinary.com/bdb-prod/image/upload/... partialResults: type: boolean description: Indicates whether the result set was truncated because there were more results than the requested limit. @@ -15817,35 +18707,6 @@ components: - limitType - limit - remaining - DateOfBirth: - type: object - description: Date of birth. - properties: - day: - type: string - description: Day of birth (01-31). - minLength: 2 - maxLength: 2 - pattern: ^[0-9]{2}$ - example: '15' - month: - type: string - description: Month of birth (01-12). - minLength: 2 - maxLength: 2 - pattern: ^[0-9]{2}$ - example: '08' - year: - type: string - description: Year of birth (four digits). - minLength: 4 - maxLength: 4 - pattern: ^[0-9]{4}$ - example: '1990' - example: - day: '15' - month: '08' - year: '1990' OnrampLimitUpgradeIdentityFields: type: object description: Populate the properties that correspond to the `fields` array from the user's `OnrampLimitUpgradeOption`. @@ -15890,18 +18751,280 @@ components: day: '15' month: '08' year: '1990' + PaymentMethodId: + type: string + pattern: ^paymentMethod_[a-f0-9\-]{36}$ + description: The ID of the Payment Method, which is a UUID prefixed by the string `paymentMethod_`. + example: paymentMethod_8e03978e-40d5-43e8-bc93-6894a57f9324 + PaymentMethodBase: + type: object + description: Common properties shared by all payment method types. + properties: + paymentMethodId: + $ref: '#/components/schemas/PaymentMethodId' + active: + type: boolean + description: Whether the payment method is active and can be used in transfers. A payment method may be inactive due to verification requirements or entity-level restrictions. + example: true + createdAt: + type: string + format: date-time + description: The timestamp when the payment method was created. + example: '2024-01-15T10:30:00Z' + updatedAt: + type: string + format: date-time + description: The timestamp when the payment method was last updated. + example: '2024-01-15T10:30:00Z' + required: + - paymentMethodId + - active + - createdAt + - updatedAt + FedwireDetails: + type: object + description: Details specific to Fedwire (domestic USD wire) payment methods. + properties: + asset: + type: string + description: The asset for this payment method. Always `usd` for Fedwire. + example: usd + bankName: + type: string + description: The name of the bank. + example: ALLY BANK + accountLast4: + type: string + description: The last 4 digits of the bank account number. + pattern: ^[0-9]{4}$ + example: '1234' + routingNumber: + type: string + description: The ABA routing number of the bank. + pattern: ^[0-9]{9}$ + example: '124003116' + required: + - asset + - bankName + - accountLast4 + - routingNumber + example: + asset: usd + bankName: ALLY BANK + accountLast4: '1234' + routingNumber: '124003116' + FedwirePaymentMethod: + type: object + title: FedwirePaymentMethod + description: A Fedwire (domestic USD wire) payment method linked to your entity. + allOf: + - $ref: '#/components/schemas/PaymentMethodBase' + - type: object + properties: + paymentRail: + type: string + description: The payment rail for this payment method. + enum: + - fedwire + example: fedwire + fedwire: + allOf: + - $ref: '#/components/schemas/FedwireDetails' + description: Fedwire (domestic USD wire) details. + required: + - paymentRail + - fedwire + example: + paymentMethodId: paymentMethod_8e03978e-40d5-43e8-bc93-6894a57f9324 + paymentRail: fedwire + active: true + createdAt: '2024-01-15T10:30:00Z' + updatedAt: '2024-01-15T10:30:00Z' + fedwire: + asset: usd + bankName: ALLY BANK + accountLast4: '1234' + routingNumber: '124003116' + SwiftDetails: + type: object + description: Details specific to SWIFT (international wire) payment methods. + properties: + asset: + type: string + description: The asset for this payment method (e.g., `eur`, `gbp`). + example: eur + bankName: + type: string + description: The name of the bank. + example: Deutsche Bank + accountLast4: + type: string + description: The last 4 characters of the account identifier. For IBAN-based accounts (e.g., EU), this is the last 4 characters of the IBAN. For account number-based accounts (e.g., US), this is the last 4 digits of the account number. + pattern: ^[A-Z0-9]{4}$ + example: '5678' + ibanLast4: + type: string + deprecated: true + description: 'Deprecated: use `accountLast4` instead. The last 4 characters of the account identifier.' + pattern: ^[A-Z0-9]{4}$ + example: '5678' + bic: + type: string + description: The Bank Identifier Code (BIC) / SWIFT code. + pattern: ^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$ + example: DEUTDEFF + required: + - asset + - bankName + - accountLast4 + - bic + example: + asset: eur + bankName: Deutsche Bank + accountLast4: '5678' + ibanLast4: '5678' + bic: DEUTDEFF + SwiftPaymentMethod: + type: object + title: SwiftPaymentMethod + description: A SWIFT (international wire) payment method linked to your entity. + allOf: + - $ref: '#/components/schemas/PaymentMethodBase' + - type: object + properties: + paymentRail: + type: string + description: The payment rail for this payment method. + enum: + - swift + example: swift + swift: + allOf: + - $ref: '#/components/schemas/SwiftDetails' + description: SWIFT (international wire) details. + required: + - paymentRail + - swift + example: + paymentMethodId: paymentMethod_def45678-1234-5678-9abc-def012345678 + paymentRail: swift + active: true + createdAt: '2024-01-15T10:30:00Z' + updatedAt: '2024-01-15T10:30:00Z' + swift: + asset: eur + bankName: Deutsche Bank + accountLast4: '5678' + ibanLast4: '5678' + bic: DEUTDEFF + SepaDetails: + type: object + description: Details specific to SEPA (Single Euro Payments Area) payment methods. + properties: + asset: + type: string + description: The asset for this payment method. Always `eur` for SEPA. + example: eur + bankName: + type: string + description: The name of the bank. + example: ING Bank + ibanLast4: + type: string + description: The last 4 characters of the IBAN. + pattern: ^[A-Z0-9]{4}$ + example: '4300' + bic: + type: string + description: The Bank Identifier Code (BIC) / SWIFT code. + pattern: ^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$ + example: INGBNL2A + required: + - asset + - bankName + - ibanLast4 + - bic + example: + asset: eur + bankName: ING Bank + ibanLast4: '4300' + bic: INGBNL2A + SepaPaymentMethod: + type: object + title: SepaPaymentMethod + description: A SEPA (Single Euro Payments Area) payment method linked to your entity. + allOf: + - $ref: '#/components/schemas/PaymentMethodBase' + - type: object + properties: + paymentRail: + type: string + description: The payment rail for this payment method. + enum: + - sepa + example: sepa + sepa: + allOf: + - $ref: '#/components/schemas/SepaDetails' + description: SEPA (Single Euro Payments Area) details. + required: + - paymentRail + - sepa + example: + paymentMethodId: paymentMethod_abc12345-6789-0abc-def0-123456789abc + paymentRail: sepa + active: true + createdAt: '2024-01-15T10:30:00Z' + updatedAt: '2024-01-15T10:30:00Z' + sepa: + asset: eur + bankName: ING Bank + ibanLast4: '4300' + bic: INGBNL2A + payment-methods_PaymentMethod: + description: |- + A payment method linked to your entity. Payment methods represent external financial instruments that can be used as a target for transfers. + + The `paymentRail` field indicates which type-specific details object is present. Type-specific fields are nested under a key matching the rail name (e.g., `fedwire`, `swift`). + oneOf: + - $ref: '#/components/schemas/FedwirePaymentMethod' + - $ref: '#/components/schemas/SwiftPaymentMethod' + - $ref: '#/components/schemas/SepaPaymentMethod' + discriminator: + propertyName: paymentRail + mapping: + fedwire: '#/components/schemas/FedwirePaymentMethod' + swift: '#/components/schemas/SwiftPaymentMethod' + sepa: '#/components/schemas/SepaPaymentMethod' responses: - UnauthorizedError: - description: Unauthorized. + IdempotencyError: + description: Idempotency key conflict. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - unauthorized: + idempotency_error: value: - errorType: unauthorized - errorMessage: The request is not properly authenticated. + errorType: idempotency_error + errorMessage: Idempotency key '8e03978e-40d5-43e8-bc93-6894a57f9324' was already used with a different request payload. Please try again with a new idempotency key. + EndpointUnavailableError: + description: 'The endpoint cannot serve the request right now, either because the API is in an unintended outage (`service_unavailable` — dependency failure, deploy issue) or because an operator has intentionally disabled this specific endpoint via a kill switch (`endpoint_unavailable`). Clients should dispatch on `errorType`: `service_unavailable` is typically transient and safe to retry, while `endpoint_unavailable` may persist until an operator re-enables the endpoint.' + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + service_unavailable: + summary: API-wide outage + value: + errorType: service_unavailable + errorMessage: Service unavailable. Please try again later. + endpoint_unavailable: + summary: Endpoint disabled by operator + value: + errorType: endpoint_unavailable + errorMessage: This endpoint is temporarily unavailable. Please try again later. InternalServerError: description: Internal server error. content: @@ -15935,6 +19058,17 @@ components: value: errorType: service_unavailable errorMessage: Service unavailable. Please try again later. + UnauthorizedError: + description: Unauthorized. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + examples: + unauthorized: + value: + errorType: unauthorized + errorMessage: The request is not properly authenticated. PaymentMethodRequiredError: description: A payment method is required to complete this operation. content: @@ -15946,17 +19080,37 @@ components: value: errorType: payment_method_required errorMessage: A valid payment method is required to complete this operation. Please add a payment method to your account at https://portal.cdp.coinbase.com. - IdempotencyError: - description: Idempotency key conflict. + DelegationForbiddenError: + description: The request was rejected due to a delegation issue. The errorType field indicates the specific reason. content: application/json: schema: $ref: '#/components/schemas/Error' examples: - idempotency_error: + forbidden: value: - errorType: idempotency_error - errorMessage: Idempotency key '8e03978e-40d5-43e8-bc93-6894a57f9324' was already used with a different request payload. Please try again with a new idempotency key. + errorType: forbidden + errorMessage: Unable to complete the requested signing or sending operation for this address. + delegation_not_found: + value: + errorType: delegation_not_found + errorMessage: Unable to complete this operation. No active delegation grant was found. Create a delegation for this operation and try again. + delegation_expired: + value: + errorType: delegation_expired + errorMessage: The delegation grant has expired. Create a new delegation grant and retry the request. + delegation_revoked: + value: + errorType: delegation_revoked + errorMessage: The delegation grant has been revoked. Please create a new delegation. + delegation_not_authorized: + value: + errorType: delegation_not_authorized + errorMessage: The delegation grant does not authorize this operation. + delegation_not_enabled: + value: + errorType: delegation_not_enabled + errorMessage: Delegated signing is not enabled for this project. AlreadyExistsError: description: The resource already exists. content: @@ -15978,15 +19132,15 @@ components: unsupported_query: value: errorType: invalid_sql_query - errorMessage: INSERTs are not supported + errorMessage: INSERTs are not supported. invalid_sql: value: errorType: invalid_sql_query - errorMessage: 'SQL syntax error: Invalid table name ''invalid_table''' + errorMessage: 'SQL syntax error: Invalid table name ''invalid_table''.' query_too_long: value: errorType: invalid_sql_query - errorMessage: Query exceeds maximum length of 10,000 characters + errorMessage: Query exceeds maximum length of 10,000 characters. ClientClosedRequestError: description: The client closed the connection before the server could send a response. content: @@ -16111,7 +19265,7 @@ components: value: success: false errorReason: insufficient_funds - errorMessage: Insufficient funds + errorMessage: Insufficient funds. payer: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' x402SupportedPaymentKindsResponse: description: Successfully retrieved supported payment kinds for the x402 protocol. @@ -16176,87 +19330,196 @@ components: value: errorType: rate_limit_exceeded errorMessage: Rate limit exceeded. - parameters: - XWalletAuth: - name: X-Wallet-Auth - in: header - required: true - description: | - A JWT signed using your Wallet Secret, encoded in base64. Refer to the - [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) - section of our Authentication docs for more details on how to generate your Wallet Token. - schema: - type: string - example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEyMywicm9sZSI6ImFkbWluIiwiZXhwIjoxNzAxOTgwMDAwfQ.HWvMTKmCCTxHaxjvZyLaC6UQ6TV3ErTDWBf7zmdH0Lw - IdempotencyKey: - name: X-Idempotency-Key - in: header - required: false - description: | - An optional string request header for making requests safely retryable. - When included, duplicate requests with the same key will return identical responses. - Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. - schema: - type: string - maxLength: 128 - minLength: 1 - example: 8e03978e-40d5-43e8-bc93-6894a57f9324 - XWalletAuthOptional: - name: X-Wallet-Auth - in: header - required: false - description: | - A JWT signed using your Wallet Secret, encoded in base64. Refer to the - [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) - section of our Authentication docs for more details on how to generate your Wallet Token. - schema: - type: string - example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEyMywicm9sZSI6ImFkbWluIiwiZXhwIjoxNzAxOTgwMDAwfQ.HWvMTKmCCTxHaxjvZyLaC6UQ6TV3ErTDWBf7zmdH0Lw - XDeveloperAuth: - name: X-Developer-Auth - in: header - required: false - description: | - A JWT signed using your Wallet Secret, encoded in base64. Refer to the - [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) - section of our Authentication docs for more details on how to generate your Wallet Token. - schema: - type: string - example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEyMywicm9sZSI6ImFkbWluIiwiZXhwIjoxNzAxOTgwMDAwfQ.HWvMTKmCCTxHaxjvZyLaC6UQ6TV3ErTDWBf7zmdH0Lw - ProjectIDOptional: - name: projectID - in: query - required: false - description: The ID of the CDP Project. Required for end users authenticated using custom auth (i.e. a non-CDP JWT provider). - schema: - type: string - pattern: ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$ - example: 8e03978e-40d5-43e8-bc93-6894a57f9324 - PageSize: - name: pageSize - description: The number of resources to return per page. - in: query - required: false - schema: - type: integer - default: 20 - example: 10 - PageToken: - name: pageToken - description: The token for the next page of resources, if any. - in: query - required: false - schema: - type: string - example: eyJsYXN0X2lkIjogImFiYzEyMyIsICJ0aW1lc3RhbXAiOiAxNzA3ODIzNzAxfQ== + examples: + ListTransfersResponse: + summary: Page containing a regular and an FX (completed) transfer + value: + transfers: + - transferId: transfer_af2937b0-9846-4fe7-bfe9-ccc22d935114 + status: quoted + source: + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + asset: usd + target: + address: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' + network: base + asset: usdc + amount: '100.00' + asset: usd + sourceAmount: '103.50' + sourceAsset: usd + targetAmount: '100.00' + targetAsset: usdc + exchangeRate: + sourceAsset: usd + targetAsset: usdc + rate: '1' + fees: + - type: bank + amount: '2.50' + asset: usd + - type: conversion + amount: '1.00' + asset: usd + expiresAt: '2023-10-08T14:45:00Z' + createdAt: '2023-10-08T14:30:00Z' + updatedAt: '2023-10-08T14:30:00Z' + metadata: + invoiceId: '12345' + reference: 'Payment for invoice #12345' + - transferId: transfer_bf3948c1-ab57-5gf8-cde3-ddd33e046225 + status: completed + source: + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + asset: usdc + target: + accountId: account_bf3948c1-ab57-5gf8-cde3-ddd33e046225 + asset: eur + amount: '100.00' + asset: usdc + sourceAmount: '100.00' + sourceAsset: usdc + targetAmount: '85.02' + targetAsset: eur + exchangeRate: + sourceAsset: usdc + targetAsset: eur + rate: '0.8502' + fees: + - type: conversion + amount: '0.01' + asset: usdc + estimate: + exchangeRate: + sourceAsset: usdc + targetAsset: eur + rate: '0.85' + targetAmount: '85.00' + targetAsset: eur + fees: + - type: conversion + amount: '0.01' + asset: usdc + estimatedAt: '2023-10-08T14:30:00Z' + completedAt: '2023-10-08T14:31:05Z' + createdAt: '2023-10-08T14:30:00Z' + updatedAt: '2023-10-08T14:31:05Z' + RegularTransferQuoted: + summary: Regular transfer in quoted state (USD → USDC at 1:1) + value: + transferId: transfer_af2937b0-9846-4fe7-bfe9-ccc22d935114 + status: quoted + source: + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + asset: usd + target: + address: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' + network: base + asset: usdc + amount: '100.00' + asset: usd + sourceAmount: '103.50' + sourceAsset: usd + targetAmount: '100.00' + targetAsset: usdc + exchangeRate: + sourceAsset: usd + targetAsset: usdc + rate: '1' + fees: + - type: bank + amount: '2.50' + asset: usd + - type: conversion + amount: '1.00' + asset: usd + expiresAt: '2023-10-08T14:45:00Z' + createdAt: '2023-10-08T14:30:00Z' + updatedAt: '2023-10-08T14:30:00Z' + metadata: + invoiceId: '12345' + reference: 'Payment for invoice #12345' + FxTransferQuoted: + summary: Trade-backed FX transfer in quoted state (USDC → EUR) + value: + transferId: transfer_bf3948c1-ab57-5gf8-cde3-ddd33e046225 + status: quoted + source: + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + asset: usdc + target: + accountId: account_bf3948c1-ab57-5gf8-cde3-ddd33e046225 + asset: eur + amount: '100.00' + asset: usdc + sourceAmount: '100.00' + sourceAsset: usdc + estimate: + exchangeRate: + sourceAsset: usdc + targetAsset: eur + rate: '0.85' + targetAmount: '85.00' + targetAsset: eur + fees: + - type: conversion + amount: '0.01' + asset: usdc + estimatedAt: '2023-10-08T14:30:00Z' + expiresAt: '2023-10-08T14:30:10Z' + createdAt: '2023-10-08T14:30:00Z' + updatedAt: '2023-10-08T14:30:00Z' + FxTransferCompleted: + summary: Trade-backed FX transfer in completed state (top-level actuals + immutable estimate snapshot) + value: + transferId: transfer_bf3948c1-ab57-5gf8-cde3-ddd33e046225 + status: completed + source: + accountId: account_af2937b0-9846-4fe7-bfe9-ccc22d935114 + asset: usdc + target: + accountId: account_bf3948c1-ab57-5gf8-cde3-ddd33e046225 + asset: eur + amount: '100.00' + asset: usdc + sourceAmount: '100.00' + sourceAsset: usdc + targetAmount: '85.02' + targetAsset: eur + exchangeRate: + sourceAsset: usdc + targetAsset: eur + rate: '0.8502' + fees: + - type: conversion + amount: '0.01' + asset: usdc + estimate: + exchangeRate: + sourceAsset: usdc + targetAsset: eur + rate: '0.85' + targetAmount: '85.00' + targetAsset: eur + fees: + - type: conversion + amount: '0.01' + asset: usdc + estimatedAt: '2023-10-08T14:30:00Z' + completedAt: '2023-10-08T14:31:05Z' + createdAt: '2023-10-08T14:30:00Z' + updatedAt: '2023-10-08T14:31:05Z' x-tagGroups: + - name: Accounts + tags: + - Accounts - name: Payments tags: + - Deposit Destinations + - Payment Methods + - Transfers - Onramp - x402 Facilitator - - name: Trading - tags: - - EVM Swaps - name: Wallets tags: - End User Accounts @@ -16266,6 +19529,9 @@ x-tagGroups: - Faucets - Policy Engine - Solana Accounts + - name: Trading + tags: + - EVM Swaps - name: Onchain Tools tags: - EVM Token Balances diff --git a/python/cdp/openapi_client/__init__.py b/python/cdp/openapi_client/__init__.py index 051bf5bad..cc9904641 100644 --- a/python/cdp/openapi_client/__init__.py +++ b/python/cdp/openapi_client/__init__.py @@ -18,6 +18,8 @@ __version__ = "1.0.0" # import apis into sdk package +from cdp.openapi_client.api.accounts_api import AccountsApi +from cdp.openapi_client.api.deposit_destinations_api import DepositDestinationsApi from cdp.openapi_client.api.evm_accounts_api import EVMAccountsApi from cdp.openapi_client.api.evm_smart_accounts_api import EVMSmartAccountsApi from cdp.openapi_client.api.evm_swaps_api import EVMSwapsApi @@ -27,10 +29,12 @@ from cdp.openapi_client.api.faucets_api import FaucetsApi from cdp.openapi_client.api.onchain_data_api import OnchainDataApi from cdp.openapi_client.api.onramp_api import OnrampApi +from cdp.openapi_client.api.payment_methods_api import PaymentMethodsApi from cdp.openapi_client.api.policy_engine_api import PolicyEngineApi from cdp.openapi_client.api.sqlapi_api import SQLAPIApi from cdp.openapi_client.api.solana_accounts_api import SolanaAccountsApi from cdp.openapi_client.api.solana_token_balances_api import SolanaTokenBalancesApi +from cdp.openapi_client.api.transfers_api import TransfersApi from cdp.openapi_client.api.webhooks_api import WebhooksApi from cdp.openapi_client.api.x402_facilitator_api import X402FacilitatorApi @@ -52,18 +56,30 @@ from cdp.openapi_client.models.abi_input import AbiInput from cdp.openapi_client.models.abi_parameter import AbiParameter from cdp.openapi_client.models.abi_state_mutability import AbiStateMutability +from cdp.openapi_client.models.account import Account from cdp.openapi_client.models.account_token_addresses_response import AccountTokenAddressesResponse +from cdp.openapi_client.models.account_type import AccountType from cdp.openapi_client.models.add_end_user_evm_account201_response import AddEndUserEvmAccount201Response from cdp.openapi_client.models.add_end_user_evm_smart_account201_response import AddEndUserEvmSmartAccount201Response from cdp.openapi_client.models.add_end_user_evm_smart_account_request import AddEndUserEvmSmartAccountRequest from cdp.openapi_client.models.add_end_user_solana_account201_response import AddEndUserSolanaAccount201Response +from cdp.openapi_client.models.amount_detail import AmountDetail +from cdp.openapi_client.models.asset_type import AssetType from cdp.openapi_client.models.authentication_method import AuthenticationMethod +from cdp.openapi_client.models.balance import Balance +from cdp.openapi_client.models.balances import Balances +from cdp.openapi_client.models.balances_asset import BalancesAsset from cdp.openapi_client.models.common_swap_response import CommonSwapResponse from cdp.openapi_client.models.common_swap_response_fees import CommonSwapResponseFees from cdp.openapi_client.models.common_swap_response_issues import CommonSwapResponseIssues from cdp.openapi_client.models.common_swap_response_issues_allowance import CommonSwapResponseIssuesAllowance from cdp.openapi_client.models.common_swap_response_issues_balance import CommonSwapResponseIssuesBalance +from cdp.openapi_client.models.create_account_request import CreateAccountRequest +from cdp.openapi_client.models.create_crypto_deposit_destination_request import CreateCryptoDepositDestinationRequest from cdp.openapi_client.models.create_delegation_for_end_user_account_request import CreateDelegationForEndUserAccountRequest +from cdp.openapi_client.models.create_deposit_destination_crypto import CreateDepositDestinationCrypto +from cdp.openapi_client.models.create_deposit_destination_request import CreateDepositDestinationRequest +from cdp.openapi_client.models.create_deposit_destination_request_base import CreateDepositDestinationRequestBase from cdp.openapi_client.models.create_end_user_evm_swap_rule import CreateEndUserEvmSwapRule from cdp.openapi_client.models.create_end_user_request import CreateEndUserRequest from cdp.openapi_client.models.create_end_user_request_evm_account import CreateEndUserRequestEvmAccount @@ -85,11 +101,26 @@ from cdp.openapi_client.models.create_swap_quote_response_all_of_permit2 import CreateSwapQuoteResponseAllOfPermit2 from cdp.openapi_client.models.create_swap_quote_response_all_of_transaction import CreateSwapQuoteResponseAllOfTransaction from cdp.openapi_client.models.create_swap_quote_response_wrapper import CreateSwapQuoteResponseWrapper +from cdp.openapi_client.models.create_transfer_source import CreateTransferSource +from cdp.openapi_client.models.crypto_deposit_destination import CryptoDepositDestination from cdp.openapi_client.models.date_of_birth import DateOfBirth +from cdp.openapi_client.models.deposit_destination import DepositDestination +from cdp.openapi_client.models.deposit_destination_crypto import DepositDestinationCrypto +from cdp.openapi_client.models.deposit_destination_reference import DepositDestinationReference +from cdp.openapi_client.models.deposit_destination_status import DepositDestinationStatus +from cdp.openapi_client.models.deposit_destination_target import DepositDestinationTarget +from cdp.openapi_client.models.deposit_destination_target_account import DepositDestinationTargetAccount +from cdp.openapi_client.models.deposit_travel_rule_beneficiary import DepositTravelRuleBeneficiary +from cdp.openapi_client.models.deposit_travel_rule_originator import DepositTravelRuleOriginator +from cdp.openapi_client.models.deposit_travel_rule_request import DepositTravelRuleRequest +from cdp.openapi_client.models.deposit_travel_rule_response import DepositTravelRuleResponse +from cdp.openapi_client.models.deposit_travel_rule_vasp import DepositTravelRuleVasp from cdp.openapi_client.models.developer_jwt_authentication import DeveloperJWTAuthentication from cdp.openapi_client.models.eip712_domain import EIP712Domain from cdp.openapi_client.models.eip712_message import EIP712Message +from cdp.openapi_client.models.email_address import EmailAddress from cdp.openapi_client.models.email_authentication import EmailAuthentication +from cdp.openapi_client.models.email_instrument import EmailInstrument from cdp.openapi_client.models.end_user import EndUser from cdp.openapi_client.models.end_user_evm_account import EndUserEvmAccount from cdp.openapi_client.models.end_user_evm_smart_account import EndUserEvmSmartAccount @@ -120,6 +151,8 @@ from cdp.openapi_client.models.export_evm_account200_response import ExportEvmAccount200Response from cdp.openapi_client.models.export_evm_account_request import ExportEvmAccountRequest from cdp.openapi_client.models.export_solana_account200_response import ExportSolanaAccount200Response +from cdp.openapi_client.models.fedwire_details import FedwireDetails +from cdp.openapi_client.models.fedwire_payment_method import FedwirePaymentMethod from cdp.openapi_client.models.get_delegation_for_end_user200_response import GetDelegationForEndUser200Response from cdp.openapi_client.models.get_onramp_order_by_id200_response import GetOnrampOrderById200Response from cdp.openapi_client.models.get_onramp_user_limits200_response import GetOnrampUserLimits200Response @@ -139,25 +172,32 @@ from cdp.openapi_client.models.inline_object2 import InlineObject2 from cdp.openapi_client.models.known_abi_type import KnownAbiType from cdp.openapi_client.models.known_idl_type import KnownIdlType +from cdp.openapi_client.models.list_balances200_response import ListBalances200Response +from cdp.openapi_client.models.list_deposit_destinations200_response import ListDepositDestinations200Response from cdp.openapi_client.models.list_end_users200_response import ListEndUsers200Response from cdp.openapi_client.models.list_evm_accounts200_response import ListEvmAccounts200Response from cdp.openapi_client.models.list_evm_smart_accounts200_response import ListEvmSmartAccounts200Response from cdp.openapi_client.models.list_evm_token_balances200_response import ListEvmTokenBalances200Response from cdp.openapi_client.models.list_evm_token_balances_network import ListEvmTokenBalancesNetwork +from cdp.openapi_client.models.list_foundation_accounts200_response import ListFoundationAccounts200Response +from cdp.openapi_client.models.list_payment_methods200_response import ListPaymentMethods200Response from cdp.openapi_client.models.list_policies200_response import ListPolicies200Response from cdp.openapi_client.models.list_response import ListResponse from cdp.openapi_client.models.list_solana_accounts200_response import ListSolanaAccounts200Response from cdp.openapi_client.models.list_solana_token_balances200_response import ListSolanaTokenBalances200Response from cdp.openapi_client.models.list_solana_token_balances_network import ListSolanaTokenBalancesNetwork from cdp.openapi_client.models.list_spend_permissions200_response import ListSpendPermissions200Response +from cdp.openapi_client.models.list_transfers200_response import ListTransfers200Response from cdp.openapi_client.models.lookup_end_user200_response import LookupEndUser200Response from cdp.openapi_client.models.mfa_methods import MFAMethods from cdp.openapi_client.models.mfa_methods_sms import MFAMethodsSms from cdp.openapi_client.models.mfa_methods_totp import MFAMethodsTotp from cdp.openapi_client.models.mint_address_criterion import MintAddressCriterion from cdp.openapi_client.models.net_usd_change_criterion import NetUSDChangeCriterion +from cdp.openapi_client.models.network import Network from cdp.openapi_client.models.o_auth2_authentication import OAuth2Authentication from cdp.openapi_client.models.o_auth2_provider_type import OAuth2ProviderType +from cdp.openapi_client.models.onchain_address import OnchainAddress from cdp.openapi_client.models.onchain_data_column_schema import OnchainDataColumnSchema from cdp.openapi_client.models.onchain_data_query import OnchainDataQuery from cdp.openapi_client.models.onchain_data_result import OnchainDataResult @@ -180,6 +220,11 @@ from cdp.openapi_client.models.onramp_session import OnrampSession from cdp.openapi_client.models.onramp_user_id_type import OnrampUserIdType from cdp.openapi_client.models.onramp_user_limit import OnrampUserLimit +from cdp.openapi_client.models.originating_bank_account_us import OriginatingBankAccountUS +from cdp.openapi_client.models.payment_method import PaymentMethod +from cdp.openapi_client.models.payment_method_base import PaymentMethodBase +from cdp.openapi_client.models.payment_methods_payment_method import PaymentMethodsPaymentMethod +from cdp.openapi_client.models.physical_address import PhysicalAddress from cdp.openapi_client.models.policy import Policy from cdp.openapi_client.models.prepare_and_send_user_operation_request import PrepareAndSendUserOperationRequest from cdp.openapi_client.models.prepare_user_operation_request import PrepareUserOperationRequest @@ -215,6 +260,8 @@ from cdp.openapi_client.models.send_user_operation_request import SendUserOperationRequest from cdp.openapi_client.models.send_user_operation_rule import SendUserOperationRule from cdp.openapi_client.models.send_user_operation_with_end_user_account_request import SendUserOperationWithEndUserAccountRequest +from cdp.openapi_client.models.sepa_details import SepaDetails +from cdp.openapi_client.models.sepa_payment_method import SepaPaymentMethod from cdp.openapi_client.models.sign_end_user_evm_hash_rule import SignEndUserEvmHashRule from cdp.openapi_client.models.sign_end_user_evm_message_rule import SignEndUserEvmMessageRule from cdp.openapi_client.models.sign_end_user_evm_transaction_rule import SignEndUserEvmTransactionRule @@ -275,11 +322,31 @@ from cdp.openapi_client.models.spl_address_criterion import SplAddressCriterion from cdp.openapi_client.models.spl_value_criterion import SplValueCriterion from cdp.openapi_client.models.swap_unavailable_response import SwapUnavailableResponse +from cdp.openapi_client.models.swift_details import SwiftDetails +from cdp.openapi_client.models.swift_payment_method import SwiftPaymentMethod from cdp.openapi_client.models.telegram_authentication import TelegramAuthentication from cdp.openapi_client.models.token import Token from cdp.openapi_client.models.token_amount import TokenAmount from cdp.openapi_client.models.token_balance import TokenBalance from cdp.openapi_client.models.token_fee import TokenFee +from cdp.openapi_client.models.transfer import Transfer +from cdp.openapi_client.models.transfer_details import TransferDetails +from cdp.openapi_client.models.transfer_details_onchain_transactions_inner import TransferDetailsOnchainTransactionsInner +from cdp.openapi_client.models.transfer_details_travel_rule import TransferDetailsTravelRule +from cdp.openapi_client.models.transfer_estimate import TransferEstimate +from cdp.openapi_client.models.transfer_exchange_rate import TransferExchangeRate +from cdp.openapi_client.models.transfer_fee import TransferFee +from cdp.openapi_client.models.transfer_request import TransferRequest +from cdp.openapi_client.models.transfer_source import TransferSource +from cdp.openapi_client.models.transfer_status import TransferStatus +from cdp.openapi_client.models.transfer_target import TransferTarget +from cdp.openapi_client.models.transfers_account import TransfersAccount +from cdp.openapi_client.models.travel_rule import TravelRule +from cdp.openapi_client.models.travel_rule_beneficiary import TravelRuleBeneficiary +from cdp.openapi_client.models.travel_rule_originator import TravelRuleOriginator +from cdp.openapi_client.models.travel_rule_originator_all_of_virtual_asset_service_provider import TravelRuleOriginatorAllOfVirtualAssetServiceProvider +from cdp.openapi_client.models.travel_rule_party import TravelRuleParty +from cdp.openapi_client.models.travel_rule_status import TravelRuleStatus from cdp.openapi_client.models.update_evm_account_request import UpdateEvmAccountRequest from cdp.openapi_client.models.update_evm_smart_account_request import UpdateEvmSmartAccountRequest from cdp.openapi_client.models.update_policy_request import UpdatePolicyRequest diff --git a/python/cdp/openapi_client/api/__init__.py b/python/cdp/openapi_client/api/__init__.py index 4d179df73..0300f91d9 100644 --- a/python/cdp/openapi_client/api/__init__.py +++ b/python/cdp/openapi_client/api/__init__.py @@ -1,6 +1,8 @@ # flake8: noqa # import apis into api package +from cdp.openapi_client.api.accounts_api import AccountsApi +from cdp.openapi_client.api.deposit_destinations_api import DepositDestinationsApi from cdp.openapi_client.api.evm_accounts_api import EVMAccountsApi from cdp.openapi_client.api.evm_smart_accounts_api import EVMSmartAccountsApi from cdp.openapi_client.api.evm_swaps_api import EVMSwapsApi @@ -10,10 +12,12 @@ from cdp.openapi_client.api.faucets_api import FaucetsApi from cdp.openapi_client.api.onchain_data_api import OnchainDataApi from cdp.openapi_client.api.onramp_api import OnrampApi +from cdp.openapi_client.api.payment_methods_api import PaymentMethodsApi from cdp.openapi_client.api.policy_engine_api import PolicyEngineApi from cdp.openapi_client.api.sqlapi_api import SQLAPIApi from cdp.openapi_client.api.solana_accounts_api import SolanaAccountsApi from cdp.openapi_client.api.solana_token_balances_api import SolanaTokenBalancesApi +from cdp.openapi_client.api.transfers_api import TransfersApi from cdp.openapi_client.api.webhooks_api import WebhooksApi from cdp.openapi_client.api.x402_facilitator_api import X402FacilitatorApi diff --git a/python/cdp/openapi_client/api/accounts_api.py b/python/cdp/openapi_client/api/accounts_api.py new file mode 100644 index 000000000..2e83092b1 --- /dev/null +++ b/python/cdp/openapi_client/api/accounts_api.py @@ -0,0 +1,1511 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from pydantic import Field, StrictInt, StrictStr, field_validator +from typing import Optional +from typing_extensions import Annotated +from cdp.openapi_client.models.account import Account +from cdp.openapi_client.models.account_type import AccountType +from cdp.openapi_client.models.balance import Balance +from cdp.openapi_client.models.create_account_request import CreateAccountRequest +from cdp.openapi_client.models.list_balances200_response import ListBalances200Response +from cdp.openapi_client.models.list_foundation_accounts200_response import ListFoundationAccounts200Response + +from cdp.openapi_client.api_client import ApiClient, RequestSerialized +from cdp.openapi_client.api_response import ApiResponse +from cdp.openapi_client.rest import RESTResponseType + + +class AccountsApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + async def create_foundation_account( + self, + create_account_request: CreateAccountRequest, + x_idempotency_key: Annotated[Optional[Annotated[str, Field(min_length=1, strict=True, max_length=128)]], Field(description="An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. ")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Account: + """Create account + + Create an account for your Entity. Support for creating Customer-owned accounts is in development. + + :param create_account_request: (required) + :type create_account_request: CreateAccountRequest + :param x_idempotency_key: An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + :type x_idempotency_key: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_foundation_account_serialize( + create_account_request=create_account_request, + x_idempotency_key=x_idempotency_key, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Account", + '400': "Error", + '422': "Error", + '503': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def create_foundation_account_with_http_info( + self, + create_account_request: CreateAccountRequest, + x_idempotency_key: Annotated[Optional[Annotated[str, Field(min_length=1, strict=True, max_length=128)]], Field(description="An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. ")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Account]: + """Create account + + Create an account for your Entity. Support for creating Customer-owned accounts is in development. + + :param create_account_request: (required) + :type create_account_request: CreateAccountRequest + :param x_idempotency_key: An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + :type x_idempotency_key: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_foundation_account_serialize( + create_account_request=create_account_request, + x_idempotency_key=x_idempotency_key, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Account", + '400': "Error", + '422': "Error", + '503': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def create_foundation_account_without_preload_content( + self, + create_account_request: CreateAccountRequest, + x_idempotency_key: Annotated[Optional[Annotated[str, Field(min_length=1, strict=True, max_length=128)]], Field(description="An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. ")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create account + + Create an account for your Entity. Support for creating Customer-owned accounts is in development. + + :param create_account_request: (required) + :type create_account_request: CreateAccountRequest + :param x_idempotency_key: An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + :type x_idempotency_key: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_foundation_account_serialize( + create_account_request=create_account_request, + x_idempotency_key=x_idempotency_key, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Account", + '400': "Error", + '422': "Error", + '503': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _create_foundation_account_serialize( + self, + create_account_request, + x_idempotency_key, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + if x_idempotency_key is not None: + _header_params['X-Idempotency-Key'] = x_idempotency_key + # process the form parameters + # process the body parameter + if create_account_request is not None: + _body_params = create_account_request + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/v2/accounts', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + async def get_balance_by_asset( + self, + account_id: Annotated[str, Field(strict=True, description="The unique identifier of the account.")], + asset: Annotated[str, Field(min_length=1, strict=True, max_length=42, description="The symbol of the asset.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Balance: + """Get balance for account + + Get the balance for an account by asset. + + :param account_id: The unique identifier of the account. (required) + :type account_id: str + :param asset: The symbol of the asset. (required) + :type asset: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_balance_by_asset_serialize( + account_id=account_id, + asset=asset, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Balance", + '400': "Error", + '401': "Error", + '404': "Error", + '500': "Error", + '503': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def get_balance_by_asset_with_http_info( + self, + account_id: Annotated[str, Field(strict=True, description="The unique identifier of the account.")], + asset: Annotated[str, Field(min_length=1, strict=True, max_length=42, description="The symbol of the asset.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Balance]: + """Get balance for account + + Get the balance for an account by asset. + + :param account_id: The unique identifier of the account. (required) + :type account_id: str + :param asset: The symbol of the asset. (required) + :type asset: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_balance_by_asset_serialize( + account_id=account_id, + asset=asset, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Balance", + '400': "Error", + '401': "Error", + '404': "Error", + '500': "Error", + '503': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def get_balance_by_asset_without_preload_content( + self, + account_id: Annotated[str, Field(strict=True, description="The unique identifier of the account.")], + asset: Annotated[str, Field(min_length=1, strict=True, max_length=42, description="The symbol of the asset.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get balance for account + + Get the balance for an account by asset. + + :param account_id: The unique identifier of the account. (required) + :type account_id: str + :param asset: The symbol of the asset. (required) + :type asset: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_balance_by_asset_serialize( + account_id=account_id, + asset=asset, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Balance", + '400': "Error", + '401': "Error", + '404': "Error", + '500': "Error", + '503': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_balance_by_asset_serialize( + self, + account_id, + asset, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if account_id is not None: + _path_params['accountId'] = account_id + if asset is not None: + _path_params['asset'] = asset + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v2/accounts/{accountId}/balances/{asset}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + async def get_foundation_account_by_id( + self, + account_id: Annotated[str, Field(strict=True, description="The ID of the account to retrieve.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Account: + """Get account + + Get an account by its ID. + + :param account_id: The ID of the account to retrieve. (required) + :type account_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_foundation_account_by_id_serialize( + account_id=account_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Account", + '400': "Error", + '404': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def get_foundation_account_by_id_with_http_info( + self, + account_id: Annotated[str, Field(strict=True, description="The ID of the account to retrieve.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Account]: + """Get account + + Get an account by its ID. + + :param account_id: The ID of the account to retrieve. (required) + :type account_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_foundation_account_by_id_serialize( + account_id=account_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Account", + '400': "Error", + '404': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def get_foundation_account_by_id_without_preload_content( + self, + account_id: Annotated[str, Field(strict=True, description="The ID of the account to retrieve.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get account + + Get an account by its ID. + + :param account_id: The ID of the account to retrieve. (required) + :type account_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_foundation_account_by_id_serialize( + account_id=account_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Account", + '400': "Error", + '404': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_foundation_account_by_id_serialize( + self, + account_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if account_id is not None: + _path_params['accountId'] = account_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v2/accounts/{accountId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + async def list_balances( + self, + account_id: Annotated[str, Field(strict=True, description="The unique identifier of the account.")], + page_size: Annotated[Optional[StrictInt], Field(description="The number of resources to return per page.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="The token for the next page of resources, if any.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ListBalances200Response: + """List balances for account + + List the balances for an account. Results are sorted by native-fiat equivalent balance in descending order. + + :param account_id: The unique identifier of the account. (required) + :type account_id: str + :param page_size: The number of resources to return per page. + :type page_size: int + :param page_token: The token for the next page of resources, if any. + :type page_token: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_balances_serialize( + account_id=account_id, + page_size=page_size, + page_token=page_token, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ListBalances200Response", + '400': "Error", + '401': "Error", + '404': "Error", + '500': "Error", + '503': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def list_balances_with_http_info( + self, + account_id: Annotated[str, Field(strict=True, description="The unique identifier of the account.")], + page_size: Annotated[Optional[StrictInt], Field(description="The number of resources to return per page.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="The token for the next page of resources, if any.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ListBalances200Response]: + """List balances for account + + List the balances for an account. Results are sorted by native-fiat equivalent balance in descending order. + + :param account_id: The unique identifier of the account. (required) + :type account_id: str + :param page_size: The number of resources to return per page. + :type page_size: int + :param page_token: The token for the next page of resources, if any. + :type page_token: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_balances_serialize( + account_id=account_id, + page_size=page_size, + page_token=page_token, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ListBalances200Response", + '400': "Error", + '401': "Error", + '404': "Error", + '500': "Error", + '503': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def list_balances_without_preload_content( + self, + account_id: Annotated[str, Field(strict=True, description="The unique identifier of the account.")], + page_size: Annotated[Optional[StrictInt], Field(description="The number of resources to return per page.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="The token for the next page of resources, if any.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List balances for account + + List the balances for an account. Results are sorted by native-fiat equivalent balance in descending order. + + :param account_id: The unique identifier of the account. (required) + :type account_id: str + :param page_size: The number of resources to return per page. + :type page_size: int + :param page_token: The token for the next page of resources, if any. + :type page_token: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_balances_serialize( + account_id=account_id, + page_size=page_size, + page_token=page_token, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ListBalances200Response", + '400': "Error", + '401': "Error", + '404': "Error", + '500': "Error", + '503': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _list_balances_serialize( + self, + account_id, + page_size, + page_token, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if account_id is not None: + _path_params['accountId'] = account_id + # process the query parameters + if page_size is not None: + + _query_params.append(('pageSize', page_size)) + + if page_token is not None: + + _query_params.append(('pageToken', page_token)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v2/accounts/{accountId}/balances', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + async def list_foundation_accounts( + self, + page_size: Annotated[Optional[StrictInt], Field(description="The number of resources to return per page.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="The token for the next page of resources, if any.")] = None, + type: Annotated[Optional[AccountType], Field(description="Filter accounts by account type. When omitted, accounts of any type are returned. Combined with `owner` using AND.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ListFoundationAccounts200Response: + """List accounts + + List all accounts. The API will return all accounts that the API Key has Permissions to access. You can filter the results by using query parameters, which will be treated as a single conjunction (i.e. AND). Results are sorted by creation date in descending order (newest first). + + :param page_size: The number of resources to return per page. + :type page_size: int + :param page_token: The token for the next page of resources, if any. + :type page_token: str + :param type: Filter accounts by account type. When omitted, accounts of any type are returned. Combined with `owner` using AND. + :type type: AccountType + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_foundation_accounts_serialize( + page_size=page_size, + page_token=page_token, + type=type, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ListFoundationAccounts200Response", + '400': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def list_foundation_accounts_with_http_info( + self, + page_size: Annotated[Optional[StrictInt], Field(description="The number of resources to return per page.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="The token for the next page of resources, if any.")] = None, + type: Annotated[Optional[AccountType], Field(description="Filter accounts by account type. When omitted, accounts of any type are returned. Combined with `owner` using AND.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ListFoundationAccounts200Response]: + """List accounts + + List all accounts. The API will return all accounts that the API Key has Permissions to access. You can filter the results by using query parameters, which will be treated as a single conjunction (i.e. AND). Results are sorted by creation date in descending order (newest first). + + :param page_size: The number of resources to return per page. + :type page_size: int + :param page_token: The token for the next page of resources, if any. + :type page_token: str + :param type: Filter accounts by account type. When omitted, accounts of any type are returned. Combined with `owner` using AND. + :type type: AccountType + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_foundation_accounts_serialize( + page_size=page_size, + page_token=page_token, + type=type, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ListFoundationAccounts200Response", + '400': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def list_foundation_accounts_without_preload_content( + self, + page_size: Annotated[Optional[StrictInt], Field(description="The number of resources to return per page.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="The token for the next page of resources, if any.")] = None, + type: Annotated[Optional[AccountType], Field(description="Filter accounts by account type. When omitted, accounts of any type are returned. Combined with `owner` using AND.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List accounts + + List all accounts. The API will return all accounts that the API Key has Permissions to access. You can filter the results by using query parameters, which will be treated as a single conjunction (i.e. AND). Results are sorted by creation date in descending order (newest first). + + :param page_size: The number of resources to return per page. + :type page_size: int + :param page_token: The token for the next page of resources, if any. + :type page_token: str + :param type: Filter accounts by account type. When omitted, accounts of any type are returned. Combined with `owner` using AND. + :type type: AccountType + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_foundation_accounts_serialize( + page_size=page_size, + page_token=page_token, + type=type, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ListFoundationAccounts200Response", + '400': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _list_foundation_accounts_serialize( + self, + page_size, + page_token, + type, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if page_size is not None: + + _query_params.append(('pageSize', page_size)) + + if page_token is not None: + + _query_params.append(('pageToken', page_token)) + + if type is not None: + + _query_params.append(('type', type.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v2/accounts', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/python/cdp/openapi_client/api/deposit_destinations_api.py b/python/cdp/openapi_client/api/deposit_destinations_api.py new file mode 100644 index 000000000..0e43e9705 --- /dev/null +++ b/python/cdp/openapi_client/api/deposit_destinations_api.py @@ -0,0 +1,979 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from pydantic import Field, StrictInt, StrictStr, field_validator +from typing import Optional +from typing_extensions import Annotated +from cdp.openapi_client.models.create_deposit_destination_request import CreateDepositDestinationRequest +from cdp.openapi_client.models.deposit_destination import DepositDestination +from cdp.openapi_client.models.list_deposit_destinations200_response import ListDepositDestinations200Response + +from cdp.openapi_client.api_client import ApiClient, RequestSerialized +from cdp.openapi_client.api_response import ApiResponse +from cdp.openapi_client.rest import RESTResponseType + + +class DepositDestinationsApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + async def create_deposit_destination( + self, + create_deposit_destination_request: CreateDepositDestinationRequest, + x_idempotency_key: Annotated[Optional[Annotated[str, Field(min_length=1, strict=True, max_length=128)]], Field(description="An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. ")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> DepositDestination: + """Create deposit destination + + Create a new deposit destination for an account. A deposit destination is a cryptocurrency address that can be used to receive funds. The address will be generated for the specified network. + + :param create_deposit_destination_request: (required) + :type create_deposit_destination_request: CreateDepositDestinationRequest + :param x_idempotency_key: An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + :type x_idempotency_key: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_deposit_destination_serialize( + create_deposit_destination_request=create_deposit_destination_request, + x_idempotency_key=x_idempotency_key, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "DepositDestination", + '400': "Error", + '401': "Error", + '404': "Error", + '422': "Error", + '500': "Error", + '503': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def create_deposit_destination_with_http_info( + self, + create_deposit_destination_request: CreateDepositDestinationRequest, + x_idempotency_key: Annotated[Optional[Annotated[str, Field(min_length=1, strict=True, max_length=128)]], Field(description="An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. ")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[DepositDestination]: + """Create deposit destination + + Create a new deposit destination for an account. A deposit destination is a cryptocurrency address that can be used to receive funds. The address will be generated for the specified network. + + :param create_deposit_destination_request: (required) + :type create_deposit_destination_request: CreateDepositDestinationRequest + :param x_idempotency_key: An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + :type x_idempotency_key: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_deposit_destination_serialize( + create_deposit_destination_request=create_deposit_destination_request, + x_idempotency_key=x_idempotency_key, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "DepositDestination", + '400': "Error", + '401': "Error", + '404': "Error", + '422': "Error", + '500': "Error", + '503': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def create_deposit_destination_without_preload_content( + self, + create_deposit_destination_request: CreateDepositDestinationRequest, + x_idempotency_key: Annotated[Optional[Annotated[str, Field(min_length=1, strict=True, max_length=128)]], Field(description="An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. ")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create deposit destination + + Create a new deposit destination for an account. A deposit destination is a cryptocurrency address that can be used to receive funds. The address will be generated for the specified network. + + :param create_deposit_destination_request: (required) + :type create_deposit_destination_request: CreateDepositDestinationRequest + :param x_idempotency_key: An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + :type x_idempotency_key: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_deposit_destination_serialize( + create_deposit_destination_request=create_deposit_destination_request, + x_idempotency_key=x_idempotency_key, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "DepositDestination", + '400': "Error", + '401': "Error", + '404': "Error", + '422': "Error", + '500': "Error", + '503': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _create_deposit_destination_serialize( + self, + create_deposit_destination_request, + x_idempotency_key, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + if x_idempotency_key is not None: + _header_params['X-Idempotency-Key'] = x_idempotency_key + # process the form parameters + # process the body parameter + if create_deposit_destination_request is not None: + _body_params = create_deposit_destination_request + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/v2/deposit-destinations', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + async def get_deposit_destination_by_id( + self, + deposit_destination_id: Annotated[str, Field(strict=True, description="The ID of the deposit address to retrieve.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> DepositDestination: + """Get deposit destination + + Get a specific deposit destination by its ID. + + :param deposit_destination_id: The ID of the deposit address to retrieve. (required) + :type deposit_destination_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_deposit_destination_by_id_serialize( + deposit_destination_id=deposit_destination_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DepositDestination", + '400': "Error", + '401': "Error", + '404': "Error", + '500': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def get_deposit_destination_by_id_with_http_info( + self, + deposit_destination_id: Annotated[str, Field(strict=True, description="The ID of the deposit address to retrieve.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[DepositDestination]: + """Get deposit destination + + Get a specific deposit destination by its ID. + + :param deposit_destination_id: The ID of the deposit address to retrieve. (required) + :type deposit_destination_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_deposit_destination_by_id_serialize( + deposit_destination_id=deposit_destination_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DepositDestination", + '400': "Error", + '401': "Error", + '404': "Error", + '500': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def get_deposit_destination_by_id_without_preload_content( + self, + deposit_destination_id: Annotated[str, Field(strict=True, description="The ID of the deposit address to retrieve.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get deposit destination + + Get a specific deposit destination by its ID. + + :param deposit_destination_id: The ID of the deposit address to retrieve. (required) + :type deposit_destination_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_deposit_destination_by_id_serialize( + deposit_destination_id=deposit_destination_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DepositDestination", + '400': "Error", + '401': "Error", + '404': "Error", + '500': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_deposit_destination_by_id_serialize( + self, + deposit_destination_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if deposit_destination_id is not None: + _path_params['depositDestinationId'] = deposit_destination_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v2/deposit-destinations/{depositDestinationId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + async def list_deposit_destinations( + self, + account_id: Annotated[Optional[Annotated[str, Field(strict=True)]], Field(description="Filter deposit destinations by account ID.")] = None, + address: Annotated[Optional[StrictStr], Field(description="Filter deposit destinations by the cryptocurrency address.")] = None, + type: Annotated[Optional[StrictStr], Field(description="Filter deposit destinations by type.")] = None, + network: Annotated[Optional[StrictStr], Field(description="Filter deposit destinations by network.")] = None, + page_size: Annotated[Optional[StrictInt], Field(description="The number of resources to return per page.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="The token for the next page of resources, if any.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ListDepositDestinations200Response: + """List deposit destinations + + List deposit destinations. You can optionally filter the results by type, account ID, network, or cryptocurrency address. Results are sorted by creation date in descending order (newest first). + + :param account_id: Filter deposit destinations by account ID. + :type account_id: str + :param address: Filter deposit destinations by the cryptocurrency address. + :type address: str + :param type: Filter deposit destinations by type. + :type type: str + :param network: Filter deposit destinations by network. + :type network: str + :param page_size: The number of resources to return per page. + :type page_size: int + :param page_token: The token for the next page of resources, if any. + :type page_token: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_deposit_destinations_serialize( + account_id=account_id, + address=address, + type=type, + network=network, + page_size=page_size, + page_token=page_token, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ListDepositDestinations200Response", + '400': "Error", + '401': "Error", + '500': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def list_deposit_destinations_with_http_info( + self, + account_id: Annotated[Optional[Annotated[str, Field(strict=True)]], Field(description="Filter deposit destinations by account ID.")] = None, + address: Annotated[Optional[StrictStr], Field(description="Filter deposit destinations by the cryptocurrency address.")] = None, + type: Annotated[Optional[StrictStr], Field(description="Filter deposit destinations by type.")] = None, + network: Annotated[Optional[StrictStr], Field(description="Filter deposit destinations by network.")] = None, + page_size: Annotated[Optional[StrictInt], Field(description="The number of resources to return per page.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="The token for the next page of resources, if any.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ListDepositDestinations200Response]: + """List deposit destinations + + List deposit destinations. You can optionally filter the results by type, account ID, network, or cryptocurrency address. Results are sorted by creation date in descending order (newest first). + + :param account_id: Filter deposit destinations by account ID. + :type account_id: str + :param address: Filter deposit destinations by the cryptocurrency address. + :type address: str + :param type: Filter deposit destinations by type. + :type type: str + :param network: Filter deposit destinations by network. + :type network: str + :param page_size: The number of resources to return per page. + :type page_size: int + :param page_token: The token for the next page of resources, if any. + :type page_token: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_deposit_destinations_serialize( + account_id=account_id, + address=address, + type=type, + network=network, + page_size=page_size, + page_token=page_token, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ListDepositDestinations200Response", + '400': "Error", + '401': "Error", + '500': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def list_deposit_destinations_without_preload_content( + self, + account_id: Annotated[Optional[Annotated[str, Field(strict=True)]], Field(description="Filter deposit destinations by account ID.")] = None, + address: Annotated[Optional[StrictStr], Field(description="Filter deposit destinations by the cryptocurrency address.")] = None, + type: Annotated[Optional[StrictStr], Field(description="Filter deposit destinations by type.")] = None, + network: Annotated[Optional[StrictStr], Field(description="Filter deposit destinations by network.")] = None, + page_size: Annotated[Optional[StrictInt], Field(description="The number of resources to return per page.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="The token for the next page of resources, if any.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List deposit destinations + + List deposit destinations. You can optionally filter the results by type, account ID, network, or cryptocurrency address. Results are sorted by creation date in descending order (newest first). + + :param account_id: Filter deposit destinations by account ID. + :type account_id: str + :param address: Filter deposit destinations by the cryptocurrency address. + :type address: str + :param type: Filter deposit destinations by type. + :type type: str + :param network: Filter deposit destinations by network. + :type network: str + :param page_size: The number of resources to return per page. + :type page_size: int + :param page_token: The token for the next page of resources, if any. + :type page_token: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_deposit_destinations_serialize( + account_id=account_id, + address=address, + type=type, + network=network, + page_size=page_size, + page_token=page_token, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ListDepositDestinations200Response", + '400': "Error", + '401': "Error", + '500': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _list_deposit_destinations_serialize( + self, + account_id, + address, + type, + network, + page_size, + page_token, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if account_id is not None: + + _query_params.append(('accountId', account_id)) + + if address is not None: + + _query_params.append(('address', address)) + + if type is not None: + + _query_params.append(('type', type)) + + if network is not None: + + _query_params.append(('network', network)) + + if page_size is not None: + + _query_params.append(('pageSize', page_size)) + + if page_token is not None: + + _query_params.append(('pageToken', page_token)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v2/deposit-destinations', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/python/cdp/openapi_client/api/embedded_wallets_api.py b/python/cdp/openapi_client/api/embedded_wallets_api.py index c0db32961..168cefc31 100644 --- a/python/cdp/openapi_client/api/embedded_wallets_api.py +++ b/python/cdp/openapi_client/api/embedded_wallets_api.py @@ -85,7 +85,7 @@ async def create_delegation_for_end_user_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> GetDelegationForEndUser200Response: - """Create account-scoped delegation for an end user account + """Create account-scoped delegation for end user Creates an account-scoped delegation that allows a developer to sign on behalf of an end user for a single blockchain account (identified by its address) for the specified duration. The end user must be authenticated to authorize this delegation. Multiple account-scoped delegations may exist concurrently for a single end user (one per canonical account address). Account-scoped and user-scoped delegations cannot coexist for the same user. When the address corresponds to an EVM Smart Account, the delegation is scoped to the Smart Account's owner EOA rather than the Smart Account address itself. This means `/address/{smartAccountAddress}/delegation` and `/address/{ownerEoaAddress}/delegation` resolve to the same delegation, and the 409 `account_scoped_delegation_active` error may be returned when creating via either address if one already exists for the canonical owner. @@ -182,7 +182,7 @@ async def create_delegation_for_end_user_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[GetDelegationForEndUser200Response]: - """Create account-scoped delegation for an end user account + """Create account-scoped delegation for end user Creates an account-scoped delegation that allows a developer to sign on behalf of an end user for a single blockchain account (identified by its address) for the specified duration. The end user must be authenticated to authorize this delegation. Multiple account-scoped delegations may exist concurrently for a single end user (one per canonical account address). Account-scoped and user-scoped delegations cannot coexist for the same user. When the address corresponds to an EVM Smart Account, the delegation is scoped to the Smart Account's owner EOA rather than the Smart Account address itself. This means `/address/{smartAccountAddress}/delegation` and `/address/{ownerEoaAddress}/delegation` resolve to the same delegation, and the 409 `account_scoped_delegation_active` error may be returned when creating via either address if one already exists for the canonical owner. @@ -279,7 +279,7 @@ async def create_delegation_for_end_user_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Create account-scoped delegation for an end user account + """Create account-scoped delegation for end user Creates an account-scoped delegation that allows a developer to sign on behalf of an end user for a single blockchain account (identified by its address) for the specified duration. The end user must be authenticated to authorize this delegation. Multiple account-scoped delegations may exist concurrently for a single end user (one per canonical account address). Account-scoped and user-scoped delegations cannot coexist for the same user. When the address corresponds to an EVM Smart Account, the delegation is scoped to the Smart Account's owner EOA rather than the Smart Account address itself. This means `/address/{smartAccountAddress}/delegation` and `/address/{ownerEoaAddress}/delegation` resolve to the same delegation, and the 409 `account_scoped_delegation_active` error may be returned when creating via either address if one already exists for the canonical owner. @@ -522,6 +522,7 @@ async def create_evm_eip7702_delegation_with_end_user_account( '400': "Error", '401': "Error", '402': "Error", + '403': "Error", '404': "Error", '409': "Error", '422': "Error", @@ -619,6 +620,7 @@ async def create_evm_eip7702_delegation_with_end_user_account_with_http_info( '400': "Error", '401': "Error", '402': "Error", + '403': "Error", '404': "Error", '409': "Error", '422': "Error", @@ -716,6 +718,7 @@ async def create_evm_eip7702_delegation_with_end_user_account_without_preload_co '400': "Error", '401': "Error", '402': "Error", + '403': "Error", '404': "Error", '409': "Error", '422': "Error", @@ -1139,7 +1142,7 @@ async def get_delegation_for_end_user_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> GetDelegationForEndUser200Response: - """Get account-scoped delegation for an end user account + """Get account-scoped delegation for end user Returns the active account-scoped delegation for the specified end user account, if one exists. Useful for showing delegation status in a UI. When the address corresponds to an EVM Smart Account, this returns the delegation for the Smart Account's owner EOA. @@ -1219,7 +1222,7 @@ async def get_delegation_for_end_user_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[GetDelegationForEndUser200Response]: - """Get account-scoped delegation for an end user account + """Get account-scoped delegation for end user Returns the active account-scoped delegation for the specified end user account, if one exists. Useful for showing delegation status in a UI. When the address corresponds to an EVM Smart Account, this returns the delegation for the Smart Account's owner EOA. @@ -1299,7 +1302,7 @@ async def get_delegation_for_end_user_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Get account-scoped delegation for an end user account + """Get account-scoped delegation for end user Returns the active account-scoped delegation for the specified end user account, if one exists. Useful for showing delegation status in a UI. When the address corresponds to an EVM Smart Account, this returns the delegation for the Smart Account's owner EOA. @@ -1819,7 +1822,7 @@ async def revoke_delegation_for_end_user_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Revoke account-scoped delegation for an end user account + """Revoke account-scoped delegation for end user Revokes the active account-scoped delegation for the specified end user account. Other account-scoped delegations for the same user are unaffected. This operation can be performed by the end user themselves or by a developer using their API key. When the address corresponds to an EVM Smart Account, this revokes the delegation for the Smart Account's owner EOA. @@ -1915,7 +1918,7 @@ async def revoke_delegation_for_end_user_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[None]: - """Revoke account-scoped delegation for an end user account + """Revoke account-scoped delegation for end user Revokes the active account-scoped delegation for the specified end user account. Other account-scoped delegations for the same user are unaffected. This operation can be performed by the end user themselves or by a developer using their API key. When the address corresponds to an EVM Smart Account, this revokes the delegation for the Smart Account's owner EOA. @@ -2011,7 +2014,7 @@ async def revoke_delegation_for_end_user_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Revoke account-scoped delegation for an end user account + """Revoke account-scoped delegation for end user Revokes the active account-scoped delegation for the specified end user account. Other account-scoped delegations for the same user are unaffected. This operation can be performed by the end user themselves or by a developer using their API key. When the address corresponds to an EVM Smart Account, this revokes the delegation for the Smart Account's owner EOA. @@ -2264,6 +2267,7 @@ async def send_evm_asset_with_end_user_account( '400': "Error", '401': "Error", '402': "Error", + '403': "Error", '404': "Error", '422': "Error", '500': "Error", @@ -2367,6 +2371,7 @@ async def send_evm_asset_with_end_user_account_with_http_info( '400': "Error", '401': "Error", '402': "Error", + '403': "Error", '404': "Error", '422': "Error", '500': "Error", @@ -2470,6 +2475,7 @@ async def send_evm_asset_with_end_user_account_without_preload_content( '400': "Error", '401': "Error", '402': "Error", + '403': "Error", '404': "Error", '422': "Error", '500': "Error", @@ -2606,7 +2612,7 @@ async def send_evm_transaction_with_end_user_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SendEvmTransactionWithEndUserAccount200Response: - """Send a transaction with end user EVM account + """Send transaction via end user EVM account Signs a transaction with the given end user EVM account and sends it to the indicated supported network. This API handles nonce management and gas estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). **Transaction fields and API behavior** - `to` *(Required)*: The address of the contract or account to send the transaction to. - `chainId` *(Ignored)*: The value of the `chainId` field in the transaction is ignored. The transaction will be sent to the network indicated by the `network` field in the request body. - `nonce` *(Optional)*: The nonce to use for the transaction. If not provided, the API will assign a nonce to the transaction based on the current state of the account. - `maxPriorityFeePerGas` *(Optional)*: The maximum priority fee per gas to use for the transaction. If not provided, the API will estimate a value based on current network conditions. - `maxFeePerGas` *(Optional)*: The maximum fee per gas to use for the transaction. If not provided, the API will estimate a value based on current network conditions. - `gasLimit` *(Optional)*: The gas limit to use for the transaction. If not provided, the API will estimate a value based on the `to` and `data` fields of the transaction. - `value` *(Optional)*: The amount of ETH, in wei, to send with the transaction. - `data` *(Optional)*: The data to send with the transaction; only used for contract calls. - `accessList` *(Optional)*: The access list to use for the transaction. @@ -2703,7 +2709,7 @@ async def send_evm_transaction_with_end_user_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SendEvmTransactionWithEndUserAccount200Response]: - """Send a transaction with end user EVM account + """Send transaction via end user EVM account Signs a transaction with the given end user EVM account and sends it to the indicated supported network. This API handles nonce management and gas estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). **Transaction fields and API behavior** - `to` *(Required)*: The address of the contract or account to send the transaction to. - `chainId` *(Ignored)*: The value of the `chainId` field in the transaction is ignored. The transaction will be sent to the network indicated by the `network` field in the request body. - `nonce` *(Optional)*: The nonce to use for the transaction. If not provided, the API will assign a nonce to the transaction based on the current state of the account. - `maxPriorityFeePerGas` *(Optional)*: The maximum priority fee per gas to use for the transaction. If not provided, the API will estimate a value based on current network conditions. - `maxFeePerGas` *(Optional)*: The maximum fee per gas to use for the transaction. If not provided, the API will estimate a value based on current network conditions. - `gasLimit` *(Optional)*: The gas limit to use for the transaction. If not provided, the API will estimate a value based on the `to` and `data` fields of the transaction. - `value` *(Optional)*: The amount of ETH, in wei, to send with the transaction. - `data` *(Optional)*: The data to send with the transaction; only used for contract calls. - `accessList` *(Optional)*: The access list to use for the transaction. @@ -2800,7 +2806,7 @@ async def send_evm_transaction_with_end_user_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Send a transaction with end user EVM account + """Send transaction via end user EVM account Signs a transaction with the given end user EVM account and sends it to the indicated supported network. This API handles nonce management and gas estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). **Transaction fields and API behavior** - `to` *(Required)*: The address of the contract or account to send the transaction to. - `chainId` *(Ignored)*: The value of the `chainId` field in the transaction is ignored. The transaction will be sent to the network indicated by the `network` field in the request body. - `nonce` *(Optional)*: The nonce to use for the transaction. If not provided, the API will assign a nonce to the transaction based on the current state of the account. - `maxPriorityFeePerGas` *(Optional)*: The maximum priority fee per gas to use for the transaction. If not provided, the API will estimate a value based on current network conditions. - `maxFeePerGas` *(Optional)*: The maximum fee per gas to use for the transaction. If not provided, the API will estimate a value based on current network conditions. - `gasLimit` *(Optional)*: The gas limit to use for the transaction. If not provided, the API will estimate a value based on the `to` and `data` fields of the transaction. - `value` *(Optional)*: The amount of ETH, in wei, to send with the transaction. - `data` *(Optional)*: The data to send with the transaction; only used for contract calls. - `accessList` *(Optional)*: The access list to use for the transaction. @@ -3052,6 +3058,7 @@ async def send_solana_asset_with_end_user_account( '400': "Error", '401': "Error", '402': "Error", + '403': "Error", '404': "Error", '422': "Error", '500': "Error", @@ -3155,6 +3162,7 @@ async def send_solana_asset_with_end_user_account_with_http_info( '400': "Error", '401': "Error", '402': "Error", + '403': "Error", '404': "Error", '422': "Error", '500': "Error", @@ -3258,6 +3266,7 @@ async def send_solana_asset_with_end_user_account_without_preload_content( '400': "Error", '401': "Error", '402': "Error", + '403': "Error", '404': "Error", '422': "Error", '500': "Error", @@ -3394,7 +3403,7 @@ async def send_solana_transaction_with_end_user_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SendSolanaTransactionWithEndUserAccount200Response: - """Send a transaction with end user Solana account + """Send transaction via end user Solana account Signs a transaction with the given end user Solana account and sends it to the indicated supported network. The API handles recent blockhash management and fee estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. The unsigned transaction should be serialized into a byte array and then encoded as base64. **Transaction types** The following transaction types are supported: * [Legacy transactions](https://solana.com/developers/guides/advanced/versions#current-transaction-versions) * [Versioned transactions](https://solana.com/developers/guides/advanced/versions) **Instruction Batching** To batch multiple operations, include multiple instructions within a single transaction. All instructions within a transaction are executed atomically - if any instruction fails, the entire transaction fails and is rolled back. **Network Support** The following Solana networks are supported: * `solana` - Solana Mainnet * `solana-devnet` - Solana Devnet The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. @@ -3490,7 +3499,7 @@ async def send_solana_transaction_with_end_user_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SendSolanaTransactionWithEndUserAccount200Response]: - """Send a transaction with end user Solana account + """Send transaction via end user Solana account Signs a transaction with the given end user Solana account and sends it to the indicated supported network. The API handles recent blockhash management and fee estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. The unsigned transaction should be serialized into a byte array and then encoded as base64. **Transaction types** The following transaction types are supported: * [Legacy transactions](https://solana.com/developers/guides/advanced/versions#current-transaction-versions) * [Versioned transactions](https://solana.com/developers/guides/advanced/versions) **Instruction Batching** To batch multiple operations, include multiple instructions within a single transaction. All instructions within a transaction are executed atomically - if any instruction fails, the entire transaction fails and is rolled back. **Network Support** The following Solana networks are supported: * `solana` - Solana Mainnet * `solana-devnet` - Solana Devnet The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. @@ -3586,7 +3595,7 @@ async def send_solana_transaction_with_end_user_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Send a transaction with end user Solana account + """Send transaction via end user Solana account Signs a transaction with the given end user Solana account and sends it to the indicated supported network. The API handles recent blockhash management and fee estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. The unsigned transaction should be serialized into a byte array and then encoded as base64. **Transaction types** The following transaction types are supported: * [Legacy transactions](https://solana.com/developers/guides/advanced/versions#current-transaction-versions) * [Versioned transactions](https://solana.com/developers/guides/advanced/versions) **Instruction Batching** To batch multiple operations, include multiple instructions within a single transaction. All instructions within a transaction are executed atomically - if any instruction fails, the entire transaction fails and is rolled back. **Network Support** The following Solana networks are supported: * `solana` - Solana Mainnet * `solana-devnet` - Solana Devnet The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. @@ -3774,7 +3783,7 @@ async def send_user_operation_with_end_user_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> EvmUserOperation: - """Send a user operation for end user Smart Account + """Send user operation for end user Smart Account Prepares, signs, and sends a user operation for an end user's Smart Account. @@ -3874,7 +3883,7 @@ async def send_user_operation_with_end_user_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[EvmUserOperation]: - """Send a user operation for end user Smart Account + """Send user operation for end user Smart Account Prepares, signs, and sends a user operation for an end user's Smart Account. @@ -3974,7 +3983,7 @@ async def send_user_operation_with_end_user_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Send a user operation for end user Smart Account + """Send user operation for end user Smart Account Prepares, signs, and sends a user operation for an end user's Smart Account. @@ -4167,7 +4176,7 @@ async def sign_evm_message_with_end_user_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SignEvmMessageWithEndUserAccount200Response: - """Sign an EIP-191 message with end user EVM account + """Sign EIP-191 message via end user EVM account Signs an [EIP-191](https://eips.ethereum.org/EIPS/eip-191) message with the given end user EVM account. Per the specification, the message in the request body is prepended with `0x19 <0x45 (E)> ` before being signed. @@ -4222,6 +4231,7 @@ async def sign_evm_message_with_end_user_account( '200': "SignEvmMessageWithEndUserAccount200Response", '401': "Error", '402': "Error", + '403': "Error", '404': "Error", '409': "Error", '422': "Error", @@ -4262,7 +4272,7 @@ async def sign_evm_message_with_end_user_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SignEvmMessageWithEndUserAccount200Response]: - """Sign an EIP-191 message with end user EVM account + """Sign EIP-191 message via end user EVM account Signs an [EIP-191](https://eips.ethereum.org/EIPS/eip-191) message with the given end user EVM account. Per the specification, the message in the request body is prepended with `0x19 <0x45 (E)> ` before being signed. @@ -4317,6 +4327,7 @@ async def sign_evm_message_with_end_user_account_with_http_info( '200': "SignEvmMessageWithEndUserAccount200Response", '401': "Error", '402': "Error", + '403': "Error", '404': "Error", '409': "Error", '422': "Error", @@ -4357,7 +4368,7 @@ async def sign_evm_message_with_end_user_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Sign an EIP-191 message with end user EVM account + """Sign EIP-191 message via end user EVM account Signs an [EIP-191](https://eips.ethereum.org/EIPS/eip-191) message with the given end user EVM account. Per the specification, the message in the request body is prepended with `0x19 <0x45 (E)> ` before being signed. @@ -4412,6 +4423,7 @@ async def sign_evm_message_with_end_user_account_without_preload_content( '200': "SignEvmMessageWithEndUserAccount200Response", '401': "Error", '402': "Error", + '403': "Error", '404': "Error", '409': "Error", '422': "Error", @@ -4543,7 +4555,7 @@ async def sign_evm_transaction_with_end_user_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SignEvmTransactionWithEndUserAccount200Response: - """Sign a transaction with end user EVM account + """Sign transaction via end user EVM account Signs a transaction with the given end user EVM account. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. @@ -4640,7 +4652,7 @@ async def sign_evm_transaction_with_end_user_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SignEvmTransactionWithEndUserAccount200Response]: - """Sign a transaction with end user EVM account + """Sign transaction via end user EVM account Signs a transaction with the given end user EVM account. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. @@ -4737,7 +4749,7 @@ async def sign_evm_transaction_with_end_user_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Sign a transaction with end user EVM account + """Sign transaction via end user EVM account Signs a transaction with the given end user EVM account. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. @@ -4925,7 +4937,7 @@ async def sign_evm_typed_data_with_end_user_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SignEvmTypedDataWithEndUserAccount200Response: - """Sign EIP-712 typed data with end user EVM account + """Sign EIP-712 typed data via end user EVM account Signs [EIP-712](https://eips.ethereum.org/EIPS/eip-712) typed data with the given end user EVM account. @@ -4981,6 +4993,7 @@ async def sign_evm_typed_data_with_end_user_account( '400': "Error", '401': "Error", '402': "Error", + '403': "Error", '404': "Error", '422': "Error", '500': "Error", @@ -5020,7 +5033,7 @@ async def sign_evm_typed_data_with_end_user_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SignEvmTypedDataWithEndUserAccount200Response]: - """Sign EIP-712 typed data with end user EVM account + """Sign EIP-712 typed data via end user EVM account Signs [EIP-712](https://eips.ethereum.org/EIPS/eip-712) typed data with the given end user EVM account. @@ -5076,6 +5089,7 @@ async def sign_evm_typed_data_with_end_user_account_with_http_info( '400': "Error", '401': "Error", '402': "Error", + '403': "Error", '404': "Error", '422': "Error", '500': "Error", @@ -5115,7 +5129,7 @@ async def sign_evm_typed_data_with_end_user_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Sign EIP-712 typed data with end user EVM account + """Sign EIP-712 typed data via end user EVM account Signs [EIP-712](https://eips.ethereum.org/EIPS/eip-712) typed data with the given end user EVM account. @@ -5171,6 +5185,7 @@ async def sign_evm_typed_data_with_end_user_account_without_preload_content( '400': "Error", '401': "Error", '402': "Error", + '403': "Error", '404': "Error", '422': "Error", '500': "Error", @@ -5301,7 +5316,7 @@ async def sign_solana_message_with_end_user_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SignSolanaMessageWithEndUserAccount200Response: - """Sign a Base64 encoded message + """Sign Base64-encoded message Signs an arbitrary Base64 encoded message with the given Solana account. **WARNING:** Never sign a message that you didn't generate as it may put your funds at risk. @@ -5357,6 +5372,7 @@ async def sign_solana_message_with_end_user_account( '400': "Error", '401': "Error", '402': "Error", + '403': "Error", '404': "Error", '409': "Error", '422': "Error", @@ -5397,7 +5413,7 @@ async def sign_solana_message_with_end_user_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SignSolanaMessageWithEndUserAccount200Response]: - """Sign a Base64 encoded message + """Sign Base64-encoded message Signs an arbitrary Base64 encoded message with the given Solana account. **WARNING:** Never sign a message that you didn't generate as it may put your funds at risk. @@ -5453,6 +5469,7 @@ async def sign_solana_message_with_end_user_account_with_http_info( '400': "Error", '401': "Error", '402': "Error", + '403': "Error", '404': "Error", '409': "Error", '422': "Error", @@ -5493,7 +5510,7 @@ async def sign_solana_message_with_end_user_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Sign a Base64 encoded message + """Sign Base64-encoded message Signs an arbitrary Base64 encoded message with the given Solana account. **WARNING:** Never sign a message that you didn't generate as it may put your funds at risk. @@ -5549,6 +5566,7 @@ async def sign_solana_message_with_end_user_account_without_preload_content( '400': "Error", '401': "Error", '402': "Error", + '403': "Error", '404': "Error", '409': "Error", '422': "Error", @@ -5680,7 +5698,7 @@ async def sign_solana_transaction_with_end_user_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SignSolanaTransactionWithEndUserAccount200Response: - """Sign a transaction with end user Solana account + """Sign transaction via end user Solana account Signs a transaction with the given end user Solana account. The unsigned transaction should be serialized into a byte array and then encoded as base64. **Transaction types** The following transaction types are supported: * [Legacy transactions](https://solana-labs.github.io/solana-web3.js/classes/Transaction.html) * [Versioned transactions](https://solana-labs.github.io/solana-web3.js/classes/VersionedTransaction.html) The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. @@ -5777,7 +5795,7 @@ async def sign_solana_transaction_with_end_user_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SignSolanaTransactionWithEndUserAccount200Response]: - """Sign a transaction with end user Solana account + """Sign transaction via end user Solana account Signs a transaction with the given end user Solana account. The unsigned transaction should be serialized into a byte array and then encoded as base64. **Transaction types** The following transaction types are supported: * [Legacy transactions](https://solana-labs.github.io/solana-web3.js/classes/Transaction.html) * [Versioned transactions](https://solana-labs.github.io/solana-web3.js/classes/VersionedTransaction.html) The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. @@ -5874,7 +5892,7 @@ async def sign_solana_transaction_with_end_user_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Sign a transaction with end user Solana account + """Sign transaction via end user Solana account Signs a transaction with the given end user Solana account. The unsigned transaction should be serialized into a byte array and then encoded as base64. **Transaction types** The following transaction types are supported: * [Legacy transactions](https://solana-labs.github.io/solana-web3.js/classes/Transaction.html) * [Versioned transactions](https://solana-labs.github.io/solana-web3.js/classes/VersionedTransaction.html) The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. diff --git a/python/cdp/openapi_client/api/end_user_accounts_api.py b/python/cdp/openapi_client/api/end_user_accounts_api.py index 970c5022b..6a420fca0 100644 --- a/python/cdp/openapi_client/api/end_user_accounts_api.py +++ b/python/cdp/openapi_client/api/end_user_accounts_api.py @@ -70,7 +70,7 @@ async def add_end_user_evm_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> AddEndUserEvmAccount201Response: - """Add an EVM account to an end user + """Add EVM account to end user Adds a new EVM EOA account to an existing end user. End users can have up to 10 EVM accounts. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. @@ -157,7 +157,7 @@ async def add_end_user_evm_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[AddEndUserEvmAccount201Response]: - """Add an EVM account to an end user + """Add EVM account to end user Adds a new EVM EOA account to an existing end user. End users can have up to 10 EVM accounts. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. @@ -244,7 +244,7 @@ async def add_end_user_evm_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Add an EVM account to an end user + """Add EVM account to end user Adds a new EVM EOA account to an existing end user. End users can have up to 10 EVM accounts. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. @@ -413,7 +413,7 @@ async def add_end_user_evm_smart_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> AddEndUserEvmSmartAccount201Response: - """Add an EVM smart account to an end user + """Add EVM smart account to end user Creates an EVM smart account for an existing end user. The backend will create a new EVM EOA account to serve as the owner of the smart account. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. @@ -500,7 +500,7 @@ async def add_end_user_evm_smart_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[AddEndUserEvmSmartAccount201Response]: - """Add an EVM smart account to an end user + """Add EVM smart account to end user Creates an EVM smart account for an existing end user. The backend will create a new EVM EOA account to serve as the owner of the smart account. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. @@ -587,7 +587,7 @@ async def add_end_user_evm_smart_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Add an EVM smart account to an end user + """Add EVM smart account to end user Creates an EVM smart account for an existing end user. The backend will create a new EVM EOA account to serve as the owner of the smart account. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. @@ -756,7 +756,7 @@ async def add_end_user_solana_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> AddEndUserSolanaAccount201Response: - """Add a Solana account to an end user + """Add Solana account to end user Adds a new Solana account to an existing end user. End users can have up to 10 Solana accounts. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. @@ -843,7 +843,7 @@ async def add_end_user_solana_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[AddEndUserSolanaAccount201Response]: - """Add a Solana account to an end user + """Add Solana account to end user Adds a new Solana account to an existing end user. End users can have up to 10 Solana accounts. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. @@ -930,7 +930,7 @@ async def add_end_user_solana_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Add a Solana account to an end user + """Add Solana account to end user Adds a new Solana account to an existing end user. End users can have up to 10 Solana accounts. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. @@ -1098,7 +1098,7 @@ async def create_end_user( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> EndUser: - """Create an end user + """Create end user Creates an end user. An end user is an entity that can own CDP EVM accounts, EVM smart accounts, and/or Solana accounts. 1 or more authentication methods must be associated with an end user. By default, no accounts are created unless the optional `evmAccount` and/or `solanaAccount` fields are provided. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. @@ -1178,7 +1178,7 @@ async def create_end_user_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[EndUser]: - """Create an end user + """Create end user Creates an end user. An end user is an entity that can own CDP EVM accounts, EVM smart accounts, and/or Solana accounts. 1 or more authentication methods must be associated with an end user. By default, no accounts are created unless the optional `evmAccount` and/or `solanaAccount` fields are provided. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. @@ -1258,7 +1258,7 @@ async def create_end_user_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Create an end user + """Create end user Creates an end user. An end user is an entity that can own CDP EVM accounts, EVM smart accounts, and/or Solana accounts. 1 or more authentication methods must be associated with an end user. By default, no accounts are created unless the optional `evmAccount` and/or `solanaAccount` fields are provided. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. @@ -1415,7 +1415,7 @@ async def get_end_user( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> EndUser: - """Get an end user + """Get end user Gets an end user by ID. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. @@ -1484,7 +1484,7 @@ async def get_end_user_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[EndUser]: - """Get an end user + """Get end user Gets an end user by ID. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. @@ -1553,7 +1553,7 @@ async def get_end_user_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Get an end user + """Get end user Gets an end user by ID. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. @@ -1684,7 +1684,7 @@ async def import_end_user( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> EndUser: - """Import a private key for an end user + """Import end user private key Imports an existing private key for an end user into the developer's CDP Project. The private key must be encrypted using the CDP SDK's encryption scheme before being sent to this endpoint. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. This endpoint allows developers to import existing keys for their end users, supporting both EVM and Solana key types. The end user must have at least one authentication method configured. @@ -1767,7 +1767,7 @@ async def import_end_user_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[EndUser]: - """Import a private key for an end user + """Import end user private key Imports an existing private key for an end user into the developer's CDP Project. The private key must be encrypted using the CDP SDK's encryption scheme before being sent to this endpoint. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. This endpoint allows developers to import existing keys for their end users, supporting both EVM and Solana key types. The end user must have at least one authentication method configured. @@ -1850,7 +1850,7 @@ async def import_end_user_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Import a private key for an end user + """Import end user private key Imports an existing private key for an end user into the developer's CDP Project. The private key must be encrypted using the CDP SDK's encryption scheme before being sent to this endpoint. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. This endpoint allows developers to import existing keys for their end users, supporting both EVM and Solana key types. The end user must have at least one authentication method configured. diff --git a/python/cdp/openapi_client/api/evm_accounts_api.py b/python/cdp/openapi_client/api/evm_accounts_api.py index 5aa4d2af4..77f264f93 100644 --- a/python/cdp/openapi_client/api/evm_accounts_api.py +++ b/python/cdp/openapi_client/api/evm_accounts_api.py @@ -78,7 +78,7 @@ async def create_evm_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> EvmAccount: - """Create an EVM account + """Create EVM account Creates a new EVM account. @@ -161,7 +161,7 @@ async def create_evm_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[EvmAccount]: - """Create an EVM account + """Create EVM account Creates a new EVM account. @@ -244,7 +244,7 @@ async def create_evm_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Create an EVM account + """Create EVM account Creates a new EVM account. @@ -753,7 +753,7 @@ async def export_evm_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ExportEvmAccount200Response: - """Export an EVM account + """Export EVM account Export an existing EVM account's private key. It is important to store the private key in a secure place after it's exported. @@ -840,7 +840,7 @@ async def export_evm_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[ExportEvmAccount200Response]: - """Export an EVM account + """Export EVM account Export an existing EVM account's private key. It is important to store the private key in a secure place after it's exported. @@ -927,7 +927,7 @@ async def export_evm_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Export an EVM account + """Export EVM account Export an existing EVM account's private key. It is important to store the private key in a secure place after it's exported. @@ -1096,7 +1096,7 @@ async def export_evm_account_by_name( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ExportEvmAccount200Response: - """Export an EVM account by name + """Export EVM account by name Export an existing EVM account's private key by its name. It is important to store the private key in a secure place after it's exported. @@ -1183,7 +1183,7 @@ async def export_evm_account_by_name_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[ExportEvmAccount200Response]: - """Export an EVM account by name + """Export EVM account by name Export an existing EVM account's private key by its name. It is important to store the private key in a secure place after it's exported. @@ -1270,7 +1270,7 @@ async def export_evm_account_by_name_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Export an EVM account by name + """Export EVM account by name Export an existing EVM account's private key by its name. It is important to store the private key in a secure place after it's exported. @@ -1436,7 +1436,7 @@ async def get_evm_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> EvmAccount: - """Get an EVM account by address + """Get EVM account by address Gets an EVM account by its address. @@ -1508,7 +1508,7 @@ async def get_evm_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[EvmAccount]: - """Get an EVM account by address + """Get EVM account by address Gets an EVM account by its address. @@ -1580,7 +1580,7 @@ async def get_evm_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Get an EVM account by address + """Get EVM account by address Gets an EVM account by its address. @@ -1712,7 +1712,7 @@ async def get_evm_account_by_name( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> EvmAccount: - """Get an EVM account by name + """Get EVM account by name Gets an EVM account by its name. @@ -1784,7 +1784,7 @@ async def get_evm_account_by_name_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[EvmAccount]: - """Get an EVM account by name + """Get EVM account by name Gets an EVM account by its name. @@ -1856,7 +1856,7 @@ async def get_evm_account_by_name_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Get an EVM account by name + """Get EVM account by name Gets an EVM account by its name. @@ -1988,7 +1988,7 @@ async def get_evm_eip7702_delegation_operation_by_id( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> EvmEip7702DelegationOperation: - """Get EIP-7702 delegation operation for an operationID + """Get EIP-7702 delegation operation by ID Returns the EIP-7702 delegation operation. Use the delegationOperationId returned by the Create EIP-7702 delegation endpoint to poll for operation completion. @@ -2060,7 +2060,7 @@ async def get_evm_eip7702_delegation_operation_by_id_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[EvmEip7702DelegationOperation]: - """Get EIP-7702 delegation operation for an operationID + """Get EIP-7702 delegation operation by ID Returns the EIP-7702 delegation operation. Use the delegationOperationId returned by the Create EIP-7702 delegation endpoint to poll for operation completion. @@ -2132,7 +2132,7 @@ async def get_evm_eip7702_delegation_operation_by_id_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Get EIP-7702 delegation operation for an operationID + """Get EIP-7702 delegation operation by ID Returns the EIP-7702 delegation operation. Use the delegationOperationId returned by the Create EIP-7702 delegation endpoint to poll for operation completion. @@ -2266,7 +2266,7 @@ async def import_evm_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> EvmAccount: - """Import an EVM account + """Import EVM account Import an existing EVM account into the developer's CDP Project. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. @@ -2349,7 +2349,7 @@ async def import_evm_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[EvmAccount]: - """Import an EVM account + """Import EVM account Import an existing EVM account into the developer's CDP Project. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. @@ -2432,7 +2432,7 @@ async def import_evm_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Import an EVM account + """Import EVM account Import an existing EVM account into the developer's CDP Project. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. @@ -2884,7 +2884,7 @@ async def send_evm_transaction( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SendEvmTransactionWithEndUserAccount200Response: - """Send a transaction + """Send transaction Signs a transaction with the given EVM account and sends it to the indicated supported network. This API handles nonce management and gas estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). **Transaction fields and API behavior** - `to` *(Required)*: The address of the contract or account to send the transaction to. - `chainId` *(Ignored)*: The value of the `chainId` field in the transaction is ignored. The transaction will be sent to the network indicated by the `network` field in the request body. - `nonce` *(Optional)*: The nonce to use for the transaction. If not provided, the API will assign a nonce to the transaction based on the current state of the account. - `maxPriorityFeePerGas` *(Optional)*: The maximum priority fee per gas to use for the transaction. If not provided, the API will estimate a value based on current network conditions. - `maxFeePerGas` *(Optional)*: The maximum fee per gas to use for the transaction. If not provided, the API will estimate a value based on current network conditions. - `gasLimit` *(Optional)*: The gas limit to use for the transaction. If not provided, the API will estimate a value based on the `to` and `data` fields of the transaction. - `value` *(Optional)*: The amount of ETH, in wei, to send with the transaction. - `data` *(Optional)*: The data to send with the transaction; only used for contract calls. - `accessList` *(Optional)*: The access list to use for the transaction. @@ -2973,7 +2973,7 @@ async def send_evm_transaction_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SendEvmTransactionWithEndUserAccount200Response]: - """Send a transaction + """Send transaction Signs a transaction with the given EVM account and sends it to the indicated supported network. This API handles nonce management and gas estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). **Transaction fields and API behavior** - `to` *(Required)*: The address of the contract or account to send the transaction to. - `chainId` *(Ignored)*: The value of the `chainId` field in the transaction is ignored. The transaction will be sent to the network indicated by the `network` field in the request body. - `nonce` *(Optional)*: The nonce to use for the transaction. If not provided, the API will assign a nonce to the transaction based on the current state of the account. - `maxPriorityFeePerGas` *(Optional)*: The maximum priority fee per gas to use for the transaction. If not provided, the API will estimate a value based on current network conditions. - `maxFeePerGas` *(Optional)*: The maximum fee per gas to use for the transaction. If not provided, the API will estimate a value based on current network conditions. - `gasLimit` *(Optional)*: The gas limit to use for the transaction. If not provided, the API will estimate a value based on the `to` and `data` fields of the transaction. - `value` *(Optional)*: The amount of ETH, in wei, to send with the transaction. - `data` *(Optional)*: The data to send with the transaction; only used for contract calls. - `accessList` *(Optional)*: The access list to use for the transaction. @@ -3062,7 +3062,7 @@ async def send_evm_transaction_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Send a transaction + """Send transaction Signs a transaction with the given EVM account and sends it to the indicated supported network. This API handles nonce management and gas estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). **Transaction fields and API behavior** - `to` *(Required)*: The address of the contract or account to send the transaction to. - `chainId` *(Ignored)*: The value of the `chainId` field in the transaction is ignored. The transaction will be sent to the network indicated by the `network` field in the request body. - `nonce` *(Optional)*: The nonce to use for the transaction. If not provided, the API will assign a nonce to the transaction based on the current state of the account. - `maxPriorityFeePerGas` *(Optional)*: The maximum priority fee per gas to use for the transaction. If not provided, the API will estimate a value based on current network conditions. - `maxFeePerGas` *(Optional)*: The maximum fee per gas to use for the transaction. If not provided, the API will estimate a value based on current network conditions. - `gasLimit` *(Optional)*: The gas limit to use for the transaction. If not provided, the API will estimate a value based on the `to` and `data` fields of the transaction. - `value` *(Optional)*: The amount of ETH, in wei, to send with the transaction. - `data` *(Optional)*: The data to send with the transaction; only used for contract calls. - `accessList` *(Optional)*: The access list to use for the transaction. @@ -3233,7 +3233,7 @@ async def sign_evm_hash( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SignEvmHash200Response: - """Sign a hash + """Sign hash Signs an arbitrary 32 byte hash with the given EVM account. @@ -3320,7 +3320,7 @@ async def sign_evm_hash_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SignEvmHash200Response]: - """Sign a hash + """Sign hash Signs an arbitrary 32 byte hash with the given EVM account. @@ -3407,7 +3407,7 @@ async def sign_evm_hash_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Sign a hash + """Sign hash Signs an arbitrary 32 byte hash with the given EVM account. @@ -3576,7 +3576,7 @@ async def sign_evm_message( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SignEvmMessageWithEndUserAccount200Response: - """Sign an EIP-191 message + """Sign EIP-191 message Signs an [EIP-191](https://eips.ethereum.org/EIPS/eip-191) message with the given EVM account. Per the specification, the message in the request body is prepended with `0x19 <0x45 (E)> ` before being signed. @@ -3663,7 +3663,7 @@ async def sign_evm_message_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SignEvmMessageWithEndUserAccount200Response]: - """Sign an EIP-191 message + """Sign EIP-191 message Signs an [EIP-191](https://eips.ethereum.org/EIPS/eip-191) message with the given EVM account. Per the specification, the message in the request body is prepended with `0x19 <0x45 (E)> ` before being signed. @@ -3750,7 +3750,7 @@ async def sign_evm_message_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Sign an EIP-191 message + """Sign EIP-191 message Signs an [EIP-191](https://eips.ethereum.org/EIPS/eip-191) message with the given EVM account. Per the specification, the message in the request body is prepended with `0x19 <0x45 (E)> ` before being signed. @@ -3919,7 +3919,7 @@ async def sign_evm_transaction( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SignEvmTransactionWithEndUserAccount200Response: - """Sign a transaction + """Sign transaction Signs a transaction with the given EVM account. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. @@ -4008,7 +4008,7 @@ async def sign_evm_transaction_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SignEvmTransactionWithEndUserAccount200Response]: - """Sign a transaction + """Sign transaction Signs a transaction with the given EVM account. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. @@ -4097,7 +4097,7 @@ async def sign_evm_transaction_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Sign a transaction + """Sign transaction Signs a transaction with the given EVM account. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. @@ -4610,7 +4610,7 @@ async def update_evm_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> EvmAccount: - """Update an EVM account + """Update EVM account Updates an existing EVM account. Use this to update the account's name or account-level policy. @@ -4692,7 +4692,7 @@ async def update_evm_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[EvmAccount]: - """Update an EVM account + """Update EVM account Updates an existing EVM account. Use this to update the account's name or account-level policy. @@ -4774,7 +4774,7 @@ async def update_evm_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Update an EVM account + """Update EVM account Updates an existing EVM account. Use this to update the account's name or account-level policy. diff --git a/python/cdp/openapi_client/api/evm_smart_accounts_api.py b/python/cdp/openapi_client/api/evm_smart_accounts_api.py index 87bd7c7b1..0558c64ed 100644 --- a/python/cdp/openapi_client/api/evm_smart_accounts_api.py +++ b/python/cdp/openapi_client/api/evm_smart_accounts_api.py @@ -68,7 +68,7 @@ async def create_evm_smart_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> EvmSmartAccount: - """Create a Smart Account + """Create Smart Account Creates a new Smart Account. @@ -144,7 +144,7 @@ async def create_evm_smart_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[EvmSmartAccount]: - """Create a Smart Account + """Create Smart Account Creates a new Smart Account. @@ -220,7 +220,7 @@ async def create_evm_smart_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Create a Smart Account + """Create Smart Account Creates a new Smart Account. @@ -374,7 +374,7 @@ async def create_spend_permission( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> EvmUserOperation: - """Create a spend permission + """Create spend permission Creates a spend permission for the given smart account address. @@ -458,7 +458,7 @@ async def create_spend_permission_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[EvmUserOperation]: - """Create a spend permission + """Create spend permission Creates a spend permission for the given smart account address. @@ -542,7 +542,7 @@ async def create_spend_permission_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Create a spend permission + """Create spend permission Creates a spend permission for the given smart account address. @@ -705,7 +705,7 @@ async def get_evm_smart_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> EvmSmartAccount: - """Get a Smart Account by address + """Get Smart Account by address Gets a Smart Account by its address. @@ -777,7 +777,7 @@ async def get_evm_smart_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[EvmSmartAccount]: - """Get a Smart Account by address + """Get Smart Account by address Gets a Smart Account by its address. @@ -849,7 +849,7 @@ async def get_evm_smart_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Get a Smart Account by address + """Get Smart Account by address Gets a Smart Account by its address. @@ -981,7 +981,7 @@ async def get_evm_smart_account_by_name( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> EvmSmartAccount: - """Get a Smart Account by name + """Get Smart Account by name Gets a Smart Account by its name. @@ -1053,7 +1053,7 @@ async def get_evm_smart_account_by_name_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[EvmSmartAccount]: - """Get a Smart Account by name + """Get Smart Account by name Gets a Smart Account by its name. @@ -1125,7 +1125,7 @@ async def get_evm_smart_account_by_name_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Get a Smart Account by name + """Get Smart Account by name Gets a Smart Account by its name. @@ -1258,7 +1258,7 @@ async def get_user_operation( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> EvmUserOperation: - """Get a user operation + """Get user operation Gets a user operation by its hash. @@ -1334,7 +1334,7 @@ async def get_user_operation_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[EvmUserOperation]: - """Get a user operation + """Get user operation Gets a user operation by its hash. @@ -1410,7 +1410,7 @@ async def get_user_operation_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Get a user operation + """Get user operation Gets a user operation by its hash. @@ -2153,7 +2153,7 @@ async def prepare_and_send_user_operation( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> EvmUserOperation: - """Prepare and send a user operation for EVM Smart Account + """Prepare and send user operation Prepares, signs, and sends a user operation for an EVM Smart Account. This API can be used only if the owner on Smart Account is a CDP EVM Account. @@ -2241,7 +2241,7 @@ async def prepare_and_send_user_operation_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[EvmUserOperation]: - """Prepare and send a user operation for EVM Smart Account + """Prepare and send user operation Prepares, signs, and sends a user operation for an EVM Smart Account. This API can be used only if the owner on Smart Account is a CDP EVM Account. @@ -2329,7 +2329,7 @@ async def prepare_and_send_user_operation_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Prepare and send a user operation for EVM Smart Account + """Prepare and send user operation Prepares, signs, and sends a user operation for an EVM Smart Account. This API can be used only if the owner on Smart Account is a CDP EVM Account. @@ -2497,7 +2497,7 @@ async def prepare_user_operation( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> EvmUserOperation: - """Prepare a user operation + """Prepare user operation Prepares a new user operation on a Smart Account for a specific network. @@ -2574,7 +2574,7 @@ async def prepare_user_operation_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[EvmUserOperation]: - """Prepare a user operation + """Prepare user operation Prepares a new user operation on a Smart Account for a specific network. @@ -2651,7 +2651,7 @@ async def prepare_user_operation_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Prepare a user operation + """Prepare user operation Prepares a new user operation on a Smart Account for a specific network. @@ -2806,7 +2806,7 @@ async def revoke_spend_permission( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> EvmUserOperation: - """Revoke a spend permission + """Revoke spend permission Revokes an existing spend permission. @@ -2890,7 +2890,7 @@ async def revoke_spend_permission_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[EvmUserOperation]: - """Revoke a spend permission + """Revoke spend permission Revokes an existing spend permission. @@ -2974,7 +2974,7 @@ async def revoke_spend_permission_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Revoke a spend permission + """Revoke spend permission Revokes an existing spend permission. @@ -3139,7 +3139,7 @@ async def send_user_operation( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> EvmUserOperation: - """Send a user operation + """Send user operation Sends a user operation with a signature. The payload to sign must be the `userOpHash` field of the user operation. This hash should be signed directly (not using `personal_sign` or EIP-191 message hashing). The signature must be 65 bytes in length, consisting of: - 32 bytes for the `r` value - 32 bytes for the `s` value - 1 byte for the `v` value (must be 27 or 28) If using the CDP Paymaster, the user operation must be signed and sent within 2 minutes of being prepared. @@ -3222,7 +3222,7 @@ async def send_user_operation_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[EvmUserOperation]: - """Send a user operation + """Send user operation Sends a user operation with a signature. The payload to sign must be the `userOpHash` field of the user operation. This hash should be signed directly (not using `personal_sign` or EIP-191 message hashing). The signature must be 65 bytes in length, consisting of: - 32 bytes for the `r` value - 32 bytes for the `s` value - 1 byte for the `v` value (must be 27 or 28) If using the CDP Paymaster, the user operation must be signed and sent within 2 minutes of being prepared. @@ -3305,7 +3305,7 @@ async def send_user_operation_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Send a user operation + """Send user operation Sends a user operation with a signature. The payload to sign must be the `userOpHash` field of the user operation. This hash should be signed directly (not using `personal_sign` or EIP-191 message hashing). The signature must be 65 bytes in length, consisting of: - 32 bytes for the `r` value - 32 bytes for the `s` value - 1 byte for the `v` value (must be 27 or 28) If using the CDP Paymaster, the user operation must be signed and sent within 2 minutes of being prepared. @@ -3466,7 +3466,7 @@ async def update_evm_smart_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> EvmSmartAccount: - """Update an EVM Smart Account + """Update EVM Smart Account Updates an existing EVM smart account. Use this to update the smart account's name. @@ -3544,7 +3544,7 @@ async def update_evm_smart_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[EvmSmartAccount]: - """Update an EVM Smart Account + """Update EVM Smart Account Updates an existing EVM smart account. Use this to update the smart account's name. @@ -3622,7 +3622,7 @@ async def update_evm_smart_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Update an EVM Smart Account + """Update EVM Smart Account Updates an existing EVM smart account. Use this to update the smart account's name. diff --git a/python/cdp/openapi_client/api/evm_swaps_api.py b/python/cdp/openapi_client/api/evm_swaps_api.py index fd3e276a7..5aa3ca463 100644 --- a/python/cdp/openapi_client/api/evm_swaps_api.py +++ b/python/cdp/openapi_client/api/evm_swaps_api.py @@ -61,7 +61,7 @@ async def create_evm_swap_quote( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> CreateSwapQuoteResponseWrapper: - """Create a swap quote + """Create swap quote Create a swap quote, which includes the payload to sign as well as the transaction data needed to execute the swap. The developer is responsible for signing the payload and submitting the transaction to the network in order to execute the swap. @@ -137,7 +137,7 @@ async def create_evm_swap_quote_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[CreateSwapQuoteResponseWrapper]: - """Create a swap quote + """Create swap quote Create a swap quote, which includes the payload to sign as well as the transaction data needed to execute the swap. The developer is responsible for signing the payload and submitting the transaction to the network in order to execute the swap. @@ -213,7 +213,7 @@ async def create_evm_swap_quote_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Create a swap quote + """Create swap quote Create a swap quote, which includes the payload to sign as well as the transaction data needed to execute the swap. The developer is responsible for signing the payload and submitting the transaction to the network in order to execute the swap. @@ -371,7 +371,7 @@ async def get_evm_swap_price( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> GetSwapPriceResponseWrapper: - """Get a price estimate for a swap + """Get swap price estimate Get a price estimate for a swap between two tokens on an EVM network. @@ -471,7 +471,7 @@ async def get_evm_swap_price_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[GetSwapPriceResponseWrapper]: - """Get a price estimate for a swap + """Get swap price estimate Get a price estimate for a swap between two tokens on an EVM network. @@ -571,7 +571,7 @@ async def get_evm_swap_price_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Get a price estimate for a swap + """Get swap price estimate Get a price estimate for a swap between two tokens on an EVM network. diff --git a/python/cdp/openapi_client/api/payment_methods_api.py b/python/cdp/openapi_client/api/payment_methods_api.py new file mode 100644 index 000000000..df0d75684 --- /dev/null +++ b/python/cdp/openapi_client/api/payment_methods_api.py @@ -0,0 +1,603 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from pydantic import Field, StrictInt, StrictStr, field_validator +from typing import Optional +from typing_extensions import Annotated +from cdp.openapi_client.models.list_payment_methods200_response import ListPaymentMethods200Response +from cdp.openapi_client.models.payment_methods_payment_method import PaymentMethodsPaymentMethod + +from cdp.openapi_client.api_client import ApiClient, RequestSerialized +from cdp.openapi_client.api_response import ApiResponse +from cdp.openapi_client.rest import RESTResponseType + + +class PaymentMethodsApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + async def get_payment_method( + self, + payment_method_id: Annotated[str, Field(strict=True, description="The unique identifier of the payment method.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> PaymentMethodsPaymentMethod: + """Get payment method + + Get details of a specific payment method by its ID. Returns 404 if the payment method is not found or not owned by the requesting entity. + + :param payment_method_id: The unique identifier of the payment method. (required) + :type payment_method_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_payment_method_serialize( + payment_method_id=payment_method_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "PaymentMethodsPaymentMethod", + '400': "Error", + '401': "Error", + '404': "Error", + '500': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def get_payment_method_with_http_info( + self, + payment_method_id: Annotated[str, Field(strict=True, description="The unique identifier of the payment method.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[PaymentMethodsPaymentMethod]: + """Get payment method + + Get details of a specific payment method by its ID. Returns 404 if the payment method is not found or not owned by the requesting entity. + + :param payment_method_id: The unique identifier of the payment method. (required) + :type payment_method_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_payment_method_serialize( + payment_method_id=payment_method_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "PaymentMethodsPaymentMethod", + '400': "Error", + '401': "Error", + '404': "Error", + '500': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def get_payment_method_without_preload_content( + self, + payment_method_id: Annotated[str, Field(strict=True, description="The unique identifier of the payment method.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get payment method + + Get details of a specific payment method by its ID. Returns 404 if the payment method is not found or not owned by the requesting entity. + + :param payment_method_id: The unique identifier of the payment method. (required) + :type payment_method_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_payment_method_serialize( + payment_method_id=payment_method_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "PaymentMethodsPaymentMethod", + '400': "Error", + '401': "Error", + '404': "Error", + '500': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_payment_method_serialize( + self, + payment_method_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if payment_method_id is not None: + _path_params['paymentMethodId'] = payment_method_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v2/payment-methods/{paymentMethodId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + async def list_payment_methods( + self, + page_size: Annotated[Optional[StrictInt], Field(description="The number of resources to return per page.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="The token for the next page of resources, if any.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ListPaymentMethods200Response: + """List payment methods + + List payment methods linked to your entity. Payment methods represent external financial instruments that can be used as a target for transfers. The list will not include disabled or deleted payment methods. **Currently Supported Types:** - `fedwire`: Domestic USD wire transfers - `swift`: International wire transfers - `sepa`: SEPA EUR transfers **Note:** Payment methods are created and verified through your linked CDP entity. Currently, fetching payment methods is only supported for Prime investment vehicles linked to CDP. + + :param page_size: The number of resources to return per page. + :type page_size: int + :param page_token: The token for the next page of resources, if any. + :type page_token: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_payment_methods_serialize( + page_size=page_size, + page_token=page_token, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ListPaymentMethods200Response", + '400': "Error", + '401': "Error", + '500': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def list_payment_methods_with_http_info( + self, + page_size: Annotated[Optional[StrictInt], Field(description="The number of resources to return per page.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="The token for the next page of resources, if any.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ListPaymentMethods200Response]: + """List payment methods + + List payment methods linked to your entity. Payment methods represent external financial instruments that can be used as a target for transfers. The list will not include disabled or deleted payment methods. **Currently Supported Types:** - `fedwire`: Domestic USD wire transfers - `swift`: International wire transfers - `sepa`: SEPA EUR transfers **Note:** Payment methods are created and verified through your linked CDP entity. Currently, fetching payment methods is only supported for Prime investment vehicles linked to CDP. + + :param page_size: The number of resources to return per page. + :type page_size: int + :param page_token: The token for the next page of resources, if any. + :type page_token: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_payment_methods_serialize( + page_size=page_size, + page_token=page_token, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ListPaymentMethods200Response", + '400': "Error", + '401': "Error", + '500': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def list_payment_methods_without_preload_content( + self, + page_size: Annotated[Optional[StrictInt], Field(description="The number of resources to return per page.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="The token for the next page of resources, if any.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List payment methods + + List payment methods linked to your entity. Payment methods represent external financial instruments that can be used as a target for transfers. The list will not include disabled or deleted payment methods. **Currently Supported Types:** - `fedwire`: Domestic USD wire transfers - `swift`: International wire transfers - `sepa`: SEPA EUR transfers **Note:** Payment methods are created and verified through your linked CDP entity. Currently, fetching payment methods is only supported for Prime investment vehicles linked to CDP. + + :param page_size: The number of resources to return per page. + :type page_size: int + :param page_token: The token for the next page of resources, if any. + :type page_token: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_payment_methods_serialize( + page_size=page_size, + page_token=page_token, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ListPaymentMethods200Response", + '400': "Error", + '401': "Error", + '500': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _list_payment_methods_serialize( + self, + page_size, + page_token, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if page_size is not None: + + _query_params.append(('pageSize', page_size)) + + if page_token is not None: + + _query_params.append(('pageToken', page_token)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v2/payment-methods', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/python/cdp/openapi_client/api/policy_engine_api.py b/python/cdp/openapi_client/api/policy_engine_api.py index a20dd6c2f..d306662be 100644 --- a/python/cdp/openapi_client/api/policy_engine_api.py +++ b/python/cdp/openapi_client/api/policy_engine_api.py @@ -61,7 +61,7 @@ async def create_policy( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Policy: - """Create a policy + """Create policy Create a policy that can be used to govern the behavior of accounts. @@ -138,7 +138,7 @@ async def create_policy_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[Policy]: - """Create a policy + """Create policy Create a policy that can be used to govern the behavior of accounts. @@ -215,7 +215,7 @@ async def create_policy_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Create a policy + """Create policy Create a policy that can be used to govern the behavior of accounts. @@ -368,7 +368,7 @@ async def delete_policy( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Delete a policy + """Delete policy Delete a policy by its ID. This will have the effect of removing the policy from all accounts that are currently using it. @@ -446,7 +446,7 @@ async def delete_policy_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[None]: - """Delete a policy + """Delete policy Delete a policy by its ID. This will have the effect of removing the policy from all accounts that are currently using it. @@ -524,7 +524,7 @@ async def delete_policy_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Delete a policy + """Delete policy Delete a policy by its ID. This will have the effect of removing the policy from all accounts that are currently using it. @@ -664,7 +664,7 @@ async def get_policy_by_id( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Policy: - """Get a policy by ID + """Get policy by ID Get a policy by its ID. @@ -735,7 +735,7 @@ async def get_policy_by_id_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[Policy]: - """Get a policy by ID + """Get policy by ID Get a policy by its ID. @@ -806,7 +806,7 @@ async def get_policy_by_id_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Get a policy by ID + """Get policy by ID Get a policy by its ID. @@ -1245,7 +1245,7 @@ async def update_policy( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Policy: - """Update a policy + """Update policy Updates a policy by its ID. This will have the effect of applying the updated policy to all accounts that are currently using it. @@ -1327,7 +1327,7 @@ async def update_policy_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[Policy]: - """Update a policy + """Update policy Updates a policy by its ID. This will have the effect of applying the updated policy to all accounts that are currently using it. @@ -1409,7 +1409,7 @@ async def update_policy_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Update a policy + """Update policy Updates a policy by its ID. This will have the effect of applying the updated policy to all accounts that are currently using it. diff --git a/python/cdp/openapi_client/api/solana_accounts_api.py b/python/cdp/openapi_client/api/solana_accounts_api.py index 2d67a5fec..5c0a91f5a 100644 --- a/python/cdp/openapi_client/api/solana_accounts_api.py +++ b/python/cdp/openapi_client/api/solana_accounts_api.py @@ -71,7 +71,7 @@ async def create_solana_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SolanaAccount: - """Create a Solana account + """Create Solana account Creates a new Solana account. @@ -154,7 +154,7 @@ async def create_solana_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SolanaAccount]: - """Create a Solana account + """Create Solana account Creates a new Solana account. @@ -237,7 +237,7 @@ async def create_solana_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Create a Solana account + """Create Solana account Creates a new Solana account. @@ -400,7 +400,7 @@ async def export_solana_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ExportSolanaAccount200Response: - """Export an Solana account + """Export Solana account Export an existing Solana account's private key. It is important to store the private key in a secure place after it's exported. @@ -487,7 +487,7 @@ async def export_solana_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[ExportSolanaAccount200Response]: - """Export an Solana account + """Export Solana account Export an existing Solana account's private key. It is important to store the private key in a secure place after it's exported. @@ -574,7 +574,7 @@ async def export_solana_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Export an Solana account + """Export Solana account Export an existing Solana account's private key. It is important to store the private key in a secure place after it's exported. @@ -743,7 +743,7 @@ async def export_solana_account_by_name( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ExportSolanaAccount200Response: - """Export a Solana account by name + """Export Solana account by name Export an existing Solana account's private key by its name. It is important to store the private key in a secure place after it's exported. @@ -830,7 +830,7 @@ async def export_solana_account_by_name_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[ExportSolanaAccount200Response]: - """Export a Solana account by name + """Export Solana account by name Export an existing Solana account's private key by its name. It is important to store the private key in a secure place after it's exported. @@ -917,7 +917,7 @@ async def export_solana_account_by_name_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Export a Solana account by name + """Export Solana account by name Export an existing Solana account's private key by its name. It is important to store the private key in a secure place after it's exported. @@ -1083,7 +1083,7 @@ async def get_solana_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SolanaAccount: - """Get a Solana account by address + """Get Solana account by address Gets a Solana account by its address. @@ -1155,7 +1155,7 @@ async def get_solana_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SolanaAccount]: - """Get a Solana account by address + """Get Solana account by address Gets a Solana account by its address. @@ -1227,7 +1227,7 @@ async def get_solana_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Get a Solana account by address + """Get Solana account by address Gets a Solana account by its address. @@ -1359,7 +1359,7 @@ async def get_solana_account_by_name( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SolanaAccount: - """Get a Solana account by name + """Get Solana account by name Gets a Solana account by its name. @@ -1431,7 +1431,7 @@ async def get_solana_account_by_name_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SolanaAccount]: - """Get a Solana account by name + """Get Solana account by name Gets a Solana account by its name. @@ -1503,7 +1503,7 @@ async def get_solana_account_by_name_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Get a Solana account by name + """Get Solana account by name Gets a Solana account by its name. @@ -1637,7 +1637,7 @@ async def import_solana_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SolanaAccount: - """Import a Solana account + """Import Solana account Import an existing Solana account into the developer's CDP Project. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. @@ -1720,7 +1720,7 @@ async def import_solana_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SolanaAccount]: - """Import a Solana account + """Import Solana account Import an existing Solana account into the developer's CDP Project. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. @@ -1803,7 +1803,7 @@ async def import_solana_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Import a Solana account + """Import Solana account Import an existing Solana account into the developer's CDP Project. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. @@ -1964,7 +1964,7 @@ async def list_solana_accounts( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ListSolanaAccounts200Response: - """List Solana accounts or get account by name + """List Solana accounts Lists the Solana accounts belonging to the developer. The response is paginated, and by default, returns 20 accounts per page. If a name is provided, the response will contain only the account with that name. @@ -2038,7 +2038,7 @@ async def list_solana_accounts_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[ListSolanaAccounts200Response]: - """List Solana accounts or get account by name + """List Solana accounts Lists the Solana accounts belonging to the developer. The response is paginated, and by default, returns 20 accounts per page. If a name is provided, the response will contain only the account with that name. @@ -2112,7 +2112,7 @@ async def list_solana_accounts_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """List Solana accounts or get account by name + """List Solana accounts Lists the Solana accounts belonging to the developer. The response is paginated, and by default, returns 20 accounts per page. If a name is provided, the response will contain only the account with that name. @@ -2254,7 +2254,7 @@ async def send_solana_transaction( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SendSolanaTransactionWithEndUserAccount200Response: - """Send a Solana transaction + """Send Solana transaction Signs and sends a single Solana transaction using multiple Solana accounts. The transaction may contain contain several instructions, each of which may require signatures from different account keys. The transaction should be serialized into a byte array and base64 encoded. The API handles recent blockhash management and fee estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. **Transaction types** The following transaction types are supported: * [Legacy transactions](https://solana.com/developers/guides/advanced/versions#current-transaction-versions) * [Versioned transactions](https://solana.com/developers/guides/advanced/versions) **Instruction Batching** To batch multiple operations, include multiple instructions within a single transaction. All instructions within a transaction are executed atomically - if any instruction fails, the entire transaction fails and is rolled back. **Network Support** The following Solana networks are supported: * `solana` - Solana Mainnet * `solana-devnet` - Solana Devnet The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. @@ -2338,7 +2338,7 @@ async def send_solana_transaction_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SendSolanaTransactionWithEndUserAccount200Response]: - """Send a Solana transaction + """Send Solana transaction Signs and sends a single Solana transaction using multiple Solana accounts. The transaction may contain contain several instructions, each of which may require signatures from different account keys. The transaction should be serialized into a byte array and base64 encoded. The API handles recent blockhash management and fee estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. **Transaction types** The following transaction types are supported: * [Legacy transactions](https://solana.com/developers/guides/advanced/versions#current-transaction-versions) * [Versioned transactions](https://solana.com/developers/guides/advanced/versions) **Instruction Batching** To batch multiple operations, include multiple instructions within a single transaction. All instructions within a transaction are executed atomically - if any instruction fails, the entire transaction fails and is rolled back. **Network Support** The following Solana networks are supported: * `solana` - Solana Mainnet * `solana-devnet` - Solana Devnet The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. @@ -2422,7 +2422,7 @@ async def send_solana_transaction_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Send a Solana transaction + """Send Solana transaction Signs and sends a single Solana transaction using multiple Solana accounts. The transaction may contain contain several instructions, each of which may require signatures from different account keys. The transaction should be serialized into a byte array and base64 encoded. The API handles recent blockhash management and fee estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. **Transaction types** The following transaction types are supported: * [Legacy transactions](https://solana.com/developers/guides/advanced/versions#current-transaction-versions) * [Versioned transactions](https://solana.com/developers/guides/advanced/versions) **Instruction Batching** To batch multiple operations, include multiple instructions within a single transaction. All instructions within a transaction are executed atomically - if any instruction fails, the entire transaction fails and is rolled back. **Network Support** The following Solana networks are supported: * `solana` - Solana Mainnet * `solana-devnet` - Solana Devnet The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. @@ -2586,7 +2586,7 @@ async def sign_solana_message( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SignSolanaMessageWithEndUserAccount200Response: - """Sign a message + """Sign message Signs an arbitrary message with the given Solana account. **WARNING:** Never sign a message that you didn't generate, as it can be an arbitrary transaction. For example, it might send all of your funds to an attacker. @@ -2674,7 +2674,7 @@ async def sign_solana_message_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SignSolanaMessageWithEndUserAccount200Response]: - """Sign a message + """Sign message Signs an arbitrary message with the given Solana account. **WARNING:** Never sign a message that you didn't generate, as it can be an arbitrary transaction. For example, it might send all of your funds to an attacker. @@ -2762,7 +2762,7 @@ async def sign_solana_message_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Sign a message + """Sign message Signs an arbitrary message with the given Solana account. **WARNING:** Never sign a message that you didn't generate, as it can be an arbitrary transaction. For example, it might send all of your funds to an attacker. @@ -2932,7 +2932,7 @@ async def sign_solana_transaction( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SignSolanaTransactionWithEndUserAccount200Response: - """Sign a transaction + """Sign transaction Signs a transaction with the given Solana account. The unsigned transaction should be serialized into a byte array and then encoded as base64. **Transaction types** The following transaction types are supported: * [Legacy transactions](https://solana-labs.github.io/solana-web3.js/classes/Transaction.html) * [Versioned transactions](https://solana-labs.github.io/solana-web3.js/classes/VersionedTransaction.html) The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. @@ -3021,7 +3021,7 @@ async def sign_solana_transaction_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SignSolanaTransactionWithEndUserAccount200Response]: - """Sign a transaction + """Sign transaction Signs a transaction with the given Solana account. The unsigned transaction should be serialized into a byte array and then encoded as base64. **Transaction types** The following transaction types are supported: * [Legacy transactions](https://solana-labs.github.io/solana-web3.js/classes/Transaction.html) * [Versioned transactions](https://solana-labs.github.io/solana-web3.js/classes/VersionedTransaction.html) The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. @@ -3110,7 +3110,7 @@ async def sign_solana_transaction_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Sign a transaction + """Sign transaction Signs a transaction with the given Solana account. The unsigned transaction should be serialized into a byte array and then encoded as base64. **Transaction types** The following transaction types are supported: * [Legacy transactions](https://solana-labs.github.io/solana-web3.js/classes/Transaction.html) * [Versioned transactions](https://solana-labs.github.io/solana-web3.js/classes/VersionedTransaction.html) The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. @@ -3280,7 +3280,7 @@ async def update_solana_account( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SolanaAccount: - """Update a Solana account + """Update Solana account Updates an existing Solana account. Use this to update the account's name or account-level policy. @@ -3362,7 +3362,7 @@ async def update_solana_account_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SolanaAccount]: - """Update a Solana account + """Update Solana account Updates an existing Solana account. Use this to update the account's name or account-level policy. @@ -3444,7 +3444,7 @@ async def update_solana_account_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Update a Solana account + """Update Solana account Updates an existing Solana account. Use this to update the account's name or account-level policy. diff --git a/python/cdp/openapi_client/api/sqlapi_api.py b/python/cdp/openapi_client/api/sqlapi_api.py index c01c69506..2310c748b 100644 --- a/python/cdp/openapi_client/api/sqlapi_api.py +++ b/python/cdp/openapi_client/api/sqlapi_api.py @@ -318,7 +318,7 @@ async def get_sql_schema( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> OnchainDataSchemaResponse: - """Get schemas details + """Get schema details Retrieve the schema information for the available tables in the SQL API's indexed data. This includes table names, column definitions, data types, and indexed fields. @@ -391,7 +391,7 @@ async def get_sql_schema_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[OnchainDataSchemaResponse]: - """Get schemas details + """Get schema details Retrieve the schema information for the available tables in the SQL API's indexed data. This includes table names, column definitions, data types, and indexed fields. @@ -464,7 +464,7 @@ async def get_sql_schema_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Get schemas details + """Get schema details Retrieve the schema information for the available tables in the SQL API's indexed data. This includes table names, column definitions, data types, and indexed fields. diff --git a/python/cdp/openapi_client/api/transfers_api.py b/python/cdp/openapi_client/api/transfers_api.py new file mode 100644 index 000000000..bb99b2edd --- /dev/null +++ b/python/cdp/openapi_client/api/transfers_api.py @@ -0,0 +1,1775 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from datetime import datetime +from pydantic import Field, StrictInt, StrictStr, field_validator +from typing import Optional +from typing_extensions import Annotated +from cdp.openapi_client.models.deposit_travel_rule_request import DepositTravelRuleRequest +from cdp.openapi_client.models.deposit_travel_rule_response import DepositTravelRuleResponse +from cdp.openapi_client.models.list_transfers200_response import ListTransfers200Response +from cdp.openapi_client.models.transfer import Transfer +from cdp.openapi_client.models.transfer_request import TransferRequest +from cdp.openapi_client.models.transfer_status import TransferStatus + +from cdp.openapi_client.api_client import ApiClient, RequestSerialized +from cdp.openapi_client.api_response import ApiResponse +from cdp.openapi_client.rest import RESTResponseType + + +class TransfersApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + async def create_transfer( + self, + x_idempotency_key: Annotated[Optional[Annotated[str, Field(min_length=1, strict=True, max_length=128)]], Field(description="An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. ")] = None, + transfer_request: Optional[TransferRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Transfer: + """Create transfer + + Create a new transfer to move funds from a source to a target. All transfers first transition to `quoted`. If `execute: false`, the transfer stays quoted until you call `/v2/transfers/{transferId}/execute`. If `execute: true`, quoted status emits momentarily before the transfer moves to `processing`, where execution proceeds. Subscribe to the transfers webhook to follow progress in real time instead of polling. + + :param x_idempotency_key: An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + :type x_idempotency_key: str + :param transfer_request: + :type transfer_request: TransferRequest + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_transfer_serialize( + x_idempotency_key=x_idempotency_key, + transfer_request=transfer_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Transfer", + '400': "Error", + '422': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def create_transfer_with_http_info( + self, + x_idempotency_key: Annotated[Optional[Annotated[str, Field(min_length=1, strict=True, max_length=128)]], Field(description="An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. ")] = None, + transfer_request: Optional[TransferRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Transfer]: + """Create transfer + + Create a new transfer to move funds from a source to a target. All transfers first transition to `quoted`. If `execute: false`, the transfer stays quoted until you call `/v2/transfers/{transferId}/execute`. If `execute: true`, quoted status emits momentarily before the transfer moves to `processing`, where execution proceeds. Subscribe to the transfers webhook to follow progress in real time instead of polling. + + :param x_idempotency_key: An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + :type x_idempotency_key: str + :param transfer_request: + :type transfer_request: TransferRequest + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_transfer_serialize( + x_idempotency_key=x_idempotency_key, + transfer_request=transfer_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Transfer", + '400': "Error", + '422': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def create_transfer_without_preload_content( + self, + x_idempotency_key: Annotated[Optional[Annotated[str, Field(min_length=1, strict=True, max_length=128)]], Field(description="An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. ")] = None, + transfer_request: Optional[TransferRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create transfer + + Create a new transfer to move funds from a source to a target. All transfers first transition to `quoted`. If `execute: false`, the transfer stays quoted until you call `/v2/transfers/{transferId}/execute`. If `execute: true`, quoted status emits momentarily before the transfer moves to `processing`, where execution proceeds. Subscribe to the transfers webhook to follow progress in real time instead of polling. + + :param x_idempotency_key: An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + :type x_idempotency_key: str + :param transfer_request: + :type transfer_request: TransferRequest + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_transfer_serialize( + x_idempotency_key=x_idempotency_key, + transfer_request=transfer_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Transfer", + '400': "Error", + '422': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _create_transfer_serialize( + self, + x_idempotency_key, + transfer_request, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + if x_idempotency_key is not None: + _header_params['X-Idempotency-Key'] = x_idempotency_key + # process the form parameters + # process the body parameter + if transfer_request is not None: + _body_params = transfer_request + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/v2/transfers', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + async def execute_fund_transfer( + self, + transfer_id: Annotated[str, Field(strict=True, description="The ID of the transfer.")], + x_idempotency_key: Annotated[Optional[Annotated[str, Field(min_length=1, strict=True, max_length=128)]], Field(description="An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. ")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Transfer: + """Execute transfer + + Executes a transfer which was created using the Create a transfer endpoint. + + :param transfer_id: The ID of the transfer. (required) + :type transfer_id: str + :param x_idempotency_key: An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + :type x_idempotency_key: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._execute_fund_transfer_serialize( + transfer_id=transfer_id, + x_idempotency_key=x_idempotency_key, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Transfer", + '400': "Error", + '401': "Error", + '404': "Error", + '422': "Error", + '429': "Error", + '500': "Error", + '502': "Error", + '503': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def execute_fund_transfer_with_http_info( + self, + transfer_id: Annotated[str, Field(strict=True, description="The ID of the transfer.")], + x_idempotency_key: Annotated[Optional[Annotated[str, Field(min_length=1, strict=True, max_length=128)]], Field(description="An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. ")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Transfer]: + """Execute transfer + + Executes a transfer which was created using the Create a transfer endpoint. + + :param transfer_id: The ID of the transfer. (required) + :type transfer_id: str + :param x_idempotency_key: An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + :type x_idempotency_key: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._execute_fund_transfer_serialize( + transfer_id=transfer_id, + x_idempotency_key=x_idempotency_key, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Transfer", + '400': "Error", + '401': "Error", + '404': "Error", + '422': "Error", + '429': "Error", + '500': "Error", + '502': "Error", + '503': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def execute_fund_transfer_without_preload_content( + self, + transfer_id: Annotated[str, Field(strict=True, description="The ID of the transfer.")], + x_idempotency_key: Annotated[Optional[Annotated[str, Field(min_length=1, strict=True, max_length=128)]], Field(description="An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. ")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Execute transfer + + Executes a transfer which was created using the Create a transfer endpoint. + + :param transfer_id: The ID of the transfer. (required) + :type transfer_id: str + :param x_idempotency_key: An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + :type x_idempotency_key: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._execute_fund_transfer_serialize( + transfer_id=transfer_id, + x_idempotency_key=x_idempotency_key, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Transfer", + '400': "Error", + '401': "Error", + '404': "Error", + '422': "Error", + '429': "Error", + '500': "Error", + '502': "Error", + '503': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _execute_fund_transfer_serialize( + self, + transfer_id, + x_idempotency_key, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if transfer_id is not None: + _path_params['transferId'] = transfer_id + # process the query parameters + # process the header parameters + if x_idempotency_key is not None: + _header_params['X-Idempotency-Key'] = x_idempotency_key + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/v2/transfers/{transferId}/execute', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + async def get_transfer_by_id( + self, + transfer_id: Annotated[str, Field(strict=True, description="The unique identifier of the transfer.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Transfer: + """Get transfer + + Get a transfer by its ID. + + :param transfer_id: The unique identifier of the transfer. (required) + :type transfer_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_transfer_by_id_serialize( + transfer_id=transfer_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Transfer", + '404': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def get_transfer_by_id_with_http_info( + self, + transfer_id: Annotated[str, Field(strict=True, description="The unique identifier of the transfer.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Transfer]: + """Get transfer + + Get a transfer by its ID. + + :param transfer_id: The unique identifier of the transfer. (required) + :type transfer_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_transfer_by_id_serialize( + transfer_id=transfer_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Transfer", + '404': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def get_transfer_by_id_without_preload_content( + self, + transfer_id: Annotated[str, Field(strict=True, description="The unique identifier of the transfer.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get transfer + + Get a transfer by its ID. + + :param transfer_id: The unique identifier of the transfer. (required) + :type transfer_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_transfer_by_id_serialize( + transfer_id=transfer_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Transfer", + '404': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_transfer_by_id_serialize( + self, + transfer_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if transfer_id is not None: + _path_params['transferId'] = transfer_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v2/transfers/{transferId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + async def list_transfers( + self, + status: Annotated[Optional[TransferStatus], Field(description="Filter transfers by status. Useful for building dashboards, monitoring active transfers, or finding transfers needing action.")] = None, + account_id: Annotated[Optional[Annotated[str, Field(strict=True)]], Field(description="Filter transfers by account ID. Returns transfers where the specified account is either the source or target (OR semantics). Cannot be combined with `sourceAccountId` or `targetAccountId`.")] = None, + source_account_id: Annotated[Optional[Annotated[str, Field(strict=True)]], Field(description="Filter transfers by source account ID. Returns only transfers where the specified account is the source. Cannot be combined with `accountId`.")] = None, + target_account_id: Annotated[Optional[Annotated[str, Field(strict=True)]], Field(description="Filter transfers by target account ID. Returns only transfers where the specified account is the target. Cannot be combined with `accountId`.")] = None, + created_after: Annotated[Optional[datetime], Field(description="Filter transfers to those created at or after this datetime (inclusive). ISO 8601 format.")] = None, + created_before: Annotated[Optional[datetime], Field(description="Filter transfers to those created at or before this datetime (inclusive). ISO 8601 format.")] = None, + updated_after: Annotated[Optional[datetime], Field(description="Filter transfers to those updated at or after this datetime (inclusive). ISO 8601 format. Useful for incremental sync — poll for transfers that changed state since your last check.")] = None, + updated_before: Annotated[Optional[datetime], Field(description="Filter transfers to those updated at or before this datetime (inclusive). ISO 8601 format.")] = None, + source_asset: Annotated[Optional[StrictStr], Field(description="Filter transfers by source asset symbol (e.g., `usd`, `usdc`).")] = None, + target_asset: Annotated[Optional[StrictStr], Field(description="Filter transfers by target asset symbol (e.g., `usdc`, `eth`).")] = None, + source_address: Annotated[Optional[Annotated[str, Field(min_length=1, strict=True, max_length=128)]], Field(description="Filter transfers by the on-chain address of the source.")] = None, + target_address: Annotated[Optional[Annotated[str, Field(min_length=1, strict=True, max_length=128)]], Field(description="Filter transfers by the on-chain destination address of the target.")] = None, + target_email: Annotated[Optional[StrictStr], Field(description="Filter transfers by the email address of the target recipient.")] = None, + transfer_id: Annotated[Optional[Annotated[str, Field(strict=True)]], Field(description="Filter to a specific transfer by ID. When provided, returns only the matching transfer and bypasses pagination.")] = None, + page_size: Annotated[Optional[StrictInt], Field(description="The number of resources to return per page.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="The token for the next page of resources, if any.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ListTransfers200Response: + """List transfers + + List transfers for your organization. Use this to view and monitor your transfer activity. **Status Filtering**: Filter by specific status to efficiently manage transfers: * `?status=processing` - Monitor active transfers. * `?status=quoted` - Find transfers awaiting execution. * `?status=failed` - Review failed transfers for troubleshooting. * `?status=completed` - Find completed transfers. **Account Filtering**: Filter by account ID to find transfers involving a specific account: * `?accountId=` - All transfers where the account is either source or target (OR semantics). * `?sourceAccountId=` - Only transfers where the account is the source (outbound). * `?targetAccountId=` - Only transfers where the account is the target (inbound). Providing `accountId` together with `sourceAccountId` or `targetAccountId` is a validation error and returns HTTP 400. **Date Range Filtering**: Filter by creation or last-updated time for reconciliation: * `?createdAfter=2026-01-01T00:00:00Z&createdBefore=2026-01-31T23:59:59Z` - Transfers created within a date range. * `?updatedAfter=2026-01-01T00:00:00Z` - Transfers updated since a given time. Useful for incremental sync. **Asset Filtering**: Filter by source or target asset symbol: * `?sourceAsset=usd` - Transfers funded from a USD account. * `?targetAsset=usdc` - Transfers delivering USDC to the target. **Other Filters**: * `?sourceAddress=0x...` - Transfers from a specific on-chain source address. * `?targetAddress=0x...` - Transfers to a specific on-chain destination address. * `?targetEmail=user@example.com` - Transfers to a specific email recipient. * `?transferId=transfer_...` - Look up a single transfer by ID; bypasses pagination. + + :param status: Filter transfers by status. Useful for building dashboards, monitoring active transfers, or finding transfers needing action. + :type status: TransferStatus + :param account_id: Filter transfers by account ID. Returns transfers where the specified account is either the source or target (OR semantics). Cannot be combined with `sourceAccountId` or `targetAccountId`. + :type account_id: str + :param source_account_id: Filter transfers by source account ID. Returns only transfers where the specified account is the source. Cannot be combined with `accountId`. + :type source_account_id: str + :param target_account_id: Filter transfers by target account ID. Returns only transfers where the specified account is the target. Cannot be combined with `accountId`. + :type target_account_id: str + :param created_after: Filter transfers to those created at or after this datetime (inclusive). ISO 8601 format. + :type created_after: datetime + :param created_before: Filter transfers to those created at or before this datetime (inclusive). ISO 8601 format. + :type created_before: datetime + :param updated_after: Filter transfers to those updated at or after this datetime (inclusive). ISO 8601 format. Useful for incremental sync — poll for transfers that changed state since your last check. + :type updated_after: datetime + :param updated_before: Filter transfers to those updated at or before this datetime (inclusive). ISO 8601 format. + :type updated_before: datetime + :param source_asset: Filter transfers by source asset symbol (e.g., `usd`, `usdc`). + :type source_asset: str + :param target_asset: Filter transfers by target asset symbol (e.g., `usdc`, `eth`). + :type target_asset: str + :param source_address: Filter transfers by the on-chain address of the source. + :type source_address: str + :param target_address: Filter transfers by the on-chain destination address of the target. + :type target_address: str + :param target_email: Filter transfers by the email address of the target recipient. + :type target_email: str + :param transfer_id: Filter to a specific transfer by ID. When provided, returns only the matching transfer and bypasses pagination. + :type transfer_id: str + :param page_size: The number of resources to return per page. + :type page_size: int + :param page_token: The token for the next page of resources, if any. + :type page_token: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_transfers_serialize( + status=status, + account_id=account_id, + source_account_id=source_account_id, + target_account_id=target_account_id, + created_after=created_after, + created_before=created_before, + updated_after=updated_after, + updated_before=updated_before, + source_asset=source_asset, + target_asset=target_asset, + source_address=source_address, + target_address=target_address, + target_email=target_email, + transfer_id=transfer_id, + page_size=page_size, + page_token=page_token, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ListTransfers200Response", + '400': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def list_transfers_with_http_info( + self, + status: Annotated[Optional[TransferStatus], Field(description="Filter transfers by status. Useful for building dashboards, monitoring active transfers, or finding transfers needing action.")] = None, + account_id: Annotated[Optional[Annotated[str, Field(strict=True)]], Field(description="Filter transfers by account ID. Returns transfers where the specified account is either the source or target (OR semantics). Cannot be combined with `sourceAccountId` or `targetAccountId`.")] = None, + source_account_id: Annotated[Optional[Annotated[str, Field(strict=True)]], Field(description="Filter transfers by source account ID. Returns only transfers where the specified account is the source. Cannot be combined with `accountId`.")] = None, + target_account_id: Annotated[Optional[Annotated[str, Field(strict=True)]], Field(description="Filter transfers by target account ID. Returns only transfers where the specified account is the target. Cannot be combined with `accountId`.")] = None, + created_after: Annotated[Optional[datetime], Field(description="Filter transfers to those created at or after this datetime (inclusive). ISO 8601 format.")] = None, + created_before: Annotated[Optional[datetime], Field(description="Filter transfers to those created at or before this datetime (inclusive). ISO 8601 format.")] = None, + updated_after: Annotated[Optional[datetime], Field(description="Filter transfers to those updated at or after this datetime (inclusive). ISO 8601 format. Useful for incremental sync — poll for transfers that changed state since your last check.")] = None, + updated_before: Annotated[Optional[datetime], Field(description="Filter transfers to those updated at or before this datetime (inclusive). ISO 8601 format.")] = None, + source_asset: Annotated[Optional[StrictStr], Field(description="Filter transfers by source asset symbol (e.g., `usd`, `usdc`).")] = None, + target_asset: Annotated[Optional[StrictStr], Field(description="Filter transfers by target asset symbol (e.g., `usdc`, `eth`).")] = None, + source_address: Annotated[Optional[Annotated[str, Field(min_length=1, strict=True, max_length=128)]], Field(description="Filter transfers by the on-chain address of the source.")] = None, + target_address: Annotated[Optional[Annotated[str, Field(min_length=1, strict=True, max_length=128)]], Field(description="Filter transfers by the on-chain destination address of the target.")] = None, + target_email: Annotated[Optional[StrictStr], Field(description="Filter transfers by the email address of the target recipient.")] = None, + transfer_id: Annotated[Optional[Annotated[str, Field(strict=True)]], Field(description="Filter to a specific transfer by ID. When provided, returns only the matching transfer and bypasses pagination.")] = None, + page_size: Annotated[Optional[StrictInt], Field(description="The number of resources to return per page.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="The token for the next page of resources, if any.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ListTransfers200Response]: + """List transfers + + List transfers for your organization. Use this to view and monitor your transfer activity. **Status Filtering**: Filter by specific status to efficiently manage transfers: * `?status=processing` - Monitor active transfers. * `?status=quoted` - Find transfers awaiting execution. * `?status=failed` - Review failed transfers for troubleshooting. * `?status=completed` - Find completed transfers. **Account Filtering**: Filter by account ID to find transfers involving a specific account: * `?accountId=` - All transfers where the account is either source or target (OR semantics). * `?sourceAccountId=` - Only transfers where the account is the source (outbound). * `?targetAccountId=` - Only transfers where the account is the target (inbound). Providing `accountId` together with `sourceAccountId` or `targetAccountId` is a validation error and returns HTTP 400. **Date Range Filtering**: Filter by creation or last-updated time for reconciliation: * `?createdAfter=2026-01-01T00:00:00Z&createdBefore=2026-01-31T23:59:59Z` - Transfers created within a date range. * `?updatedAfter=2026-01-01T00:00:00Z` - Transfers updated since a given time. Useful for incremental sync. **Asset Filtering**: Filter by source or target asset symbol: * `?sourceAsset=usd` - Transfers funded from a USD account. * `?targetAsset=usdc` - Transfers delivering USDC to the target. **Other Filters**: * `?sourceAddress=0x...` - Transfers from a specific on-chain source address. * `?targetAddress=0x...` - Transfers to a specific on-chain destination address. * `?targetEmail=user@example.com` - Transfers to a specific email recipient. * `?transferId=transfer_...` - Look up a single transfer by ID; bypasses pagination. + + :param status: Filter transfers by status. Useful for building dashboards, monitoring active transfers, or finding transfers needing action. + :type status: TransferStatus + :param account_id: Filter transfers by account ID. Returns transfers where the specified account is either the source or target (OR semantics). Cannot be combined with `sourceAccountId` or `targetAccountId`. + :type account_id: str + :param source_account_id: Filter transfers by source account ID. Returns only transfers where the specified account is the source. Cannot be combined with `accountId`. + :type source_account_id: str + :param target_account_id: Filter transfers by target account ID. Returns only transfers where the specified account is the target. Cannot be combined with `accountId`. + :type target_account_id: str + :param created_after: Filter transfers to those created at or after this datetime (inclusive). ISO 8601 format. + :type created_after: datetime + :param created_before: Filter transfers to those created at or before this datetime (inclusive). ISO 8601 format. + :type created_before: datetime + :param updated_after: Filter transfers to those updated at or after this datetime (inclusive). ISO 8601 format. Useful for incremental sync — poll for transfers that changed state since your last check. + :type updated_after: datetime + :param updated_before: Filter transfers to those updated at or before this datetime (inclusive). ISO 8601 format. + :type updated_before: datetime + :param source_asset: Filter transfers by source asset symbol (e.g., `usd`, `usdc`). + :type source_asset: str + :param target_asset: Filter transfers by target asset symbol (e.g., `usdc`, `eth`). + :type target_asset: str + :param source_address: Filter transfers by the on-chain address of the source. + :type source_address: str + :param target_address: Filter transfers by the on-chain destination address of the target. + :type target_address: str + :param target_email: Filter transfers by the email address of the target recipient. + :type target_email: str + :param transfer_id: Filter to a specific transfer by ID. When provided, returns only the matching transfer and bypasses pagination. + :type transfer_id: str + :param page_size: The number of resources to return per page. + :type page_size: int + :param page_token: The token for the next page of resources, if any. + :type page_token: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_transfers_serialize( + status=status, + account_id=account_id, + source_account_id=source_account_id, + target_account_id=target_account_id, + created_after=created_after, + created_before=created_before, + updated_after=updated_after, + updated_before=updated_before, + source_asset=source_asset, + target_asset=target_asset, + source_address=source_address, + target_address=target_address, + target_email=target_email, + transfer_id=transfer_id, + page_size=page_size, + page_token=page_token, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ListTransfers200Response", + '400': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def list_transfers_without_preload_content( + self, + status: Annotated[Optional[TransferStatus], Field(description="Filter transfers by status. Useful for building dashboards, monitoring active transfers, or finding transfers needing action.")] = None, + account_id: Annotated[Optional[Annotated[str, Field(strict=True)]], Field(description="Filter transfers by account ID. Returns transfers where the specified account is either the source or target (OR semantics). Cannot be combined with `sourceAccountId` or `targetAccountId`.")] = None, + source_account_id: Annotated[Optional[Annotated[str, Field(strict=True)]], Field(description="Filter transfers by source account ID. Returns only transfers where the specified account is the source. Cannot be combined with `accountId`.")] = None, + target_account_id: Annotated[Optional[Annotated[str, Field(strict=True)]], Field(description="Filter transfers by target account ID. Returns only transfers where the specified account is the target. Cannot be combined with `accountId`.")] = None, + created_after: Annotated[Optional[datetime], Field(description="Filter transfers to those created at or after this datetime (inclusive). ISO 8601 format.")] = None, + created_before: Annotated[Optional[datetime], Field(description="Filter transfers to those created at or before this datetime (inclusive). ISO 8601 format.")] = None, + updated_after: Annotated[Optional[datetime], Field(description="Filter transfers to those updated at or after this datetime (inclusive). ISO 8601 format. Useful for incremental sync — poll for transfers that changed state since your last check.")] = None, + updated_before: Annotated[Optional[datetime], Field(description="Filter transfers to those updated at or before this datetime (inclusive). ISO 8601 format.")] = None, + source_asset: Annotated[Optional[StrictStr], Field(description="Filter transfers by source asset symbol (e.g., `usd`, `usdc`).")] = None, + target_asset: Annotated[Optional[StrictStr], Field(description="Filter transfers by target asset symbol (e.g., `usdc`, `eth`).")] = None, + source_address: Annotated[Optional[Annotated[str, Field(min_length=1, strict=True, max_length=128)]], Field(description="Filter transfers by the on-chain address of the source.")] = None, + target_address: Annotated[Optional[Annotated[str, Field(min_length=1, strict=True, max_length=128)]], Field(description="Filter transfers by the on-chain destination address of the target.")] = None, + target_email: Annotated[Optional[StrictStr], Field(description="Filter transfers by the email address of the target recipient.")] = None, + transfer_id: Annotated[Optional[Annotated[str, Field(strict=True)]], Field(description="Filter to a specific transfer by ID. When provided, returns only the matching transfer and bypasses pagination.")] = None, + page_size: Annotated[Optional[StrictInt], Field(description="The number of resources to return per page.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="The token for the next page of resources, if any.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List transfers + + List transfers for your organization. Use this to view and monitor your transfer activity. **Status Filtering**: Filter by specific status to efficiently manage transfers: * `?status=processing` - Monitor active transfers. * `?status=quoted` - Find transfers awaiting execution. * `?status=failed` - Review failed transfers for troubleshooting. * `?status=completed` - Find completed transfers. **Account Filtering**: Filter by account ID to find transfers involving a specific account: * `?accountId=` - All transfers where the account is either source or target (OR semantics). * `?sourceAccountId=` - Only transfers where the account is the source (outbound). * `?targetAccountId=` - Only transfers where the account is the target (inbound). Providing `accountId` together with `sourceAccountId` or `targetAccountId` is a validation error and returns HTTP 400. **Date Range Filtering**: Filter by creation or last-updated time for reconciliation: * `?createdAfter=2026-01-01T00:00:00Z&createdBefore=2026-01-31T23:59:59Z` - Transfers created within a date range. * `?updatedAfter=2026-01-01T00:00:00Z` - Transfers updated since a given time. Useful for incremental sync. **Asset Filtering**: Filter by source or target asset symbol: * `?sourceAsset=usd` - Transfers funded from a USD account. * `?targetAsset=usdc` - Transfers delivering USDC to the target. **Other Filters**: * `?sourceAddress=0x...` - Transfers from a specific on-chain source address. * `?targetAddress=0x...` - Transfers to a specific on-chain destination address. * `?targetEmail=user@example.com` - Transfers to a specific email recipient. * `?transferId=transfer_...` - Look up a single transfer by ID; bypasses pagination. + + :param status: Filter transfers by status. Useful for building dashboards, monitoring active transfers, or finding transfers needing action. + :type status: TransferStatus + :param account_id: Filter transfers by account ID. Returns transfers where the specified account is either the source or target (OR semantics). Cannot be combined with `sourceAccountId` or `targetAccountId`. + :type account_id: str + :param source_account_id: Filter transfers by source account ID. Returns only transfers where the specified account is the source. Cannot be combined with `accountId`. + :type source_account_id: str + :param target_account_id: Filter transfers by target account ID. Returns only transfers where the specified account is the target. Cannot be combined with `accountId`. + :type target_account_id: str + :param created_after: Filter transfers to those created at or after this datetime (inclusive). ISO 8601 format. + :type created_after: datetime + :param created_before: Filter transfers to those created at or before this datetime (inclusive). ISO 8601 format. + :type created_before: datetime + :param updated_after: Filter transfers to those updated at or after this datetime (inclusive). ISO 8601 format. Useful for incremental sync — poll for transfers that changed state since your last check. + :type updated_after: datetime + :param updated_before: Filter transfers to those updated at or before this datetime (inclusive). ISO 8601 format. + :type updated_before: datetime + :param source_asset: Filter transfers by source asset symbol (e.g., `usd`, `usdc`). + :type source_asset: str + :param target_asset: Filter transfers by target asset symbol (e.g., `usdc`, `eth`). + :type target_asset: str + :param source_address: Filter transfers by the on-chain address of the source. + :type source_address: str + :param target_address: Filter transfers by the on-chain destination address of the target. + :type target_address: str + :param target_email: Filter transfers by the email address of the target recipient. + :type target_email: str + :param transfer_id: Filter to a specific transfer by ID. When provided, returns only the matching transfer and bypasses pagination. + :type transfer_id: str + :param page_size: The number of resources to return per page. + :type page_size: int + :param page_token: The token for the next page of resources, if any. + :type page_token: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_transfers_serialize( + status=status, + account_id=account_id, + source_account_id=source_account_id, + target_account_id=target_account_id, + created_after=created_after, + created_before=created_before, + updated_after=updated_after, + updated_before=updated_before, + source_asset=source_asset, + target_asset=target_asset, + source_address=source_address, + target_address=target_address, + target_email=target_email, + transfer_id=transfer_id, + page_size=page_size, + page_token=page_token, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ListTransfers200Response", + '400': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _list_transfers_serialize( + self, + status, + account_id, + source_account_id, + target_account_id, + created_after, + created_before, + updated_after, + updated_before, + source_asset, + target_asset, + source_address, + target_address, + target_email, + transfer_id, + page_size, + page_token, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if status is not None: + + _query_params.append(('status', status.value)) + + if account_id is not None: + + _query_params.append(('accountId', account_id)) + + if source_account_id is not None: + + _query_params.append(('sourceAccountId', source_account_id)) + + if target_account_id is not None: + + _query_params.append(('targetAccountId', target_account_id)) + + if created_after is not None: + if isinstance(created_after, datetime): + _query_params.append( + ( + 'createdAfter', + created_after.strftime( + self.api_client.configuration.datetime_format + ) + ) + ) + else: + _query_params.append(('createdAfter', created_after)) + + if created_before is not None: + if isinstance(created_before, datetime): + _query_params.append( + ( + 'createdBefore', + created_before.strftime( + self.api_client.configuration.datetime_format + ) + ) + ) + else: + _query_params.append(('createdBefore', created_before)) + + if updated_after is not None: + if isinstance(updated_after, datetime): + _query_params.append( + ( + 'updatedAfter', + updated_after.strftime( + self.api_client.configuration.datetime_format + ) + ) + ) + else: + _query_params.append(('updatedAfter', updated_after)) + + if updated_before is not None: + if isinstance(updated_before, datetime): + _query_params.append( + ( + 'updatedBefore', + updated_before.strftime( + self.api_client.configuration.datetime_format + ) + ) + ) + else: + _query_params.append(('updatedBefore', updated_before)) + + if source_asset is not None: + + _query_params.append(('sourceAsset', source_asset)) + + if target_asset is not None: + + _query_params.append(('targetAsset', target_asset)) + + if source_address is not None: + + _query_params.append(('sourceAddress', source_address)) + + if target_address is not None: + + _query_params.append(('targetAddress', target_address)) + + if target_email is not None: + + _query_params.append(('targetEmail', target_email)) + + if transfer_id is not None: + + _query_params.append(('transferId', transfer_id)) + + if page_size is not None: + + _query_params.append(('pageSize', page_size)) + + if page_token is not None: + + _query_params.append(('pageToken', page_token)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v2/transfers', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + async def submit_deposit_travel_rule( + self, + transfer_id: Annotated[str, Field(strict=True, description="The unique identifier of the transfer.")], + x_idempotency_key: Annotated[Optional[Annotated[str, Field(min_length=1, strict=True, max_length=128)]], Field(description="An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. ")] = None, + deposit_travel_rule_request: Optional[DepositTravelRuleRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> DepositTravelRuleResponse: + """Submit deposit travel rule information + + Submit travel rule information for a deposit transfer held pending compliance review. Required fields vary by jurisdiction and may include originator name, address, date of birth, personal ID, and VASP information. If the submitted information satisfies all jurisdictional requirements, `status` will be `completed` and the transfer will proceed. Otherwise, `status` will be `incomplete` and `missingFields` will indicate which fields still need to be provided. + + :param transfer_id: The unique identifier of the transfer. (required) + :type transfer_id: str + :param x_idempotency_key: An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + :type x_idempotency_key: str + :param deposit_travel_rule_request: + :type deposit_travel_rule_request: DepositTravelRuleRequest + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._submit_deposit_travel_rule_serialize( + transfer_id=transfer_id, + x_idempotency_key=x_idempotency_key, + deposit_travel_rule_request=deposit_travel_rule_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DepositTravelRuleResponse", + '400': "Error", + '404': "Error", + '422': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def submit_deposit_travel_rule_with_http_info( + self, + transfer_id: Annotated[str, Field(strict=True, description="The unique identifier of the transfer.")], + x_idempotency_key: Annotated[Optional[Annotated[str, Field(min_length=1, strict=True, max_length=128)]], Field(description="An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. ")] = None, + deposit_travel_rule_request: Optional[DepositTravelRuleRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[DepositTravelRuleResponse]: + """Submit deposit travel rule information + + Submit travel rule information for a deposit transfer held pending compliance review. Required fields vary by jurisdiction and may include originator name, address, date of birth, personal ID, and VASP information. If the submitted information satisfies all jurisdictional requirements, `status` will be `completed` and the transfer will proceed. Otherwise, `status` will be `incomplete` and `missingFields` will indicate which fields still need to be provided. + + :param transfer_id: The unique identifier of the transfer. (required) + :type transfer_id: str + :param x_idempotency_key: An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + :type x_idempotency_key: str + :param deposit_travel_rule_request: + :type deposit_travel_rule_request: DepositTravelRuleRequest + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._submit_deposit_travel_rule_serialize( + transfer_id=transfer_id, + x_idempotency_key=x_idempotency_key, + deposit_travel_rule_request=deposit_travel_rule_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DepositTravelRuleResponse", + '400': "Error", + '404': "Error", + '422': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def submit_deposit_travel_rule_without_preload_content( + self, + transfer_id: Annotated[str, Field(strict=True, description="The unique identifier of the transfer.")], + x_idempotency_key: Annotated[Optional[Annotated[str, Field(min_length=1, strict=True, max_length=128)]], Field(description="An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. ")] = None, + deposit_travel_rule_request: Optional[DepositTravelRuleRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Submit deposit travel rule information + + Submit travel rule information for a deposit transfer held pending compliance review. Required fields vary by jurisdiction and may include originator name, address, date of birth, personal ID, and VASP information. If the submitted information satisfies all jurisdictional requirements, `status` will be `completed` and the transfer will proceed. Otherwise, `status` will be `incomplete` and `missingFields` will indicate which fields still need to be provided. + + :param transfer_id: The unique identifier of the transfer. (required) + :type transfer_id: str + :param x_idempotency_key: An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + :type x_idempotency_key: str + :param deposit_travel_rule_request: + :type deposit_travel_rule_request: DepositTravelRuleRequest + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._submit_deposit_travel_rule_serialize( + transfer_id=transfer_id, + x_idempotency_key=x_idempotency_key, + deposit_travel_rule_request=deposit_travel_rule_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DepositTravelRuleResponse", + '400': "Error", + '404': "Error", + '422': "Error", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _submit_deposit_travel_rule_serialize( + self, + transfer_id, + x_idempotency_key, + deposit_travel_rule_request, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if transfer_id is not None: + _path_params['transferId'] = transfer_id + # process the query parameters + # process the header parameters + if x_idempotency_key is not None: + _header_params['X-Idempotency-Key'] = x_idempotency_key + # process the form parameters + # process the body parameter + if deposit_travel_rule_request is not None: + _body_params = deposit_travel_rule_request + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/v2/transfers/{transferId}/travel-rule', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/python/cdp/openapi_client/api/webhooks_api.py b/python/cdp/openapi_client/api/webhooks_api.py index badfe7a05..eb8416c0d 100644 --- a/python/cdp/openapi_client/api/webhooks_api.py +++ b/python/cdp/openapi_client/api/webhooks_api.py @@ -621,7 +621,7 @@ async def get_webhook_subscription( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> WebhookSubscriptionResponse: - """Get webhook subscription details + """Get webhook subscription Retrieve detailed information about a specific webhook subscription including configuration, status, creation timestamp, and webhook signature secret. ### Response Includes - Subscription configuration and filters - Target URL and custom headers - Webhook signature secret for verification - Creation timestamp and status @@ -692,7 +692,7 @@ async def get_webhook_subscription_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[WebhookSubscriptionResponse]: - """Get webhook subscription details + """Get webhook subscription Retrieve detailed information about a specific webhook subscription including configuration, status, creation timestamp, and webhook signature secret. ### Response Includes - Subscription configuration and filters - Target URL and custom headers - Webhook signature secret for verification - Creation timestamp and status @@ -763,7 +763,7 @@ async def get_webhook_subscription_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Get webhook subscription details + """Get webhook subscription Retrieve detailed information about a specific webhook subscription including configuration, status, creation timestamp, and webhook signature secret. ### Response Includes - Subscription configuration and filters - Target URL and custom headers - Webhook signature secret for verification - Creation timestamp and status diff --git a/python/cdp/openapi_client/api/x402_facilitator_api.py b/python/cdp/openapi_client/api/x402_facilitator_api.py index 8423b1910..3088fe5c7 100644 --- a/python/cdp/openapi_client/api/x402_facilitator_api.py +++ b/python/cdp/openapi_client/api/x402_facilitator_api.py @@ -379,7 +379,7 @@ async def list_x402_discovery_resources( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> X402DiscoveryResourcesResponse: - """List discovered x402 resources + """List x402 resources Lists all active discovered x402 resources. This endpoint returns resources that have been discovered and cached by the x402 facilitator, including their payment requirements and metadata. The response is paginated, and by default, returns 100 items per page. @@ -458,7 +458,7 @@ async def list_x402_discovery_resources_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[X402DiscoveryResourcesResponse]: - """List discovered x402 resources + """List x402 resources Lists all active discovered x402 resources. This endpoint returns resources that have been discovered and cached by the x402 facilitator, including their payment requirements and metadata. The response is paginated, and by default, returns 100 items per page. @@ -537,7 +537,7 @@ async def list_x402_discovery_resources_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """List discovered x402 resources + """List x402 resources Lists all active discovered x402 resources. This endpoint returns resources that have been discovered and cached by the x402 facilitator, including their payment requirements and metadata. The response is paginated, and by default, returns 100 items per page. @@ -1378,7 +1378,7 @@ async def settle_x402_payment( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> InlineObject1: - """Settle a payment + """Settle payment Settle an x402 protocol payment with a specific scheme and network. @@ -1450,7 +1450,7 @@ async def settle_x402_payment_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[InlineObject1]: - """Settle a payment + """Settle payment Settle an x402 protocol payment with a specific scheme and network. @@ -1522,7 +1522,7 @@ async def settle_x402_payment_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Settle a payment + """Settle payment Settle an x402 protocol payment with a specific scheme and network. @@ -1922,7 +1922,7 @@ async def verify_x402_payment( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> InlineObject: - """Verify a payment + """Verify payment Verify an x402 protocol payment with a specific scheme and network. @@ -1993,7 +1993,7 @@ async def verify_x402_payment_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[InlineObject]: - """Verify a payment + """Verify payment Verify an x402 protocol payment with a specific scheme and network. @@ -2064,7 +2064,7 @@ async def verify_x402_payment_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Verify a payment + """Verify payment Verify an x402 protocol payment with a specific scheme and network. diff --git a/python/cdp/openapi_client/models/__init__.py b/python/cdp/openapi_client/models/__init__.py index d7a969d0c..1210297f4 100644 --- a/python/cdp/openapi_client/models/__init__.py +++ b/python/cdp/openapi_client/models/__init__.py @@ -20,18 +20,30 @@ from cdp.openapi_client.models.abi_input import AbiInput from cdp.openapi_client.models.abi_parameter import AbiParameter from cdp.openapi_client.models.abi_state_mutability import AbiStateMutability +from cdp.openapi_client.models.account import Account from cdp.openapi_client.models.account_token_addresses_response import AccountTokenAddressesResponse +from cdp.openapi_client.models.account_type import AccountType from cdp.openapi_client.models.add_end_user_evm_account201_response import AddEndUserEvmAccount201Response from cdp.openapi_client.models.add_end_user_evm_smart_account201_response import AddEndUserEvmSmartAccount201Response from cdp.openapi_client.models.add_end_user_evm_smart_account_request import AddEndUserEvmSmartAccountRequest from cdp.openapi_client.models.add_end_user_solana_account201_response import AddEndUserSolanaAccount201Response +from cdp.openapi_client.models.amount_detail import AmountDetail +from cdp.openapi_client.models.asset_type import AssetType from cdp.openapi_client.models.authentication_method import AuthenticationMethod +from cdp.openapi_client.models.balance import Balance +from cdp.openapi_client.models.balances import Balances +from cdp.openapi_client.models.balances_asset import BalancesAsset from cdp.openapi_client.models.common_swap_response import CommonSwapResponse from cdp.openapi_client.models.common_swap_response_fees import CommonSwapResponseFees from cdp.openapi_client.models.common_swap_response_issues import CommonSwapResponseIssues from cdp.openapi_client.models.common_swap_response_issues_allowance import CommonSwapResponseIssuesAllowance from cdp.openapi_client.models.common_swap_response_issues_balance import CommonSwapResponseIssuesBalance +from cdp.openapi_client.models.create_account_request import CreateAccountRequest +from cdp.openapi_client.models.create_crypto_deposit_destination_request import CreateCryptoDepositDestinationRequest from cdp.openapi_client.models.create_delegation_for_end_user_account_request import CreateDelegationForEndUserAccountRequest +from cdp.openapi_client.models.create_deposit_destination_crypto import CreateDepositDestinationCrypto +from cdp.openapi_client.models.create_deposit_destination_request import CreateDepositDestinationRequest +from cdp.openapi_client.models.create_deposit_destination_request_base import CreateDepositDestinationRequestBase from cdp.openapi_client.models.create_end_user_evm_swap_rule import CreateEndUserEvmSwapRule from cdp.openapi_client.models.create_end_user_request import CreateEndUserRequest from cdp.openapi_client.models.create_end_user_request_evm_account import CreateEndUserRequestEvmAccount @@ -53,11 +65,26 @@ from cdp.openapi_client.models.create_swap_quote_response_all_of_permit2 import CreateSwapQuoteResponseAllOfPermit2 from cdp.openapi_client.models.create_swap_quote_response_all_of_transaction import CreateSwapQuoteResponseAllOfTransaction from cdp.openapi_client.models.create_swap_quote_response_wrapper import CreateSwapQuoteResponseWrapper +from cdp.openapi_client.models.create_transfer_source import CreateTransferSource +from cdp.openapi_client.models.crypto_deposit_destination import CryptoDepositDestination from cdp.openapi_client.models.date_of_birth import DateOfBirth +from cdp.openapi_client.models.deposit_destination import DepositDestination +from cdp.openapi_client.models.deposit_destination_crypto import DepositDestinationCrypto +from cdp.openapi_client.models.deposit_destination_reference import DepositDestinationReference +from cdp.openapi_client.models.deposit_destination_status import DepositDestinationStatus +from cdp.openapi_client.models.deposit_destination_target import DepositDestinationTarget +from cdp.openapi_client.models.deposit_destination_target_account import DepositDestinationTargetAccount +from cdp.openapi_client.models.deposit_travel_rule_beneficiary import DepositTravelRuleBeneficiary +from cdp.openapi_client.models.deposit_travel_rule_originator import DepositTravelRuleOriginator +from cdp.openapi_client.models.deposit_travel_rule_request import DepositTravelRuleRequest +from cdp.openapi_client.models.deposit_travel_rule_response import DepositTravelRuleResponse +from cdp.openapi_client.models.deposit_travel_rule_vasp import DepositTravelRuleVasp from cdp.openapi_client.models.developer_jwt_authentication import DeveloperJWTAuthentication from cdp.openapi_client.models.eip712_domain import EIP712Domain from cdp.openapi_client.models.eip712_message import EIP712Message +from cdp.openapi_client.models.email_address import EmailAddress from cdp.openapi_client.models.email_authentication import EmailAuthentication +from cdp.openapi_client.models.email_instrument import EmailInstrument from cdp.openapi_client.models.end_user import EndUser from cdp.openapi_client.models.end_user_evm_account import EndUserEvmAccount from cdp.openapi_client.models.end_user_evm_smart_account import EndUserEvmSmartAccount @@ -88,6 +115,8 @@ from cdp.openapi_client.models.export_evm_account200_response import ExportEvmAccount200Response from cdp.openapi_client.models.export_evm_account_request import ExportEvmAccountRequest from cdp.openapi_client.models.export_solana_account200_response import ExportSolanaAccount200Response +from cdp.openapi_client.models.fedwire_details import FedwireDetails +from cdp.openapi_client.models.fedwire_payment_method import FedwirePaymentMethod from cdp.openapi_client.models.get_delegation_for_end_user200_response import GetDelegationForEndUser200Response from cdp.openapi_client.models.get_onramp_order_by_id200_response import GetOnrampOrderById200Response from cdp.openapi_client.models.get_onramp_user_limits200_response import GetOnrampUserLimits200Response @@ -107,25 +136,32 @@ from cdp.openapi_client.models.inline_object2 import InlineObject2 from cdp.openapi_client.models.known_abi_type import KnownAbiType from cdp.openapi_client.models.known_idl_type import KnownIdlType +from cdp.openapi_client.models.list_balances200_response import ListBalances200Response +from cdp.openapi_client.models.list_deposit_destinations200_response import ListDepositDestinations200Response from cdp.openapi_client.models.list_end_users200_response import ListEndUsers200Response from cdp.openapi_client.models.list_evm_accounts200_response import ListEvmAccounts200Response from cdp.openapi_client.models.list_evm_smart_accounts200_response import ListEvmSmartAccounts200Response from cdp.openapi_client.models.list_evm_token_balances200_response import ListEvmTokenBalances200Response from cdp.openapi_client.models.list_evm_token_balances_network import ListEvmTokenBalancesNetwork +from cdp.openapi_client.models.list_foundation_accounts200_response import ListFoundationAccounts200Response +from cdp.openapi_client.models.list_payment_methods200_response import ListPaymentMethods200Response from cdp.openapi_client.models.list_policies200_response import ListPolicies200Response from cdp.openapi_client.models.list_response import ListResponse from cdp.openapi_client.models.list_solana_accounts200_response import ListSolanaAccounts200Response from cdp.openapi_client.models.list_solana_token_balances200_response import ListSolanaTokenBalances200Response from cdp.openapi_client.models.list_solana_token_balances_network import ListSolanaTokenBalancesNetwork from cdp.openapi_client.models.list_spend_permissions200_response import ListSpendPermissions200Response +from cdp.openapi_client.models.list_transfers200_response import ListTransfers200Response from cdp.openapi_client.models.lookup_end_user200_response import LookupEndUser200Response from cdp.openapi_client.models.mfa_methods import MFAMethods from cdp.openapi_client.models.mfa_methods_sms import MFAMethodsSms from cdp.openapi_client.models.mfa_methods_totp import MFAMethodsTotp from cdp.openapi_client.models.mint_address_criterion import MintAddressCriterion from cdp.openapi_client.models.net_usd_change_criterion import NetUSDChangeCriterion +from cdp.openapi_client.models.network import Network from cdp.openapi_client.models.o_auth2_authentication import OAuth2Authentication from cdp.openapi_client.models.o_auth2_provider_type import OAuth2ProviderType +from cdp.openapi_client.models.onchain_address import OnchainAddress from cdp.openapi_client.models.onchain_data_column_schema import OnchainDataColumnSchema from cdp.openapi_client.models.onchain_data_query import OnchainDataQuery from cdp.openapi_client.models.onchain_data_result import OnchainDataResult @@ -148,6 +184,11 @@ from cdp.openapi_client.models.onramp_session import OnrampSession from cdp.openapi_client.models.onramp_user_id_type import OnrampUserIdType from cdp.openapi_client.models.onramp_user_limit import OnrampUserLimit +from cdp.openapi_client.models.originating_bank_account_us import OriginatingBankAccountUS +from cdp.openapi_client.models.payment_method import PaymentMethod +from cdp.openapi_client.models.payment_method_base import PaymentMethodBase +from cdp.openapi_client.models.payment_methods_payment_method import PaymentMethodsPaymentMethod +from cdp.openapi_client.models.physical_address import PhysicalAddress from cdp.openapi_client.models.policy import Policy from cdp.openapi_client.models.prepare_and_send_user_operation_request import PrepareAndSendUserOperationRequest from cdp.openapi_client.models.prepare_user_operation_request import PrepareUserOperationRequest @@ -183,6 +224,8 @@ from cdp.openapi_client.models.send_user_operation_request import SendUserOperationRequest from cdp.openapi_client.models.send_user_operation_rule import SendUserOperationRule from cdp.openapi_client.models.send_user_operation_with_end_user_account_request import SendUserOperationWithEndUserAccountRequest +from cdp.openapi_client.models.sepa_details import SepaDetails +from cdp.openapi_client.models.sepa_payment_method import SepaPaymentMethod from cdp.openapi_client.models.sign_end_user_evm_hash_rule import SignEndUserEvmHashRule from cdp.openapi_client.models.sign_end_user_evm_message_rule import SignEndUserEvmMessageRule from cdp.openapi_client.models.sign_end_user_evm_transaction_rule import SignEndUserEvmTransactionRule @@ -243,11 +286,31 @@ from cdp.openapi_client.models.spl_address_criterion import SplAddressCriterion from cdp.openapi_client.models.spl_value_criterion import SplValueCriterion from cdp.openapi_client.models.swap_unavailable_response import SwapUnavailableResponse +from cdp.openapi_client.models.swift_details import SwiftDetails +from cdp.openapi_client.models.swift_payment_method import SwiftPaymentMethod from cdp.openapi_client.models.telegram_authentication import TelegramAuthentication from cdp.openapi_client.models.token import Token from cdp.openapi_client.models.token_amount import TokenAmount from cdp.openapi_client.models.token_balance import TokenBalance from cdp.openapi_client.models.token_fee import TokenFee +from cdp.openapi_client.models.transfer import Transfer +from cdp.openapi_client.models.transfer_details import TransferDetails +from cdp.openapi_client.models.transfer_details_onchain_transactions_inner import TransferDetailsOnchainTransactionsInner +from cdp.openapi_client.models.transfer_details_travel_rule import TransferDetailsTravelRule +from cdp.openapi_client.models.transfer_estimate import TransferEstimate +from cdp.openapi_client.models.transfer_exchange_rate import TransferExchangeRate +from cdp.openapi_client.models.transfer_fee import TransferFee +from cdp.openapi_client.models.transfer_request import TransferRequest +from cdp.openapi_client.models.transfer_source import TransferSource +from cdp.openapi_client.models.transfer_status import TransferStatus +from cdp.openapi_client.models.transfer_target import TransferTarget +from cdp.openapi_client.models.transfers_account import TransfersAccount +from cdp.openapi_client.models.travel_rule import TravelRule +from cdp.openapi_client.models.travel_rule_beneficiary import TravelRuleBeneficiary +from cdp.openapi_client.models.travel_rule_originator import TravelRuleOriginator +from cdp.openapi_client.models.travel_rule_originator_all_of_virtual_asset_service_provider import TravelRuleOriginatorAllOfVirtualAssetServiceProvider +from cdp.openapi_client.models.travel_rule_party import TravelRuleParty +from cdp.openapi_client.models.travel_rule_status import TravelRuleStatus from cdp.openapi_client.models.update_evm_account_request import UpdateEvmAccountRequest from cdp.openapi_client.models.update_evm_smart_account_request import UpdateEvmSmartAccountRequest from cdp.openapi_client.models.update_policy_request import UpdatePolicyRequest diff --git a/python/cdp/openapi_client/models/account.py b/python/cdp/openapi_client/models/account.py new file mode 100644 index 000000000..6c0677525 --- /dev/null +++ b/python/cdp/openapi_client/models/account.py @@ -0,0 +1,125 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, field_validator +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated +from cdp.openapi_client.models.account_type import AccountType +from typing import Optional, Set +from typing_extensions import Self + +class Account(BaseModel): + """ + Account + """ # noqa: E501 + account_id: Annotated[str, Field(strict=True)] = Field(description="The ID of the Account, which is a UUID prefixed by the string `account_`.", alias="accountId") + type: AccountType + owner: Annotated[str, Field(strict=True)] = Field(description="The Owner ID of the Account. Owner IDs are UUIDs prefixed with the Owner Type as follows: * **Entity**: `entity_` - If the Owner is your Entity, e.g. `entity_af2937b0-9846-4fe7-bfe9-ccc22d935114`. Support for Customer-owned accounts (`customer_` prefix) is in development.") + name: Optional[Annotated[str, Field(strict=True, max_length=64)]] = Field(default=None, description="An optional name for the account. Must be 1-64 characters and can only contain alphanumeric characters, hyphens, and spaces.") + created_at: datetime = Field(description="The timestamp when the account was created.", alias="createdAt") + updated_at: datetime = Field(description="The timestamp when the account was last updated.", alias="updatedAt") + __properties: ClassVar[List[str]] = ["accountId", "type", "owner", "name", "createdAt", "updatedAt"] + + @field_validator('account_id') + def account_id_validate_regular_expression(cls, value): + """Validates the regular expression""" + if not re.match(r"^account_[a-f0-9\-]{36}$", value): + raise ValueError(r"must validate the regular expression /^account_[a-f0-9\-]{36}$/") + return value + + @field_validator('owner') + def owner_validate_regular_expression(cls, value): + """Validates the regular expression""" + if not re.match(r"^(entity|customer)_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", value): + raise ValueError(r"must validate the regular expression /^(entity|customer)_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/") + return value + + @field_validator('name') + def name_validate_regular_expression(cls, value): + """Validates the regular expression""" + if value is None: + return value + + if not re.match(r"^[a-zA-Z0-9 -]{1,64}$", value): + raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9 -]{1,64}$/") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Account from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Account from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "accountId": obj.get("accountId"), + "type": obj.get("type"), + "owner": obj.get("owner"), + "name": obj.get("name"), + "createdAt": obj.get("createdAt"), + "updatedAt": obj.get("updatedAt") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/account_type.py b/python/cdp/openapi_client/models/account_type.py new file mode 100644 index 000000000..919bb997d --- /dev/null +++ b/python/cdp/openapi_client/models/account_type.py @@ -0,0 +1,39 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class AccountType(str, Enum): + """ + The type of the Account. + """ + + """ + allowed enum values + """ + PRIME = 'prime' + BUSINESS = 'business' + CDP = 'cdp' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of AccountType from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/python/cdp/openapi_client/models/amount_detail.py b/python/cdp/openapi_client/models/amount_detail.py new file mode 100644 index 000000000..9f279b045 --- /dev/null +++ b/python/cdp/openapi_client/models/amount_detail.py @@ -0,0 +1,90 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class AmountDetail(BaseModel): + """ + Available and total amounts for a specific currency. + """ # noqa: E501 + available: StrictStr = Field(description="The amount that is currently available to be used.") + total: StrictStr = Field(description="The total amount, including the amount that is currently on hold.") + __properties: ClassVar[List[str]] = ["available", "total"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of AmountDetail from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of AmountDetail from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "available": obj.get("available"), + "total": obj.get("total") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/asset_type.py b/python/cdp/openapi_client/models/asset_type.py new file mode 100644 index 000000000..c3daff096 --- /dev/null +++ b/python/cdp/openapi_client/models/asset_type.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class AssetType(str, Enum): + """ + The type of the asset. + """ + + """ + allowed enum values + """ + FIAT = 'fiat' + CRYPTO = 'crypto' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of AssetType from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/python/cdp/openapi_client/models/balance.py b/python/cdp/openapi_client/models/balance.py new file mode 100644 index 000000000..492601b42 --- /dev/null +++ b/python/cdp/openapi_client/models/balance.py @@ -0,0 +1,107 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List +from cdp.openapi_client.models.amount_detail import AmountDetail +from cdp.openapi_client.models.balances_asset import BalancesAsset +from typing import Optional, Set +from typing_extensions import Self + +class Balance(BaseModel): + """ + A balance of an asset. + """ # noqa: E501 + asset: BalancesAsset + amount: Dict[str, AmountDetail] = Field(description="Amount details denominated in different assets. - The keys represent the asset symbols (e.g., \"btc\", \"usd\"), - Each value contains available and total amounts. - There will always be an entry for the asset specified in the `asset` field.") + __properties: ClassVar[List[str]] = ["asset", "amount"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Balance from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of asset + if self.asset: + _dict['asset'] = self.asset.to_dict() + # override the default output from pydantic by calling `to_dict()` of each value in amount (dict) + _field_dict = {} + if self.amount: + for _key_amount in self.amount: + if self.amount[_key_amount]: + _field_dict[_key_amount] = self.amount[_key_amount].to_dict() + _dict['amount'] = _field_dict + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Balance from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "asset": BalancesAsset.from_dict(obj["asset"]) if obj.get("asset") is not None else None, + "amount": dict( + (_k, AmountDetail.from_dict(_v)) + for _k, _v in obj["amount"].items() + ) + if obj.get("amount") is not None + else None + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/balances.py b/python/cdp/openapi_client/models/balances.py new file mode 100644 index 000000000..982f0a18c --- /dev/null +++ b/python/cdp/openapi_client/models/balances.py @@ -0,0 +1,96 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List +from cdp.openapi_client.models.balance import Balance +from typing import Optional, Set +from typing_extensions import Self + +class Balances(BaseModel): + """ + A list of balances for an account. + """ # noqa: E501 + balances: List[Balance] = Field(description="The list of balances.") + __properties: ClassVar[List[str]] = ["balances"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Balances from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in balances (list) + _items = [] + if self.balances: + for _item_balances in self.balances: + if _item_balances: + _items.append(_item_balances.to_dict()) + _dict['balances'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Balances from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "balances": [Balance.from_dict(_item) for _item in obj["balances"]] if obj.get("balances") is not None else None + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/balances_asset.py b/python/cdp/openapi_client/models/balances_asset.py new file mode 100644 index 000000000..680c4c482 --- /dev/null +++ b/python/cdp/openapi_client/models/balances_asset.py @@ -0,0 +1,96 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List +from typing_extensions import Annotated +from cdp.openapi_client.models.asset_type import AssetType +from typing import Optional, Set +from typing_extensions import Self + +class BalancesAsset(BaseModel): + """ + An asset, e.g. fiat or crypto. + """ # noqa: E501 + symbol: Annotated[str, Field(min_length=1, strict=True, max_length=42)] = Field(description="The symbol of the asset (e.g., eth, usd, usdc, usdt).") + type: AssetType + name: StrictStr = Field(description="The name of the asset.") + decimals: StrictInt = Field(description="The number of decimals (i.e. significant digits to the right of the decimal point) supported for the asset.") + __properties: ClassVar[List[str]] = ["symbol", "type", "name", "decimals"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of BalancesAsset from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of BalancesAsset from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "symbol": obj.get("symbol"), + "type": obj.get("type"), + "name": obj.get("name"), + "decimals": obj.get("decimals") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/create_account_request.py b/python/cdp/openapi_client/models/create_account_request.py new file mode 100644 index 000000000..a2e54ab58 --- /dev/null +++ b/python/cdp/openapi_client/models/create_account_request.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, field_validator +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated +from typing import Optional, Set +from typing_extensions import Self + +class CreateAccountRequest(BaseModel): + """ + CreateAccountRequest + """ # noqa: E501 + name: Optional[Annotated[str, Field(strict=True, max_length=64)]] = Field(default=None, description="An optional name for the account. Must be 1-64 characters and can only contain alphanumeric characters, hyphens, and spaces.") + __properties: ClassVar[List[str]] = ["name"] + + @field_validator('name') + def name_validate_regular_expression(cls, value): + """Validates the regular expression""" + if value is None: + return value + + if not re.match(r"^[a-zA-Z0-9 -]{1,64}$", value): + raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9 -]{1,64}$/") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CreateAccountRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CreateAccountRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/create_crypto_deposit_destination_request.py b/python/cdp/openapi_client/models/create_crypto_deposit_destination_request.py new file mode 100644 index 000000000..a9879312b --- /dev/null +++ b/python/cdp/openapi_client/models/create_crypto_deposit_destination_request.py @@ -0,0 +1,119 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated +from cdp.openapi_client.models.create_deposit_destination_crypto import CreateDepositDestinationCrypto +from cdp.openapi_client.models.deposit_destination_target import DepositDestinationTarget +from typing import Optional, Set +from typing_extensions import Self + +class CreateCryptoDepositDestinationRequest(BaseModel): + """ + CreateCryptoDepositDestinationRequest + """ # noqa: E501 + account_id: Annotated[str, Field(strict=True)] = Field(description="The ID of the Account, which is a UUID prefixed by the string `account_`.", alias="accountId") + type: StrictStr + target: Optional[DepositDestinationTarget] = None + metadata: Optional[Dict[str, Annotated[str, Field(min_length=0, strict=True, max_length=500)]]] = Field(default=None, description="Optional metadata as key-value pairs. Use this to store additional structured information on a resource, such as customer IDs, order references, or any application-specific data. Up to 10 key/value pairs may be provided. Keys and values are both strings. Keys must be ≤ 40 characters; values must be ≤ 500 characters.") + crypto: CreateDepositDestinationCrypto = Field(description="Crypto-specific details. Required when `type` is `crypto`.") + __properties: ClassVar[List[str]] = ["accountId", "type", "target", "metadata", "crypto"] + + @field_validator('account_id') + def account_id_validate_regular_expression(cls, value): + """Validates the regular expression""" + if not re.match(r"^account_[a-f0-9\-]{36}$", value): + raise ValueError(r"must validate the regular expression /^account_[a-f0-9\-]{36}$/") + return value + + @field_validator('type') + def type_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['crypto']): + raise ValueError("must be one of enum values ('crypto')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CreateCryptoDepositDestinationRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of target + if self.target: + _dict['target'] = self.target.to_dict() + # override the default output from pydantic by calling `to_dict()` of crypto + if self.crypto: + _dict['crypto'] = self.crypto.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CreateCryptoDepositDestinationRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "accountId": obj.get("accountId"), + "type": obj.get("type"), + "target": DepositDestinationTarget.from_dict(obj["target"]) if obj.get("target") is not None else None, + "metadata": obj.get("metadata"), + "crypto": CreateDepositDestinationCrypto.from_dict(obj["crypto"]) if obj.get("crypto") is not None else None + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/create_deposit_destination_crypto.py b/python/cdp/openapi_client/models/create_deposit_destination_crypto.py new file mode 100644 index 000000000..27f4027a8 --- /dev/null +++ b/python/cdp/openapi_client/models/create_deposit_destination_crypto.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict +from typing import Any, ClassVar, Dict, List +from cdp.openapi_client.models.network import Network +from typing import Optional, Set +from typing_extensions import Self + +class CreateDepositDestinationCrypto(BaseModel): + """ + Crypto-specific details for creating a deposit destination. + """ # noqa: E501 + network: Network + __properties: ClassVar[List[str]] = ["network"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CreateDepositDestinationCrypto from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CreateDepositDestinationCrypto from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "network": obj.get("network") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/create_deposit_destination_request.py b/python/cdp/openapi_client/models/create_deposit_destination_request.py new file mode 100644 index 000000000..b6a587f31 --- /dev/null +++ b/python/cdp/openapi_client/models/create_deposit_destination_request.py @@ -0,0 +1,127 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from cdp.openapi_client.models.create_crypto_deposit_destination_request import CreateCryptoDepositDestinationRequest +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +CREATEDEPOSITDESTINATIONREQUEST_ONE_OF_SCHEMAS = ["CreateCryptoDepositDestinationRequest"] + +class CreateDepositDestinationRequest(BaseModel): + """ + Request to create a new deposit destination. Provide the type-specific details matching the chosen `type`. + """ + # data type: CreateCryptoDepositDestinationRequest + oneof_schema_1_validator: Optional[CreateCryptoDepositDestinationRequest] = None + actual_instance: Optional[Union[CreateCryptoDepositDestinationRequest]] = None + one_of_schemas: Set[str] = { "CreateCryptoDepositDestinationRequest" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + discriminator_value_class_map: Dict[str, str] = { + } + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = CreateDepositDestinationRequest.model_construct() + error_messages = [] + match = 0 + # validate data type: CreateCryptoDepositDestinationRequest + if not isinstance(v, CreateCryptoDepositDestinationRequest): + error_messages.append(f"Error! Input type `{type(v)}` is not `CreateCryptoDepositDestinationRequest`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in CreateDepositDestinationRequest with oneOf schemas: CreateCryptoDepositDestinationRequest. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in CreateDepositDestinationRequest with oneOf schemas: CreateCryptoDepositDestinationRequest. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into CreateCryptoDepositDestinationRequest + try: + instance.actual_instance = CreateCryptoDepositDestinationRequest.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into CreateDepositDestinationRequest with oneOf schemas: CreateCryptoDepositDestinationRequest. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into CreateDepositDestinationRequest with oneOf schemas: CreateCryptoDepositDestinationRequest. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], CreateCryptoDepositDestinationRequest]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/python/cdp/openapi_client/models/create_deposit_destination_request_base.py b/python/cdp/openapi_client/models/create_deposit_destination_request_base.py new file mode 100644 index 000000000..b77bc87da --- /dev/null +++ b/python/cdp/openapi_client/models/create_deposit_destination_request_base.py @@ -0,0 +1,106 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated +from cdp.openapi_client.models.deposit_destination_target import DepositDestinationTarget +from typing import Optional, Set +from typing_extensions import Self + +class CreateDepositDestinationRequestBase(BaseModel): + """ + Common fields for creating a deposit destination. + """ # noqa: E501 + account_id: Annotated[str, Field(strict=True)] = Field(description="The ID of the Account, which is a UUID prefixed by the string `account_`.", alias="accountId") + type: StrictStr = Field(description="The type of deposit destination.") + target: Optional[DepositDestinationTarget] = None + metadata: Optional[Dict[str, Annotated[str, Field(min_length=0, strict=True, max_length=500)]]] = Field(default=None, description="Optional metadata as key-value pairs. Use this to store additional structured information on a resource, such as customer IDs, order references, or any application-specific data. Up to 10 key/value pairs may be provided. Keys and values are both strings. Keys must be ≤ 40 characters; values must be ≤ 500 characters.") + __properties: ClassVar[List[str]] = ["accountId", "type", "target", "metadata"] + + @field_validator('account_id') + def account_id_validate_regular_expression(cls, value): + """Validates the regular expression""" + if not re.match(r"^account_[a-f0-9\-]{36}$", value): + raise ValueError(r"must validate the regular expression /^account_[a-f0-9\-]{36}$/") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CreateDepositDestinationRequestBase from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of target + if self.target: + _dict['target'] = self.target.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CreateDepositDestinationRequestBase from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "accountId": obj.get("accountId"), + "type": obj.get("type"), + "target": DepositDestinationTarget.from_dict(obj["target"]) if obj.get("target") is not None else None, + "metadata": obj.get("metadata") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/create_transfer_source.py b/python/cdp/openapi_client/models/create_transfer_source.py new file mode 100644 index 000000000..a863af3ac --- /dev/null +++ b/python/cdp/openapi_client/models/create_transfer_source.py @@ -0,0 +1,138 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from cdp.openapi_client.models.payment_method import PaymentMethod +from cdp.openapi_client.models.transfers_account import TransfersAccount +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +CREATETRANSFERSOURCE_ONE_OF_SCHEMAS = ["PaymentMethod", "TransfersAccount"] + +class CreateTransferSource(BaseModel): + """ + The source of the transfer. + """ + # data type: TransfersAccount + oneof_schema_1_validator: Optional[TransfersAccount] = None + # data type: PaymentMethod + oneof_schema_2_validator: Optional[PaymentMethod] = None + actual_instance: Optional[Union[PaymentMethod, TransfersAccount]] = None + one_of_schemas: Set[str] = { "PaymentMethod", "TransfersAccount" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = CreateTransferSource.model_construct() + error_messages = [] + match = 0 + # validate data type: TransfersAccount + if not isinstance(v, TransfersAccount): + error_messages.append(f"Error! Input type `{type(v)}` is not `TransfersAccount`") + else: + match += 1 + # validate data type: PaymentMethod + if not isinstance(v, PaymentMethod): + error_messages.append(f"Error! Input type `{type(v)}` is not `PaymentMethod`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in CreateTransferSource with oneOf schemas: PaymentMethod, TransfersAccount. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in CreateTransferSource with oneOf schemas: PaymentMethod, TransfersAccount. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into TransfersAccount + try: + instance.actual_instance = TransfersAccount.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into PaymentMethod + try: + instance.actual_instance = PaymentMethod.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into CreateTransferSource with oneOf schemas: PaymentMethod, TransfersAccount. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into CreateTransferSource with oneOf schemas: PaymentMethod, TransfersAccount. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], PaymentMethod, TransfersAccount]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/python/cdp/openapi_client/models/crypto_deposit_destination.py b/python/cdp/openapi_client/models/crypto_deposit_destination.py new file mode 100644 index 000000000..e2d3f7b1f --- /dev/null +++ b/python/cdp/openapi_client/models/crypto_deposit_destination.py @@ -0,0 +1,136 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated +from cdp.openapi_client.models.deposit_destination_crypto import DepositDestinationCrypto +from cdp.openapi_client.models.deposit_destination_status import DepositDestinationStatus +from cdp.openapi_client.models.deposit_destination_target import DepositDestinationTarget +from typing import Optional, Set +from typing_extensions import Self + +class CryptoDepositDestination(BaseModel): + """ + A cryptocurrency deposit destination. + """ # noqa: E501 + deposit_destination_id: Annotated[str, Field(strict=True)] = Field(description="The ID of the Deposit Destination, which is a UUID prefixed by the string `depositDestination_`.", alias="depositDestinationId") + account_id: Annotated[str, Field(strict=True)] = Field(description="The ID of the Account, which is a UUID prefixed by the string `account_`.", alias="accountId") + type: StrictStr = Field(description="The type of deposit destination.") + crypto: DepositDestinationCrypto = Field(description="Crypto-specific details for this deposit destination. Always populated in responses. Contains the network and address.") + target: Optional[DepositDestinationTarget] = None + status: DepositDestinationStatus + metadata: Optional[Dict[str, Annotated[str, Field(min_length=0, strict=True, max_length=500)]]] = Field(default=None, description="Optional metadata as key-value pairs. Use this to store additional structured information on a resource, such as customer IDs, order references, or any application-specific data. Up to 10 key/value pairs may be provided. Keys and values are both strings. Keys must be ≤ 40 characters; values must be ≤ 500 characters.") + created_at: datetime = Field(description="The timestamp when the deposit destination was created.", alias="createdAt") + updated_at: datetime = Field(description="The timestamp when the deposit destination was last updated.", alias="updatedAt") + __properties: ClassVar[List[str]] = ["depositDestinationId", "accountId", "type", "crypto", "target", "status", "metadata", "createdAt", "updatedAt"] + + @field_validator('deposit_destination_id') + def deposit_destination_id_validate_regular_expression(cls, value): + """Validates the regular expression""" + if not re.match(r"^depositDestination_[a-f0-9\-]{36}$", value): + raise ValueError(r"must validate the regular expression /^depositDestination_[a-f0-9\-]{36}$/") + return value + + @field_validator('account_id') + def account_id_validate_regular_expression(cls, value): + """Validates the regular expression""" + if not re.match(r"^account_[a-f0-9\-]{36}$", value): + raise ValueError(r"must validate the regular expression /^account_[a-f0-9\-]{36}$/") + return value + + @field_validator('type') + def type_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['crypto']): + raise ValueError("must be one of enum values ('crypto')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CryptoDepositDestination from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of crypto + if self.crypto: + _dict['crypto'] = self.crypto.to_dict() + # override the default output from pydantic by calling `to_dict()` of target + if self.target: + _dict['target'] = self.target.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CryptoDepositDestination from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "depositDestinationId": obj.get("depositDestinationId"), + "accountId": obj.get("accountId"), + "type": obj.get("type"), + "crypto": DepositDestinationCrypto.from_dict(obj["crypto"]) if obj.get("crypto") is not None else None, + "target": DepositDestinationTarget.from_dict(obj["target"]) if obj.get("target") is not None else None, + "status": obj.get("status"), + "metadata": obj.get("metadata"), + "createdAt": obj.get("createdAt"), + "updatedAt": obj.get("updatedAt") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/deposit_destination.py b/python/cdp/openapi_client/models/deposit_destination.py new file mode 100644 index 000000000..17c9f7a4c --- /dev/null +++ b/python/cdp/openapi_client/models/deposit_destination.py @@ -0,0 +1,127 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from cdp.openapi_client.models.crypto_deposit_destination import CryptoDepositDestination +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +DEPOSITDESTINATION_ONE_OF_SCHEMAS = ["CryptoDepositDestination"] + +class DepositDestination(BaseModel): + """ + A deposit destination for receiving funds to an account. + """ + # data type: CryptoDepositDestination + oneof_schema_1_validator: Optional[CryptoDepositDestination] = None + actual_instance: Optional[Union[CryptoDepositDestination]] = None + one_of_schemas: Set[str] = { "CryptoDepositDestination" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + discriminator_value_class_map: Dict[str, str] = { + } + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = DepositDestination.model_construct() + error_messages = [] + match = 0 + # validate data type: CryptoDepositDestination + if not isinstance(v, CryptoDepositDestination): + error_messages.append(f"Error! Input type `{type(v)}` is not `CryptoDepositDestination`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in DepositDestination with oneOf schemas: CryptoDepositDestination. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in DepositDestination with oneOf schemas: CryptoDepositDestination. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into CryptoDepositDestination + try: + instance.actual_instance = CryptoDepositDestination.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into DepositDestination with oneOf schemas: CryptoDepositDestination. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into DepositDestination with oneOf schemas: CryptoDepositDestination. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], CryptoDepositDestination]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/python/cdp/openapi_client/models/deposit_destination_crypto.py b/python/cdp/openapi_client/models/deposit_destination_crypto.py new file mode 100644 index 000000000..a16371995 --- /dev/null +++ b/python/cdp/openapi_client/models/deposit_destination_crypto.py @@ -0,0 +1,92 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List +from typing_extensions import Annotated +from cdp.openapi_client.models.network import Network +from typing import Optional, Set +from typing_extensions import Self + +class DepositDestinationCrypto(BaseModel): + """ + Crypto-specific deposit destination details. In responses, this object is always present. Contains the network and address for the deposit destination. + """ # noqa: E501 + network: Network + address: Annotated[str, Field(min_length=1, strict=True, max_length=128)] = Field(description="A blockchain address. Format varies by network (e.g., 0x-prefixed for EVM, base58 for Solana).") + __properties: ClassVar[List[str]] = ["network", "address"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DepositDestinationCrypto from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DepositDestinationCrypto from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "network": obj.get("network"), + "address": obj.get("address") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/deposit_destination_reference.py b/python/cdp/openapi_client/models/deposit_destination_reference.py new file mode 100644 index 000000000..d885834bd --- /dev/null +++ b/python/cdp/openapi_client/models/deposit_destination_reference.py @@ -0,0 +1,96 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, field_validator +from typing import Any, ClassVar, Dict, List +from typing_extensions import Annotated +from typing import Optional, Set +from typing_extensions import Self + +class DepositDestinationReference(BaseModel): + """ + A reference to the deposit destination associated with the transfer. + """ # noqa: E501 + id: Annotated[str, Field(strict=True)] = Field(description="The ID of the Deposit Destination, which is a UUID prefixed by the string `depositDestination_`.") + __properties: ClassVar[List[str]] = ["id"] + + @field_validator('id') + def id_validate_regular_expression(cls, value): + """Validates the regular expression""" + if not re.match(r"^depositDestination_[a-f0-9\-]{36}$", value): + raise ValueError(r"must validate the regular expression /^depositDestination_[a-f0-9\-]{36}$/") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DepositDestinationReference from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DepositDestinationReference from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/deposit_destination_status.py b/python/cdp/openapi_client/models/deposit_destination_status.py new file mode 100644 index 000000000..87341181a --- /dev/null +++ b/python/cdp/openapi_client/models/deposit_destination_status.py @@ -0,0 +1,39 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class DepositDestinationStatus(str, Enum): + """ + The status of the deposit destination. + """ + + """ + allowed enum values + """ + ACTIVE = 'active' + INACTIVE = 'inactive' + PENDING = 'pending' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of DepositDestinationStatus from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/python/cdp/openapi_client/models/deposit_destination_target.py b/python/cdp/openapi_client/models/deposit_destination_target.py new file mode 100644 index 000000000..6b8c8842f --- /dev/null +++ b/python/cdp/openapi_client/models/deposit_destination_target.py @@ -0,0 +1,124 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from cdp.openapi_client.models.deposit_destination_target_account import DepositDestinationTargetAccount +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +DEPOSITDESTINATIONTARGET_ONE_OF_SCHEMAS = ["DepositDestinationTargetAccount"] + +class DepositDestinationTarget(BaseModel): + """ + The intended target for deposited funds. + """ + # data type: DepositDestinationTargetAccount + oneof_schema_1_validator: Optional[DepositDestinationTargetAccount] = None + actual_instance: Optional[Union[DepositDestinationTargetAccount]] = None + one_of_schemas: Set[str] = { "DepositDestinationTargetAccount" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = DepositDestinationTarget.model_construct() + error_messages = [] + match = 0 + # validate data type: DepositDestinationTargetAccount + if not isinstance(v, DepositDestinationTargetAccount): + error_messages.append(f"Error! Input type `{type(v)}` is not `DepositDestinationTargetAccount`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in DepositDestinationTarget with oneOf schemas: DepositDestinationTargetAccount. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in DepositDestinationTarget with oneOf schemas: DepositDestinationTargetAccount. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into DepositDestinationTargetAccount + try: + instance.actual_instance = DepositDestinationTargetAccount.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into DepositDestinationTarget with oneOf schemas: DepositDestinationTargetAccount. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into DepositDestinationTarget with oneOf schemas: DepositDestinationTargetAccount. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], DepositDestinationTargetAccount]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/python/cdp/openapi_client/models/deposit_destination_target_account.py b/python/cdp/openapi_client/models/deposit_destination_target_account.py new file mode 100644 index 000000000..7af053297 --- /dev/null +++ b/python/cdp/openapi_client/models/deposit_destination_target_account.py @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, field_validator +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated +from typing import Optional, Set +from typing_extensions import Self + +class DepositDestinationTargetAccount(BaseModel): + """ + The account and asset where incoming deposits should be credited. + """ # noqa: E501 + account_id: Optional[Annotated[str, Field(strict=True)]] = Field(default=None, description="The ID of the CDP Account to which deposited funds should be transferred.", alias="accountId") + asset: Annotated[str, Field(min_length=1, strict=True, max_length=42)] = Field(description="The symbol of the asset that should land in the target account.") + __properties: ClassVar[List[str]] = ["accountId", "asset"] + + @field_validator('account_id') + def account_id_validate_regular_expression(cls, value): + """Validates the regular expression""" + if value is None: + return value + + if not re.match(r"^account_[a-f0-9\-]{36}$", value): + raise ValueError(r"must validate the regular expression /^account_[a-f0-9\-]{36}$/") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DepositDestinationTargetAccount from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DepositDestinationTargetAccount from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "accountId": obj.get("accountId"), + "asset": obj.get("asset") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/deposit_travel_rule_beneficiary.py b/python/cdp/openapi_client/models/deposit_travel_rule_beneficiary.py new file mode 100644 index 000000000..944895ca4 --- /dev/null +++ b/python/cdp/openapi_client/models/deposit_travel_rule_beneficiary.py @@ -0,0 +1,88 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class DepositTravelRuleBeneficiary(BaseModel): + """ + Beneficiary information for a deposit travel rule submission. + """ # noqa: E501 + name: Optional[StrictStr] = Field(default=None, description="Full name of the beneficiary.") + __properties: ClassVar[List[str]] = ["name"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DepositTravelRuleBeneficiary from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DepositTravelRuleBeneficiary from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/deposit_travel_rule_originator.py b/python/cdp/openapi_client/models/deposit_travel_rule_originator.py new file mode 100644 index 000000000..aaa6398f1 --- /dev/null +++ b/python/cdp/openapi_client/models/deposit_travel_rule_originator.py @@ -0,0 +1,120 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional +from cdp.openapi_client.models.date_of_birth import DateOfBirth +from cdp.openapi_client.models.deposit_travel_rule_vasp import DepositTravelRuleVasp +from cdp.openapi_client.models.physical_address import PhysicalAddress +from typing import Optional, Set +from typing_extensions import Self + +class DepositTravelRuleOriginator(BaseModel): + """ + Originator information for a deposit travel rule submission. + """ # noqa: E501 + name: Optional[StrictStr] = Field(default=None, description="Full name of the originator.") + address: Optional[PhysicalAddress] = None + wallet_type: Optional[StrictStr] = Field(default=None, description="The type of the originator's wallet.", alias="walletType") + virtual_asset_service_provider: Optional[DepositTravelRuleVasp] = Field(default=None, alias="virtualAssetServiceProvider") + personal_id: Optional[StrictStr] = Field(default=None, description="Government-issued personal identification number for the originator.", alias="personalId") + date_of_birth: Optional[DateOfBirth] = Field(default=None, alias="dateOfBirth") + __properties: ClassVar[List[str]] = ["name", "address", "walletType", "virtualAssetServiceProvider", "personalId", "dateOfBirth"] + + @field_validator('wallet_type') + def wallet_type_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['custodial', 'self_custody']): + raise ValueError("must be one of enum values ('custodial', 'self_custody')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DepositTravelRuleOriginator from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of address + if self.address: + _dict['address'] = self.address.to_dict() + # override the default output from pydantic by calling `to_dict()` of virtual_asset_service_provider + if self.virtual_asset_service_provider: + _dict['virtualAssetServiceProvider'] = self.virtual_asset_service_provider.to_dict() + # override the default output from pydantic by calling `to_dict()` of date_of_birth + if self.date_of_birth: + _dict['dateOfBirth'] = self.date_of_birth.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DepositTravelRuleOriginator from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "address": PhysicalAddress.from_dict(obj["address"]) if obj.get("address") is not None else None, + "walletType": obj.get("walletType"), + "virtualAssetServiceProvider": DepositTravelRuleVasp.from_dict(obj["virtualAssetServiceProvider"]) if obj.get("virtualAssetServiceProvider") is not None else None, + "personalId": obj.get("personalId"), + "dateOfBirth": DateOfBirth.from_dict(obj["dateOfBirth"]) if obj.get("dateOfBirth") is not None else None + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/deposit_travel_rule_request.py b/python/cdp/openapi_client/models/deposit_travel_rule_request.py new file mode 100644 index 000000000..ed0b2c194 --- /dev/null +++ b/python/cdp/openapi_client/models/deposit_travel_rule_request.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictBool +from typing import Any, ClassVar, Dict, List, Optional +from cdp.openapi_client.models.deposit_travel_rule_beneficiary import DepositTravelRuleBeneficiary +from cdp.openapi_client.models.deposit_travel_rule_originator import DepositTravelRuleOriginator +from typing import Optional, Set +from typing_extensions import Self + +class DepositTravelRuleRequest(BaseModel): + """ + Request body for submitting travel rule information for a deposit transfer. Required fields vary by jurisdiction. + """ # noqa: E501 + originator: Optional[DepositTravelRuleOriginator] = None + beneficiary: Optional[DepositTravelRuleBeneficiary] = None + is_self: Optional[StrictBool] = Field(default=None, description="Indicates whether the user attests that the originating wallet belongs to them.", alias="isSelf") + __properties: ClassVar[List[str]] = ["originator", "beneficiary", "isSelf"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DepositTravelRuleRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of originator + if self.originator: + _dict['originator'] = self.originator.to_dict() + # override the default output from pydantic by calling `to_dict()` of beneficiary + if self.beneficiary: + _dict['beneficiary'] = self.beneficiary.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DepositTravelRuleRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "originator": DepositTravelRuleOriginator.from_dict(obj["originator"]) if obj.get("originator") is not None else None, + "beneficiary": DepositTravelRuleBeneficiary.from_dict(obj["beneficiary"]) if obj.get("beneficiary") is not None else None, + "isSelf": obj.get("isSelf") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/deposit_travel_rule_response.py b/python/cdp/openapi_client/models/deposit_travel_rule_response.py new file mode 100644 index 000000000..70384df8e --- /dev/null +++ b/python/cdp/openapi_client/models/deposit_travel_rule_response.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from cdp.openapi_client.models.travel_rule_status import TravelRuleStatus +from typing import Optional, Set +from typing_extensions import Self + +class DepositTravelRuleResponse(BaseModel): + """ + Response from submitting travel rule information for a deposit transfer. + """ # noqa: E501 + status: TravelRuleStatus + missing_fields: Optional[List[StrictStr]] = Field(default=None, description="List of field paths that are still required to complete travel rule compliance. Each entry is a dot-separated path (e.g., \"originator.name\", \"originator.address.countryCode\"). Empty when status is \"completed\".", alias="missingFields") + reason: Optional[StrictStr] = Field(default=None, description="Additional context about the current status. Present when status is `incomplete` to explain what needs to be fixed before the transfer can proceed.") + __properties: ClassVar[List[str]] = ["status", "missingFields", "reason"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DepositTravelRuleResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DepositTravelRuleResponse from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "status": obj.get("status"), + "missingFields": obj.get("missingFields"), + "reason": obj.get("reason") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/deposit_travel_rule_vasp.py b/python/cdp/openapi_client/models/deposit_travel_rule_vasp.py new file mode 100644 index 000000000..86aaa7058 --- /dev/null +++ b/python/cdp/openapi_client/models/deposit_travel_rule_vasp.py @@ -0,0 +1,90 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class DepositTravelRuleVasp(BaseModel): + """ + Information about the Virtual Asset Service Provider (VASP) for a deposit travel rule submission. + """ # noqa: E501 + identifier: Optional[StrictStr] = Field(default=None, description="The Legal Entity Identifier (LEI) of the Virtual Asset Service Provider (VASP).") + name: Optional[StrictStr] = Field(default=None, description="The name of the Virtual Asset Service Provider (VASP).") + __properties: ClassVar[List[str]] = ["identifier", "name"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DepositTravelRuleVasp from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DepositTravelRuleVasp from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "identifier": obj.get("identifier"), + "name": obj.get("name") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/email_address.py b/python/cdp/openapi_client/models/email_address.py new file mode 100644 index 000000000..260d12e93 --- /dev/null +++ b/python/cdp/openapi_client/models/email_address.py @@ -0,0 +1,88 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class EmailAddress(BaseModel): + """ + The target of the payment is an email address. + """ # noqa: E501 + email: StrictStr = Field(description="The email address of the recipient. The recipient will need to have an account with Coinbase or onboard to Coinbase to receive the payment.") + __properties: ClassVar[List[str]] = ["email"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of EmailAddress from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of EmailAddress from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "email": obj.get("email") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/email_instrument.py b/python/cdp/openapi_client/models/email_instrument.py new file mode 100644 index 000000000..ddbeadd78 --- /dev/null +++ b/python/cdp/openapi_client/models/email_instrument.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing_extensions import Annotated +from typing import Optional, Set +from typing_extensions import Self + +class EmailInstrument(BaseModel): + """ + The target of the payment is an email address. + """ # noqa: E501 + email: StrictStr = Field(description="The email address of the recipient. The recipient will need to have an account with Coinbase or onboard to Coinbase to receive the payment.") + asset: Annotated[str, Field(min_length=1, strict=True, max_length=42)] = Field(description="Asset symbol of the payment received by the recipient.") + __properties: ClassVar[List[str]] = ["email", "asset"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of EmailInstrument from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of EmailInstrument from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "email": obj.get("email"), + "asset": obj.get("asset") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/error_type.py b/python/cdp/openapi_client/models/error_type.py index cf811dc36..e01fbc8cd 100644 --- a/python/cdp/openapi_client/models/error_type.py +++ b/python/cdp/openapi_client/models/error_type.py @@ -32,6 +32,7 @@ class ErrorType(str, Enum): BAD_GATEWAY = 'bad_gateway' CAPTURE_EXPIRED = 'capture_expired' CLIENT_CLOSED_REQUEST = 'client_closed_request' + ENDPOINT_UNAVAILABLE = 'endpoint_unavailable' FAUCET_LIMIT_EXCEEDED = 'faucet_limit_exceeded' FORBIDDEN = 'forbidden' IDEMPOTENCY_ERROR = 'idempotency_error' @@ -49,6 +50,7 @@ class ErrorType(str, Enum): SERVICE_UNAVAILABLE = 'service_unavailable' TIMED_OUT = 'timed_out' UNAUTHORIZED = 'unauthorized' + UNSUPPORTED_TOS_LANGUAGE = 'unsupported_tos_language' POLICY_VIOLATION = 'policy_violation' POLICY_IN_USE = 'policy_in_use' ACCOUNT_LIMIT_EXCEEDED = 'account_limit_exceeded' @@ -73,6 +75,7 @@ class ErrorType(str, Enum): TARGET_ONCHAIN_ADDRESS_INVALID = 'target_onchain_address_invalid' TRANSFER_AMOUNT_INVALID = 'transfer_amount_invalid' TRANSFER_ASSET_NOT_SUPPORTED = 'transfer_asset_not_supported' + TRANSFER_QUOTE_EXPIRED = 'transfer_quote_expired' INSUFFICIENT_BALANCE = 'insufficient_balance' METADATA_TOO_MANY_ENTRIES = 'metadata_too_many_entries' METADATA_KEY_TOO_LONG = 'metadata_key_too_long' @@ -91,6 +94,11 @@ class ErrorType(str, Enum): INSUFFICIENT_LIQUIDITY = 'insufficient_liquidity' INSUFFICIENT_ALLOWANCE = 'insufficient_allowance' TRANSACTION_SIMULATION_FAILED = 'transaction_simulation_failed' + DELEGATION_NOT_FOUND = 'delegation_not_found' + DELEGATION_EXPIRED = 'delegation_expired' + DELEGATION_REVOKED = 'delegation_revoked' + DELEGATION_NOT_AUTHORIZED = 'delegation_not_authorized' + DELEGATION_NOT_ENABLED = 'delegation_not_enabled' @classmethod def from_json(cls, json_str: str) -> Self: diff --git a/python/cdp/openapi_client/models/fedwire_details.py b/python/cdp/openapi_client/models/fedwire_details.py new file mode 100644 index 000000000..6be116967 --- /dev/null +++ b/python/cdp/openapi_client/models/fedwire_details.py @@ -0,0 +1,109 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing_extensions import Annotated +from typing import Optional, Set +from typing_extensions import Self + +class FedwireDetails(BaseModel): + """ + Details specific to Fedwire (domestic USD wire) payment methods. + """ # noqa: E501 + asset: StrictStr = Field(description="The asset for this payment method. Always `usd` for Fedwire.") + bank_name: StrictStr = Field(description="The name of the bank.", alias="bankName") + account_last4: Annotated[str, Field(strict=True)] = Field(description="The last 4 digits of the bank account number.", alias="accountLast4") + routing_number: Annotated[str, Field(strict=True)] = Field(description="The ABA routing number of the bank.", alias="routingNumber") + __properties: ClassVar[List[str]] = ["asset", "bankName", "accountLast4", "routingNumber"] + + @field_validator('account_last4') + def account_last4_validate_regular_expression(cls, value): + """Validates the regular expression""" + if not re.match(r"^[0-9]{4}$", value): + raise ValueError(r"must validate the regular expression /^[0-9]{4}$/") + return value + + @field_validator('routing_number') + def routing_number_validate_regular_expression(cls, value): + """Validates the regular expression""" + if not re.match(r"^[0-9]{9}$", value): + raise ValueError(r"must validate the regular expression /^[0-9]{9}$/") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of FedwireDetails from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of FedwireDetails from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "asset": obj.get("asset"), + "bankName": obj.get("bankName"), + "accountLast4": obj.get("accountLast4"), + "routingNumber": obj.get("routingNumber") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/fedwire_payment_method.py b/python/cdp/openapi_client/models/fedwire_payment_method.py new file mode 100644 index 000000000..e9baa34cc --- /dev/null +++ b/python/cdp/openapi_client/models/fedwire_payment_method.py @@ -0,0 +1,118 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing_extensions import Annotated +from cdp.openapi_client.models.fedwire_details import FedwireDetails +from typing import Optional, Set +from typing_extensions import Self + +class FedwirePaymentMethod(BaseModel): + """ + A Fedwire (domestic USD wire) payment method linked to your entity. + """ # noqa: E501 + payment_method_id: Annotated[str, Field(strict=True)] = Field(description="The ID of the Payment Method, which is a UUID prefixed by the string `paymentMethod_`.", alias="paymentMethodId") + active: StrictBool = Field(description="Whether the payment method is active and can be used in transfers. A payment method may be inactive due to verification requirements or entity-level restrictions.") + created_at: datetime = Field(description="The timestamp when the payment method was created.", alias="createdAt") + updated_at: datetime = Field(description="The timestamp when the payment method was last updated.", alias="updatedAt") + payment_rail: StrictStr = Field(description="The payment rail for this payment method.", alias="paymentRail") + fedwire: FedwireDetails = Field(description="Fedwire (domestic USD wire) details.") + __properties: ClassVar[List[str]] = ["paymentMethodId", "active", "createdAt", "updatedAt", "paymentRail", "fedwire"] + + @field_validator('payment_method_id') + def payment_method_id_validate_regular_expression(cls, value): + """Validates the regular expression""" + if not re.match(r"^paymentMethod_[a-f0-9\-]{36}$", value): + raise ValueError(r"must validate the regular expression /^paymentMethod_[a-f0-9\-]{36}$/") + return value + + @field_validator('payment_rail') + def payment_rail_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['fedwire']): + raise ValueError("must be one of enum values ('fedwire')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of FedwirePaymentMethod from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of fedwire + if self.fedwire: + _dict['fedwire'] = self.fedwire.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of FedwirePaymentMethod from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "paymentMethodId": obj.get("paymentMethodId"), + "active": obj.get("active"), + "createdAt": obj.get("createdAt"), + "updatedAt": obj.get("updatedAt"), + "paymentRail": obj.get("paymentRail"), + "fedwire": FedwireDetails.from_dict(obj["fedwire"]) if obj.get("fedwire") is not None else None + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/list_balances200_response.py b/python/cdp/openapi_client/models/list_balances200_response.py new file mode 100644 index 000000000..8a1d4948f --- /dev/null +++ b/python/cdp/openapi_client/models/list_balances200_response.py @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from cdp.openapi_client.models.balance import Balance +from typing import Optional, Set +from typing_extensions import Self + +class ListBalances200Response(BaseModel): + """ + ListBalances200Response + """ # noqa: E501 + balances: List[Balance] = Field(description="The list of balances.") + next_page_token: Optional[StrictStr] = Field(default=None, description="The token for the next page of items, if any.", alias="nextPageToken") + __properties: ClassVar[List[str]] = ["balances", "nextPageToken"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ListBalances200Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in balances (list) + _items = [] + if self.balances: + for _item_balances in self.balances: + if _item_balances: + _items.append(_item_balances.to_dict()) + _dict['balances'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ListBalances200Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "balances": [Balance.from_dict(_item) for _item in obj["balances"]] if obj.get("balances") is not None else None, + "nextPageToken": obj.get("nextPageToken") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/list_deposit_destinations200_response.py b/python/cdp/openapi_client/models/list_deposit_destinations200_response.py new file mode 100644 index 000000000..49fdaf471 --- /dev/null +++ b/python/cdp/openapi_client/models/list_deposit_destinations200_response.py @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from cdp.openapi_client.models.deposit_destination import DepositDestination +from typing import Optional, Set +from typing_extensions import Self + +class ListDepositDestinations200Response(BaseModel): + """ + ListDepositDestinations200Response + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(default=None, description="The token for the next page of items, if any.", alias="nextPageToken") + deposit_destinations: List[DepositDestination] = Field(description="The list of deposit destinations.", alias="depositDestinations") + __properties: ClassVar[List[str]] = ["nextPageToken", "depositDestinations"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ListDepositDestinations200Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in deposit_destinations (list) + _items = [] + if self.deposit_destinations: + for _item_deposit_destinations in self.deposit_destinations: + if _item_deposit_destinations: + _items.append(_item_deposit_destinations.to_dict()) + _dict['depositDestinations'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ListDepositDestinations200Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "nextPageToken": obj.get("nextPageToken"), + "depositDestinations": [DepositDestination.from_dict(_item) for _item in obj["depositDestinations"]] if obj.get("depositDestinations") is not None else None + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/list_foundation_accounts200_response.py b/python/cdp/openapi_client/models/list_foundation_accounts200_response.py new file mode 100644 index 000000000..985e0d491 --- /dev/null +++ b/python/cdp/openapi_client/models/list_foundation_accounts200_response.py @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from cdp.openapi_client.models.account import Account +from typing import Optional, Set +from typing_extensions import Self + +class ListFoundationAccounts200Response(BaseModel): + """ + ListFoundationAccounts200Response + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(default=None, description="The token for the next page of items, if any.", alias="nextPageToken") + accounts: List[Account] = Field(description="The list of accounts.") + __properties: ClassVar[List[str]] = ["nextPageToken", "accounts"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ListFoundationAccounts200Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in accounts (list) + _items = [] + if self.accounts: + for _item_accounts in self.accounts: + if _item_accounts: + _items.append(_item_accounts.to_dict()) + _dict['accounts'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ListFoundationAccounts200Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "nextPageToken": obj.get("nextPageToken"), + "accounts": [Account.from_dict(_item) for _item in obj["accounts"]] if obj.get("accounts") is not None else None + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/list_payment_methods200_response.py b/python/cdp/openapi_client/models/list_payment_methods200_response.py new file mode 100644 index 000000000..0833bea57 --- /dev/null +++ b/python/cdp/openapi_client/models/list_payment_methods200_response.py @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from cdp.openapi_client.models.payment_methods_payment_method import PaymentMethodsPaymentMethod +from typing import Optional, Set +from typing_extensions import Self + +class ListPaymentMethods200Response(BaseModel): + """ + ListPaymentMethods200Response + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(default=None, description="The token for the next page of items, if any.", alias="nextPageToken") + payment_methods: List[PaymentMethodsPaymentMethod] = Field(description="The list of payment methods.", alias="paymentMethods") + __properties: ClassVar[List[str]] = ["nextPageToken", "paymentMethods"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ListPaymentMethods200Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in payment_methods (list) + _items = [] + if self.payment_methods: + for _item_payment_methods in self.payment_methods: + if _item_payment_methods: + _items.append(_item_payment_methods.to_dict()) + _dict['paymentMethods'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ListPaymentMethods200Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "nextPageToken": obj.get("nextPageToken"), + "paymentMethods": [PaymentMethodsPaymentMethod.from_dict(_item) for _item in obj["paymentMethods"]] if obj.get("paymentMethods") is not None else None + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/list_transfers200_response.py b/python/cdp/openapi_client/models/list_transfers200_response.py new file mode 100644 index 000000000..70179c797 --- /dev/null +++ b/python/cdp/openapi_client/models/list_transfers200_response.py @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from cdp.openapi_client.models.transfer import Transfer +from typing import Optional, Set +from typing_extensions import Self + +class ListTransfers200Response(BaseModel): + """ + ListTransfers200Response + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(default=None, description="The token for the next page of items, if any.", alias="nextPageToken") + transfers: List[Transfer] = Field(description="The list of transfers.") + __properties: ClassVar[List[str]] = ["nextPageToken", "transfers"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ListTransfers200Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in transfers (list) + _items = [] + if self.transfers: + for _item_transfers in self.transfers: + if _item_transfers: + _items.append(_item_transfers.to_dict()) + _dict['transfers'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ListTransfers200Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "nextPageToken": obj.get("nextPageToken"), + "transfers": [Transfer.from_dict(_item) for _item in obj["transfers"]] if obj.get("transfers") is not None else None + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/network.py b/python/cdp/openapi_client/models/network.py new file mode 100644 index 000000000..6c76d3527 --- /dev/null +++ b/python/cdp/openapi_client/models/network.py @@ -0,0 +1,46 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class Network(str, Enum): + """ + The blockchain network for the payment. Supported networks depend on the account type. See [API and Network Support](https://docs.cdp.coinbase.com/api-reference/payment-apis/supported-networks-assets#by-asset-and-network) for more details. + """ + + """ + allowed enum values + """ + BASE = 'base' + ETHEREUM = 'ethereum' + SOLANA = 'solana' + APTOS = 'aptos' + ARBITRUM = 'arbitrum' + ARBITRUM_MINUS_SEPOLIA = 'arbitrum-sepolia' + OPTIMISM = 'optimism' + POLYGON = 'polygon' + WORLD = 'world' + WORLD_MINUS_SEPOLIA = 'world-sepolia' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of Network from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/python/cdp/openapi_client/models/onchain_address.py b/python/cdp/openapi_client/models/onchain_address.py new file mode 100644 index 000000000..770eb6f05 --- /dev/null +++ b/python/cdp/openapi_client/models/onchain_address.py @@ -0,0 +1,96 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated +from cdp.openapi_client.models.network import Network +from typing import Optional, Set +from typing_extensions import Self + +class OnchainAddress(BaseModel): + """ + The target of the payment is an onchain address. + """ # noqa: E501 + address: Annotated[str, Field(min_length=1, strict=True, max_length=128)] = Field(description="The onchain crypto address of the recipient. Examples: - EVM address: 0xabc1234567890abcdef1234567890abcdef123456 - Solana address: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT - XRP address: rhccc5p23aKiCGFcEqqnjEfLRZ6xEvfy3s ") + network: Network + destination_tag: Optional[StrictStr] = Field(default=None, description="The destination tag of the onchain address. Destination tags are used by certain networks (primarily XRP/Ripple) to identify specific recipients when multiple users share a single address. The tag ensures funds are credited to the correct account within the shared address. Examples by network: - XRP/Ripple: Numeric values like \"1234567890\" or \"123456\" - Stellar (XLM): Memos which can be text, ID, or hash format Note: Most networks (Ethereum, Bitcoin, Solana) do not use destination tags. ", alias="destinationTag") + asset: Annotated[str, Field(min_length=1, strict=True, max_length=42)] = Field(description="Asset symbol of the payment received by the recipient.") + __properties: ClassVar[List[str]] = ["address", "network", "destinationTag", "asset"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of OnchainAddress from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of OnchainAddress from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "address": obj.get("address"), + "network": obj.get("network"), + "destinationTag": obj.get("destinationTag"), + "asset": obj.get("asset") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/originating_bank_account_us.py b/python/cdp/openapi_client/models/originating_bank_account_us.py new file mode 100644 index 000000000..54948d15a --- /dev/null +++ b/python/cdp/openapi_client/models/originating_bank_account_us.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing_extensions import Annotated +from typing import Optional, Set +from typing_extensions import Self + +class OriginatingBankAccountUS(BaseModel): + """ + The originating US bank account details for the transfer source. Present when funds were deposited from an external bank account into a deposit destination. Only the last 4 digits of the account number are exposed. + """ # noqa: E501 + bank_name: StrictStr = Field(description="The name of the bank that originated the deposit.", alias="bankName") + account_last4: Annotated[str, Field(strict=True)] = Field(description="The last 4 digits of the originating bank account number.", alias="accountLast4") + currency: StrictStr = Field(description="The fiat currency of the deposit (e.g., `usd`).") + __properties: ClassVar[List[str]] = ["bankName", "accountLast4", "currency"] + + @field_validator('account_last4') + def account_last4_validate_regular_expression(cls, value): + """Validates the regular expression""" + if not re.match(r"^[0-9]{4}$", value): + raise ValueError(r"must validate the regular expression /^[0-9]{4}$/") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of OriginatingBankAccountUS from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of OriginatingBankAccountUS from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "bankName": obj.get("bankName"), + "accountLast4": obj.get("accountLast4"), + "currency": obj.get("currency") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/payment_method.py b/python/cdp/openapi_client/models/payment_method.py new file mode 100644 index 000000000..942696b08 --- /dev/null +++ b/python/cdp/openapi_client/models/payment_method.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing_extensions import Annotated +from typing import Optional, Set +from typing_extensions import Self + +class PaymentMethod(BaseModel): + """ + The Payment Method specific details for the transfer. + """ # noqa: E501 + payment_method_id: StrictStr = Field(description="The ID of the Payment Method.", alias="paymentMethodId") + asset: Annotated[str, Field(min_length=1, strict=True, max_length=42)] = Field(description="The symbol of the asset (e.g., eth, usd, usdc, usdt).") + __properties: ClassVar[List[str]] = ["paymentMethodId", "asset"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PaymentMethod from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PaymentMethod from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "paymentMethodId": obj.get("paymentMethodId"), + "asset": obj.get("asset") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/payment_method_base.py b/python/cdp/openapi_client/models/payment_method_base.py new file mode 100644 index 000000000..78ee8a6d8 --- /dev/null +++ b/python/cdp/openapi_client/models/payment_method_base.py @@ -0,0 +1,103 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, field_validator +from typing import Any, ClassVar, Dict, List +from typing_extensions import Annotated +from typing import Optional, Set +from typing_extensions import Self + +class PaymentMethodBase(BaseModel): + """ + Common properties shared by all payment method types. + """ # noqa: E501 + payment_method_id: Annotated[str, Field(strict=True)] = Field(description="The ID of the Payment Method, which is a UUID prefixed by the string `paymentMethod_`.", alias="paymentMethodId") + active: StrictBool = Field(description="Whether the payment method is active and can be used in transfers. A payment method may be inactive due to verification requirements or entity-level restrictions.") + created_at: datetime = Field(description="The timestamp when the payment method was created.", alias="createdAt") + updated_at: datetime = Field(description="The timestamp when the payment method was last updated.", alias="updatedAt") + __properties: ClassVar[List[str]] = ["paymentMethodId", "active", "createdAt", "updatedAt"] + + @field_validator('payment_method_id') + def payment_method_id_validate_regular_expression(cls, value): + """Validates the regular expression""" + if not re.match(r"^paymentMethod_[a-f0-9\-]{36}$", value): + raise ValueError(r"must validate the regular expression /^paymentMethod_[a-f0-9\-]{36}$/") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PaymentMethodBase from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PaymentMethodBase from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "paymentMethodId": obj.get("paymentMethodId"), + "active": obj.get("active"), + "createdAt": obj.get("createdAt"), + "updatedAt": obj.get("updatedAt") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/payment_methods_payment_method.py b/python/cdp/openapi_client/models/payment_methods_payment_method.py new file mode 100644 index 000000000..d30d1fb9b --- /dev/null +++ b/python/cdp/openapi_client/models/payment_methods_payment_method.py @@ -0,0 +1,155 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from cdp.openapi_client.models.fedwire_payment_method import FedwirePaymentMethod +from cdp.openapi_client.models.sepa_payment_method import SepaPaymentMethod +from cdp.openapi_client.models.swift_payment_method import SwiftPaymentMethod +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +PAYMENTMETHODSPAYMENTMETHOD_ONE_OF_SCHEMAS = ["FedwirePaymentMethod", "SepaPaymentMethod", "SwiftPaymentMethod"] + +class PaymentMethodsPaymentMethod(BaseModel): + """ + A payment method linked to your entity. Payment methods represent external financial instruments that can be used as a target for transfers. The `paymentRail` field indicates which type-specific details object is present. Type-specific fields are nested under a key matching the rail name (e.g., `fedwire`, `swift`). + """ + # data type: FedwirePaymentMethod + oneof_schema_1_validator: Optional[FedwirePaymentMethod] = None + # data type: SwiftPaymentMethod + oneof_schema_2_validator: Optional[SwiftPaymentMethod] = None + # data type: SepaPaymentMethod + oneof_schema_3_validator: Optional[SepaPaymentMethod] = None + actual_instance: Optional[Union[FedwirePaymentMethod, SepaPaymentMethod, SwiftPaymentMethod]] = None + one_of_schemas: Set[str] = { "FedwirePaymentMethod", "SepaPaymentMethod", "SwiftPaymentMethod" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + discriminator_value_class_map: Dict[str, str] = { + } + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = PaymentMethodsPaymentMethod.model_construct() + error_messages = [] + match = 0 + # validate data type: FedwirePaymentMethod + if not isinstance(v, FedwirePaymentMethod): + error_messages.append(f"Error! Input type `{type(v)}` is not `FedwirePaymentMethod`") + else: + match += 1 + # validate data type: SwiftPaymentMethod + if not isinstance(v, SwiftPaymentMethod): + error_messages.append(f"Error! Input type `{type(v)}` is not `SwiftPaymentMethod`") + else: + match += 1 + # validate data type: SepaPaymentMethod + if not isinstance(v, SepaPaymentMethod): + error_messages.append(f"Error! Input type `{type(v)}` is not `SepaPaymentMethod`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in PaymentMethodsPaymentMethod with oneOf schemas: FedwirePaymentMethod, SepaPaymentMethod, SwiftPaymentMethod. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in PaymentMethodsPaymentMethod with oneOf schemas: FedwirePaymentMethod, SepaPaymentMethod, SwiftPaymentMethod. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into FedwirePaymentMethod + try: + instance.actual_instance = FedwirePaymentMethod.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into SwiftPaymentMethod + try: + instance.actual_instance = SwiftPaymentMethod.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into SepaPaymentMethod + try: + instance.actual_instance = SepaPaymentMethod.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into PaymentMethodsPaymentMethod with oneOf schemas: FedwirePaymentMethod, SepaPaymentMethod, SwiftPaymentMethod. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into PaymentMethodsPaymentMethod with oneOf schemas: FedwirePaymentMethod, SepaPaymentMethod, SwiftPaymentMethod. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], FedwirePaymentMethod, SepaPaymentMethod, SwiftPaymentMethod]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/python/cdp/openapi_client/models/physical_address.py b/python/cdp/openapi_client/models/physical_address.py new file mode 100644 index 000000000..3f69a4170 --- /dev/null +++ b/python/cdp/openapi_client/models/physical_address.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated +from typing import Optional, Set +from typing_extensions import Self + +class PhysicalAddress(BaseModel): + """ + A physical address with standard address components including street, city, state/province, postal code, and country. + """ # noqa: E501 + line1: Optional[StrictStr] = Field(default=None, description="Primary street address.") + line2: Optional[StrictStr] = Field(default=None, description="Secondary address information.") + city: Optional[StrictStr] = Field(default=None, description="City or locality.") + state: Optional[StrictStr] = Field(default=None, description="State, province, or region.") + post_code: Optional[StrictStr] = Field(default=None, description="Postal or ZIP code.", alias="postCode") + country_code: Optional[Annotated[str, Field(min_length=2, strict=True, max_length=2)]] = Field(default=None, description="ISO 3166-1 alpha-2 country code (2 characters). See https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes.", alias="countryCode") + __properties: ClassVar[List[str]] = ["line1", "line2", "city", "state", "postCode", "countryCode"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PhysicalAddress from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PhysicalAddress from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "line1": obj.get("line1"), + "line2": obj.get("line2"), + "city": obj.get("city"), + "state": obj.get("state"), + "postCode": obj.get("postCode"), + "countryCode": obj.get("countryCode") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/send_user_operation_rule.py b/python/cdp/openapi_client/models/send_user_operation_rule.py index eca1b0753..1935f117f 100644 --- a/python/cdp/openapi_client/models/send_user_operation_rule.py +++ b/python/cdp/openapi_client/models/send_user_operation_rule.py @@ -20,7 +20,7 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator from typing import Any, ClassVar, Dict, List -from cdp.openapi_client.models.sign_evm_transaction_criteria_inner import SignEvmTransactionCriteriaInner +from cdp.openapi_client.models.send_evm_transaction_criteria_inner import SendEvmTransactionCriteriaInner from typing import Optional, Set from typing_extensions import Self @@ -30,7 +30,7 @@ class SendUserOperationRule(BaseModel): """ # noqa: E501 action: StrictStr = Field(description="Whether matching the rule will cause the request to be rejected or accepted.") operation: StrictStr = Field(description="The operation to which the rule applies. Every element of the `criteria` array must match the specified operation.") - criteria: List[SignEvmTransactionCriteriaInner] = Field(description="A schema for specifying criteria for the SendUserOperation operation.") + criteria: List[SendEvmTransactionCriteriaInner] = Field(description="A schema for specifying criteria for the SendUserOperation operation.") __properties: ClassVar[List[str]] = ["action", "operation", "criteria"] @field_validator('action') @@ -107,7 +107,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: _obj = cls.model_validate({ "action": obj.get("action"), "operation": obj.get("operation"), - "criteria": [SignEvmTransactionCriteriaInner.from_dict(_item) for _item in obj["criteria"]] if obj.get("criteria") is not None else None + "criteria": [SendEvmTransactionCriteriaInner.from_dict(_item) for _item in obj["criteria"]] if obj.get("criteria") is not None else None }) return _obj diff --git a/python/cdp/openapi_client/models/sepa_details.py b/python/cdp/openapi_client/models/sepa_details.py new file mode 100644 index 000000000..b5169b357 --- /dev/null +++ b/python/cdp/openapi_client/models/sepa_details.py @@ -0,0 +1,109 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing_extensions import Annotated +from typing import Optional, Set +from typing_extensions import Self + +class SepaDetails(BaseModel): + """ + Details specific to SEPA (Single Euro Payments Area) payment methods. + """ # noqa: E501 + asset: StrictStr = Field(description="The asset for this payment method. Always `eur` for SEPA.") + bank_name: StrictStr = Field(description="The name of the bank.", alias="bankName") + iban_last4: Annotated[str, Field(strict=True)] = Field(description="The last 4 characters of the IBAN.", alias="ibanLast4") + bic: Annotated[str, Field(strict=True)] = Field(description="The Bank Identifier Code (BIC) / SWIFT code.") + __properties: ClassVar[List[str]] = ["asset", "bankName", "ibanLast4", "bic"] + + @field_validator('iban_last4') + def iban_last4_validate_regular_expression(cls, value): + """Validates the regular expression""" + if not re.match(r"^[A-Z0-9]{4}$", value): + raise ValueError(r"must validate the regular expression /^[A-Z0-9]{4}$/") + return value + + @field_validator('bic') + def bic_validate_regular_expression(cls, value): + """Validates the regular expression""" + if not re.match(r"^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$", value): + raise ValueError(r"must validate the regular expression /^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$/") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of SepaDetails from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of SepaDetails from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "asset": obj.get("asset"), + "bankName": obj.get("bankName"), + "ibanLast4": obj.get("ibanLast4"), + "bic": obj.get("bic") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/sepa_payment_method.py b/python/cdp/openapi_client/models/sepa_payment_method.py new file mode 100644 index 000000000..1ac21fa04 --- /dev/null +++ b/python/cdp/openapi_client/models/sepa_payment_method.py @@ -0,0 +1,118 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing_extensions import Annotated +from cdp.openapi_client.models.sepa_details import SepaDetails +from typing import Optional, Set +from typing_extensions import Self + +class SepaPaymentMethod(BaseModel): + """ + A SEPA (Single Euro Payments Area) payment method linked to your entity. + """ # noqa: E501 + payment_method_id: Annotated[str, Field(strict=True)] = Field(description="The ID of the Payment Method, which is a UUID prefixed by the string `paymentMethod_`.", alias="paymentMethodId") + active: StrictBool = Field(description="Whether the payment method is active and can be used in transfers. A payment method may be inactive due to verification requirements or entity-level restrictions.") + created_at: datetime = Field(description="The timestamp when the payment method was created.", alias="createdAt") + updated_at: datetime = Field(description="The timestamp when the payment method was last updated.", alias="updatedAt") + payment_rail: StrictStr = Field(description="The payment rail for this payment method.", alias="paymentRail") + sepa: SepaDetails = Field(description="SEPA (Single Euro Payments Area) details.") + __properties: ClassVar[List[str]] = ["paymentMethodId", "active", "createdAt", "updatedAt", "paymentRail", "sepa"] + + @field_validator('payment_method_id') + def payment_method_id_validate_regular_expression(cls, value): + """Validates the regular expression""" + if not re.match(r"^paymentMethod_[a-f0-9\-]{36}$", value): + raise ValueError(r"must validate the regular expression /^paymentMethod_[a-f0-9\-]{36}$/") + return value + + @field_validator('payment_rail') + def payment_rail_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['sepa']): + raise ValueError("must be one of enum values ('sepa')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of SepaPaymentMethod from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of sepa + if self.sepa: + _dict['sepa'] = self.sepa.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of SepaPaymentMethod from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "paymentMethodId": obj.get("paymentMethodId"), + "active": obj.get("active"), + "createdAt": obj.get("createdAt"), + "updatedAt": obj.get("updatedAt"), + "paymentRail": obj.get("paymentRail"), + "sepa": SepaDetails.from_dict(obj["sepa"]) if obj.get("sepa") is not None else None + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/swift_details.py b/python/cdp/openapi_client/models/swift_details.py new file mode 100644 index 000000000..ce5dfdb8b --- /dev/null +++ b/python/cdp/openapi_client/models/swift_details.py @@ -0,0 +1,121 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated +from typing import Optional, Set +from typing_extensions import Self + +class SwiftDetails(BaseModel): + """ + Details specific to SWIFT (international wire) payment methods. + """ # noqa: E501 + asset: StrictStr = Field(description="The asset for this payment method (e.g., `eur`, `gbp`).") + bank_name: StrictStr = Field(description="The name of the bank.", alias="bankName") + account_last4: Annotated[str, Field(strict=True)] = Field(description="The last 4 characters of the account identifier. For IBAN-based accounts (e.g., EU), this is the last 4 characters of the IBAN. For account number-based accounts (e.g., US), this is the last 4 digits of the account number.", alias="accountLast4") + iban_last4: Optional[Annotated[str, Field(strict=True)]] = Field(default=None, description="Deprecated: use `accountLast4` instead. The last 4 characters of the account identifier.", alias="ibanLast4") + bic: Annotated[str, Field(strict=True)] = Field(description="The Bank Identifier Code (BIC) / SWIFT code.") + __properties: ClassVar[List[str]] = ["asset", "bankName", "accountLast4", "ibanLast4", "bic"] + + @field_validator('account_last4') + def account_last4_validate_regular_expression(cls, value): + """Validates the regular expression""" + if not re.match(r"^[A-Z0-9]{4}$", value): + raise ValueError(r"must validate the regular expression /^[A-Z0-9]{4}$/") + return value + + @field_validator('iban_last4') + def iban_last4_validate_regular_expression(cls, value): + """Validates the regular expression""" + if value is None: + return value + + if not re.match(r"^[A-Z0-9]{4}$", value): + raise ValueError(r"must validate the regular expression /^[A-Z0-9]{4}$/") + return value + + @field_validator('bic') + def bic_validate_regular_expression(cls, value): + """Validates the regular expression""" + if not re.match(r"^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$", value): + raise ValueError(r"must validate the regular expression /^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$/") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of SwiftDetails from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of SwiftDetails from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "asset": obj.get("asset"), + "bankName": obj.get("bankName"), + "accountLast4": obj.get("accountLast4"), + "ibanLast4": obj.get("ibanLast4"), + "bic": obj.get("bic") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/swift_payment_method.py b/python/cdp/openapi_client/models/swift_payment_method.py new file mode 100644 index 000000000..747acc77e --- /dev/null +++ b/python/cdp/openapi_client/models/swift_payment_method.py @@ -0,0 +1,118 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing_extensions import Annotated +from cdp.openapi_client.models.swift_details import SwiftDetails +from typing import Optional, Set +from typing_extensions import Self + +class SwiftPaymentMethod(BaseModel): + """ + A SWIFT (international wire) payment method linked to your entity. + """ # noqa: E501 + payment_method_id: Annotated[str, Field(strict=True)] = Field(description="The ID of the Payment Method, which is a UUID prefixed by the string `paymentMethod_`.", alias="paymentMethodId") + active: StrictBool = Field(description="Whether the payment method is active and can be used in transfers. A payment method may be inactive due to verification requirements or entity-level restrictions.") + created_at: datetime = Field(description="The timestamp when the payment method was created.", alias="createdAt") + updated_at: datetime = Field(description="The timestamp when the payment method was last updated.", alias="updatedAt") + payment_rail: StrictStr = Field(description="The payment rail for this payment method.", alias="paymentRail") + swift: SwiftDetails = Field(description="SWIFT (international wire) details.") + __properties: ClassVar[List[str]] = ["paymentMethodId", "active", "createdAt", "updatedAt", "paymentRail", "swift"] + + @field_validator('payment_method_id') + def payment_method_id_validate_regular_expression(cls, value): + """Validates the regular expression""" + if not re.match(r"^paymentMethod_[a-f0-9\-]{36}$", value): + raise ValueError(r"must validate the regular expression /^paymentMethod_[a-f0-9\-]{36}$/") + return value + + @field_validator('payment_rail') + def payment_rail_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['swift']): + raise ValueError("must be one of enum values ('swift')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of SwiftPaymentMethod from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of swift + if self.swift: + _dict['swift'] = self.swift.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of SwiftPaymentMethod from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "paymentMethodId": obj.get("paymentMethodId"), + "active": obj.get("active"), + "createdAt": obj.get("createdAt"), + "updatedAt": obj.get("updatedAt"), + "paymentRail": obj.get("paymentRail"), + "swift": SwiftDetails.from_dict(obj["swift"]) if obj.get("swift") is not None else None + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/transfer.py b/python/cdp/openapi_client/models/transfer.py new file mode 100644 index 000000000..5aaa7aec5 --- /dev/null +++ b/python/cdp/openapi_client/models/transfer.py @@ -0,0 +1,155 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated +from cdp.openapi_client.models.transfer_details import TransferDetails +from cdp.openapi_client.models.transfer_estimate import TransferEstimate +from cdp.openapi_client.models.transfer_exchange_rate import TransferExchangeRate +from cdp.openapi_client.models.transfer_fee import TransferFee +from cdp.openapi_client.models.transfer_source import TransferSource +from cdp.openapi_client.models.transfer_status import TransferStatus +from cdp.openapi_client.models.transfer_target import TransferTarget +from typing import Optional, Set +from typing_extensions import Self + +class Transfer(BaseModel): + """ + A Transfer represents all the information needed to execute a transfer and tracks the lifecycle of a transfer from initiation through completion or failure. + """ # noqa: E501 + transfer_id: Optional[StrictStr] = Field(default=None, description="The ID of the transfer. Required when validateOnly is false.", alias="transferId") + status: Optional[TransferStatus] = None + source: TransferSource + target: TransferTarget + source_amount: Optional[StrictStr] = Field(default=None, description="The amount of the source asset that will be transferred out, as a decimal string in standard unit denomination.", alias="sourceAmount") + source_asset: Optional[Annotated[str, Field(min_length=1, strict=True, max_length=42)]] = Field(default=None, description="The asset symbol of the source amount.", alias="sourceAsset") + target_amount: Optional[StrictStr] = Field(default=None, description="The amount of the target asset that will be received, as a decimal string in standard unit denomination.", alias="targetAmount") + target_asset: Optional[Annotated[str, Field(min_length=1, strict=True, max_length=42)]] = Field(default=None, description="The asset symbol of the target amount.", alias="targetAsset") + exchange_rate: Optional[TransferExchangeRate] = Field(default=None, alias="exchangeRate") + fees: Optional[List[TransferFee]] = Field(default=None, description="The fees associated with this transfer. Different transfer types have different fee structures. **NOTE:** These examples are not exhaustive. Common examples: * **Crypto transfers**: Network fees (gas) paid in the native token * **Fiat conversions**: Processing fees + exchange fees in USD * **Wire transfers**: Wire fees ($15) + processing fees ($5) in USD * **Crypto conversions**: Spread fees paid in the source asset.") + estimate: Optional[TransferEstimate] = None + completed_at: Optional[datetime] = Field(default=None, description="The date and time the transfer was completed.", alias="completedAt") + failure_reason: Optional[StrictStr] = Field(default=None, description="The reason for failure, if the transfer failed. Only present when status is `failed`.", alias="failureReason") + expires_at: Optional[datetime] = Field(default=None, description="The date and time when this transfer will expire if not executed. Only present for `quoted` status. A new transfer must be created to obtain an updated quote after expiration. Required when validateOnly is false.", alias="expiresAt") + executed_at: Optional[datetime] = Field(default=None, description="The date and time the transfer was executed and moved to processing. Only present when status has progressed beyond `quoted`.", alias="executedAt") + created_at: Optional[datetime] = Field(default=None, description="The date and time the transfer was created. Required when validateOnly is false.", alias="createdAt") + updated_at: Optional[datetime] = Field(default=None, description="The date and time the transfer was last updated. Required when validateOnly is false.", alias="updatedAt") + metadata: Optional[Dict[str, Annotated[str, Field(min_length=0, strict=True, max_length=500)]]] = Field(default=None, description="Optional metadata as key-value pairs. Use this to store additional structured information on a resource, such as customer IDs, order references, or any application-specific data. Up to 10 key/value pairs may be provided. Keys and values are both strings. Keys must be ≤ 40 characters; values must be ≤ 500 characters.") + details: Optional[TransferDetails] = None + __properties: ClassVar[List[str]] = ["transferId", "status", "source", "target", "sourceAmount", "sourceAsset", "targetAmount", "targetAsset", "exchangeRate", "fees", "estimate", "completedAt", "failureReason", "expiresAt", "executedAt", "createdAt", "updatedAt", "metadata", "details"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Transfer from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of source + if self.source: + _dict['source'] = self.source.to_dict() + # override the default output from pydantic by calling `to_dict()` of target + if self.target: + _dict['target'] = self.target.to_dict() + # override the default output from pydantic by calling `to_dict()` of exchange_rate + if self.exchange_rate: + _dict['exchangeRate'] = self.exchange_rate.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in fees (list) + _items = [] + if self.fees: + for _item_fees in self.fees: + if _item_fees: + _items.append(_item_fees.to_dict()) + _dict['fees'] = _items + # override the default output from pydantic by calling `to_dict()` of estimate + if self.estimate: + _dict['estimate'] = self.estimate.to_dict() + # override the default output from pydantic by calling `to_dict()` of details + if self.details: + _dict['details'] = self.details.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Transfer from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "transferId": obj.get("transferId"), + "status": obj.get("status"), + "source": TransferSource.from_dict(obj["source"]) if obj.get("source") is not None else None, + "target": TransferTarget.from_dict(obj["target"]) if obj.get("target") is not None else None, + "sourceAmount": obj.get("sourceAmount"), + "sourceAsset": obj.get("sourceAsset"), + "targetAmount": obj.get("targetAmount"), + "targetAsset": obj.get("targetAsset"), + "exchangeRate": TransferExchangeRate.from_dict(obj["exchangeRate"]) if obj.get("exchangeRate") is not None else None, + "fees": [TransferFee.from_dict(_item) for _item in obj["fees"]] if obj.get("fees") is not None else None, + "estimate": TransferEstimate.from_dict(obj["estimate"]) if obj.get("estimate") is not None else None, + "completedAt": obj.get("completedAt"), + "failureReason": obj.get("failureReason"), + "expiresAt": obj.get("expiresAt"), + "executedAt": obj.get("executedAt"), + "createdAt": obj.get("createdAt"), + "updatedAt": obj.get("updatedAt"), + "metadata": obj.get("metadata"), + "details": TransferDetails.from_dict(obj["details"]) if obj.get("details") is not None else None + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/transfer_details.py b/python/cdp/openapi_client/models/transfer_details.py new file mode 100644 index 000000000..7152c98ff --- /dev/null +++ b/python/cdp/openapi_client/models/transfer_details.py @@ -0,0 +1,108 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List, Optional +from cdp.openapi_client.models.deposit_destination_reference import DepositDestinationReference +from cdp.openapi_client.models.transfer_details_onchain_transactions_inner import TransferDetailsOnchainTransactionsInner +from cdp.openapi_client.models.transfer_details_travel_rule import TransferDetailsTravelRule +from typing import Optional, Set +from typing_extensions import Self + +class TransferDetails(BaseModel): + """ + Additional details about the transfer. For example, if the transfer was sent to a deposit destination, the information about that destination will be included in this field. + """ # noqa: E501 + deposit_destination: Optional[DepositDestinationReference] = Field(default=None, alias="depositDestination") + onchain_transactions: Optional[List[TransferDetailsOnchainTransactionsInner]] = Field(default=None, description="The onchain transactions associated with the transfer.", alias="onchainTransactions") + travel_rule: Optional[TransferDetailsTravelRule] = Field(default=None, alias="travelRule") + __properties: ClassVar[List[str]] = ["depositDestination", "onchainTransactions", "travelRule"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TransferDetails from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of deposit_destination + if self.deposit_destination: + _dict['depositDestination'] = self.deposit_destination.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in onchain_transactions (list) + _items = [] + if self.onchain_transactions: + for _item_onchain_transactions in self.onchain_transactions: + if _item_onchain_transactions: + _items.append(_item_onchain_transactions.to_dict()) + _dict['onchainTransactions'] = _items + # override the default output from pydantic by calling `to_dict()` of travel_rule + if self.travel_rule: + _dict['travelRule'] = self.travel_rule.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TransferDetails from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "depositDestination": DepositDestinationReference.from_dict(obj["depositDestination"]) if obj.get("depositDestination") is not None else None, + "onchainTransactions": [TransferDetailsOnchainTransactionsInner.from_dict(_item) for _item in obj["onchainTransactions"]] if obj.get("onchainTransactions") is not None else None, + "travelRule": TransferDetailsTravelRule.from_dict(obj["travelRule"]) if obj.get("travelRule") is not None else None + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/transfer_details_onchain_transactions_inner.py b/python/cdp/openapi_client/models/transfer_details_onchain_transactions_inner.py new file mode 100644 index 000000000..4ac8b0a4e --- /dev/null +++ b/python/cdp/openapi_client/models/transfer_details_onchain_transactions_inner.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from cdp.openapi_client.models.network import Network +from typing import Optional, Set +from typing_extensions import Self + +class TransferDetailsOnchainTransactionsInner(BaseModel): + """ + An onchain transaction associated with the transfer. + """ # noqa: E501 + transaction_hash: StrictStr = Field(description="The transaction hash.", alias="transactionHash") + network: Network + __properties: ClassVar[List[str]] = ["transactionHash", "network"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TransferDetailsOnchainTransactionsInner from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TransferDetailsOnchainTransactionsInner from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "transactionHash": obj.get("transactionHash"), + "network": obj.get("network") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/transfer_details_travel_rule.py b/python/cdp/openapi_client/models/transfer_details_travel_rule.py new file mode 100644 index 000000000..24c7690c0 --- /dev/null +++ b/python/cdp/openapi_client/models/transfer_details_travel_rule.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from cdp.openapi_client.models.travel_rule_status import TravelRuleStatus +from typing import Optional, Set +from typing_extensions import Self + +class TransferDetailsTravelRule(BaseModel): + """ + Travel rule compliance status for deposit transfers. Present when the transfer requires travel rule information. + """ # noqa: E501 + status: Optional[TravelRuleStatus] = None + status_message: Optional[StrictStr] = Field(default=None, description="Additional details about the current travel rule status. For example, when status is `incomplete`, this may indicate the specific missing information required to proceed.", alias="statusMessage") + __properties: ClassVar[List[str]] = ["status", "statusMessage"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TransferDetailsTravelRule from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TransferDetailsTravelRule from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "status": obj.get("status"), + "statusMessage": obj.get("statusMessage") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/transfer_estimate.py b/python/cdp/openapi_client/models/transfer_estimate.py new file mode 100644 index 000000000..d831dff07 --- /dev/null +++ b/python/cdp/openapi_client/models/transfer_estimate.py @@ -0,0 +1,110 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated +from cdp.openapi_client.models.transfer_exchange_rate import TransferExchangeRate +from cdp.openapi_client.models.transfer_fee import TransferFee +from typing import Optional, Set +from typing_extensions import Self + +class TransferEstimate(BaseModel): + """ + A point-in-time snapshot of estimated values for a transfer where exact amounts cannot be locked in at quote time (e.g., when the executed rate is determined at execution time and moves with the market). Present in both pre-execution and post-execution states: * **Quoted state:** top-level fields whose values cannot be guaranteed are absent; `estimate` holds their estimated values. * **Completed state:** top-level fields contain the actual executed values; `estimate` is retained as an immutable audit snapshot of the pre-execution estimate. + """ # noqa: E501 + exchange_rate: Optional[TransferExchangeRate] = Field(default=None, alias="exchangeRate") + target_amount: Optional[StrictStr] = Field(default=None, description="Estimated amount of the target asset that will be received, as a decimal string in standard unit denomination.", alias="targetAmount") + target_asset: Optional[Annotated[str, Field(min_length=1, strict=True, max_length=42)]] = Field(default=None, description="The asset symbol of the estimated target amount.", alias="targetAsset") + fees: Optional[List[TransferFee]] = Field(default=None, description="The fees associated with this transfer. Different transfer types have different fee structures. **NOTE:** These examples are not exhaustive. Common examples: * **Crypto transfers**: Network fees (gas) paid in the native token * **Fiat conversions**: Processing fees + exchange fees in USD * **Wire transfers**: Wire fees ($15) + processing fees ($5) in USD * **Crypto conversions**: Spread fees paid in the source asset.") + estimated_at: datetime = Field(description="The date and time when this estimate was captured.", alias="estimatedAt") + __properties: ClassVar[List[str]] = ["exchangeRate", "targetAmount", "targetAsset", "fees", "estimatedAt"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TransferEstimate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of exchange_rate + if self.exchange_rate: + _dict['exchangeRate'] = self.exchange_rate.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in fees (list) + _items = [] + if self.fees: + for _item_fees in self.fees: + if _item_fees: + _items.append(_item_fees.to_dict()) + _dict['fees'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TransferEstimate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "exchangeRate": TransferExchangeRate.from_dict(obj["exchangeRate"]) if obj.get("exchangeRate") is not None else None, + "targetAmount": obj.get("targetAmount"), + "targetAsset": obj.get("targetAsset"), + "fees": [TransferFee.from_dict(_item) for _item in obj["fees"]] if obj.get("fees") is not None else None, + "estimatedAt": obj.get("estimatedAt") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/transfer_exchange_rate.py b/python/cdp/openapi_client/models/transfer_exchange_rate.py new file mode 100644 index 000000000..525d09ffd --- /dev/null +++ b/python/cdp/openapi_client/models/transfer_exchange_rate.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing_extensions import Annotated +from typing import Optional, Set +from typing_extensions import Self + +class TransferExchangeRate(BaseModel): + """ + Exchange rate information for currency conversion. The rate indicates how much of the target asset is equivalent to one unit of the source asset. + """ # noqa: E501 + source_asset: Annotated[str, Field(min_length=1, strict=True, max_length=42)] = Field(description="The asset being converted from.", alias="sourceAsset") + target_asset: Annotated[str, Field(min_length=1, strict=True, max_length=42)] = Field(description="The asset being converted to.", alias="targetAsset") + rate: StrictStr = Field(description="The exchange rate value as a decimal string. Indicates how many units of the target asset equal one unit of the source asset.") + __properties: ClassVar[List[str]] = ["sourceAsset", "targetAsset", "rate"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TransferExchangeRate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TransferExchangeRate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "sourceAsset": obj.get("sourceAsset"), + "targetAsset": obj.get("targetAsset"), + "rate": obj.get("rate") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/transfer_fee.py b/python/cdp/openapi_client/models/transfer_fee.py new file mode 100644 index 000000000..8481c16f3 --- /dev/null +++ b/python/cdp/openapi_client/models/transfer_fee.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing_extensions import Annotated +from typing import Optional, Set +from typing_extensions import Self + +class TransferFee(BaseModel): + """ + A single fee for a transfer. + """ # noqa: E501 + type: StrictStr = Field(description="The type of the fee, indicating its purpose.") + amount: StrictStr = Field(description="The amount of the fee in units of the asset specified by `asset`.") + asset: Annotated[str, Field(min_length=1, strict=True, max_length=42)] = Field(description="The asset symbol.") + __properties: ClassVar[List[str]] = ["type", "amount", "asset"] + + @field_validator('type') + def type_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['bank', 'conversion', 'network', 'other']): + raise ValueError("must be one of enum values ('bank', 'conversion', 'network', 'other')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TransferFee from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TransferFee from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "type": obj.get("type"), + "amount": obj.get("amount"), + "asset": obj.get("asset") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/transfer_request.py b/python/cdp/openapi_client/models/transfer_request.py new file mode 100644 index 000000000..764581c74 --- /dev/null +++ b/python/cdp/openapi_client/models/transfer_request.py @@ -0,0 +1,127 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated +from cdp.openapi_client.models.create_transfer_source import CreateTransferSource +from cdp.openapi_client.models.transfer_target import TransferTarget +from cdp.openapi_client.models.travel_rule import TravelRule +from typing import Optional, Set +from typing_extensions import Self + +class TransferRequest(BaseModel): + """ + A request to create a transfer. + """ # noqa: E501 + source: CreateTransferSource + target: TransferTarget + amount: StrictStr = Field(description="The amount of the transfer, as a decimal string in standard unit denomination of the asset specified by `asset` (e.g., \"100.00\" for 100 USD, \"0.05\" for 0.05 ETH).") + asset: Annotated[str, Field(min_length=1, strict=True, max_length=42)] = Field(description="The symbol of the asset for the amount. This must be one of the assets of the source or target.") + amount_type: Optional[StrictStr] = Field(default='source', description="Specifies whether the given amount is to be received by the target or taken from the source. - `target`: The transfer `target` receives the exact value specified in `amount`. Fees are added to the amount taken from the transfer `source`. - `source`: The transfer `target` receives the value specified in `amount`, minus any fees. ", alias="amountType") + validate_only: Optional[StrictBool] = Field(default=False, description="If true, validates the transfer without initiating it. If the request is valid, a 2xx will be returned. If the request is invalid, a 4xx error will be returned. The response will include an errorType, for e.g. invalid_target if the specified target cannot receive funds.", alias="validateOnly") + execute: StrictBool = Field(description="Whether to immediately execute the transfer. If false, the transfer will be created in quoted status and must be executed manually via the /execute endpoint.") + metadata: Optional[Dict[str, Annotated[str, Field(min_length=0, strict=True, max_length=500)]]] = Field(default=None, description="Optional metadata as key-value pairs. Use this to store additional structured information on a resource, such as customer IDs, order references, or any application-specific data. Up to 10 key/value pairs may be provided. Keys and values are both strings. Keys must be ≤ 40 characters; values must be ≤ 500 characters.") + travel_rule: Optional[TravelRule] = Field(default=None, alias="travelRule") + __properties: ClassVar[List[str]] = ["source", "target", "amount", "asset", "amountType", "validateOnly", "execute", "metadata", "travelRule"] + + @field_validator('amount_type') + def amount_type_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['target', 'source']): + raise ValueError("must be one of enum values ('target', 'source')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TransferRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of source + if self.source: + _dict['source'] = self.source.to_dict() + # override the default output from pydantic by calling `to_dict()` of target + if self.target: + _dict['target'] = self.target.to_dict() + # override the default output from pydantic by calling `to_dict()` of travel_rule + if self.travel_rule: + _dict['travelRule'] = self.travel_rule.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TransferRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "source": CreateTransferSource.from_dict(obj["source"]) if obj.get("source") is not None else None, + "target": TransferTarget.from_dict(obj["target"]) if obj.get("target") is not None else None, + "amount": obj.get("amount"), + "asset": obj.get("asset"), + "amountType": obj.get("amountType") if obj.get("amountType") is not None else 'source', + "validateOnly": obj.get("validateOnly") if obj.get("validateOnly") is not None else False, + "execute": obj.get("execute"), + "metadata": obj.get("metadata"), + "travelRule": TravelRule.from_dict(obj["travelRule"]) if obj.get("travelRule") is not None else None + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/transfer_source.py b/python/cdp/openapi_client/models/transfer_source.py new file mode 100644 index 000000000..30c8e716f --- /dev/null +++ b/python/cdp/openapi_client/models/transfer_source.py @@ -0,0 +1,166 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from cdp.openapi_client.models.onchain_address import OnchainAddress +from cdp.openapi_client.models.originating_bank_account_us import OriginatingBankAccountUS +from cdp.openapi_client.models.payment_method import PaymentMethod +from cdp.openapi_client.models.transfers_account import TransfersAccount +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +TRANSFERSOURCE_ONE_OF_SCHEMAS = ["OnchainAddress", "OriginatingBankAccountUS", "PaymentMethod", "TransfersAccount"] + +class TransferSource(BaseModel): + """ + The source of the transfer. + """ + # data type: TransfersAccount + oneof_schema_1_validator: Optional[TransfersAccount] = None + # data type: PaymentMethod + oneof_schema_2_validator: Optional[PaymentMethod] = None + # data type: OnchainAddress + oneof_schema_3_validator: Optional[OnchainAddress] = None + # data type: OriginatingBankAccountUS + oneof_schema_4_validator: Optional[OriginatingBankAccountUS] = None + actual_instance: Optional[Union[OnchainAddress, OriginatingBankAccountUS, PaymentMethod, TransfersAccount]] = None + one_of_schemas: Set[str] = { "OnchainAddress", "OriginatingBankAccountUS", "PaymentMethod", "TransfersAccount" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = TransferSource.model_construct() + error_messages = [] + match = 0 + # validate data type: TransfersAccount + if not isinstance(v, TransfersAccount): + error_messages.append(f"Error! Input type `{type(v)}` is not `TransfersAccount`") + else: + match += 1 + # validate data type: PaymentMethod + if not isinstance(v, PaymentMethod): + error_messages.append(f"Error! Input type `{type(v)}` is not `PaymentMethod`") + else: + match += 1 + # validate data type: OnchainAddress + if not isinstance(v, OnchainAddress): + error_messages.append(f"Error! Input type `{type(v)}` is not `OnchainAddress`") + else: + match += 1 + # validate data type: OriginatingBankAccountUS + if not isinstance(v, OriginatingBankAccountUS): + error_messages.append(f"Error! Input type `{type(v)}` is not `OriginatingBankAccountUS`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in TransferSource with oneOf schemas: OnchainAddress, OriginatingBankAccountUS, PaymentMethod, TransfersAccount. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in TransferSource with oneOf schemas: OnchainAddress, OriginatingBankAccountUS, PaymentMethod, TransfersAccount. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into TransfersAccount + try: + instance.actual_instance = TransfersAccount.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into PaymentMethod + try: + instance.actual_instance = PaymentMethod.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into OnchainAddress + try: + instance.actual_instance = OnchainAddress.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into OriginatingBankAccountUS + try: + instance.actual_instance = OriginatingBankAccountUS.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into TransferSource with oneOf schemas: OnchainAddress, OriginatingBankAccountUS, PaymentMethod, TransfersAccount. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into TransferSource with oneOf schemas: OnchainAddress, OriginatingBankAccountUS, PaymentMethod, TransfersAccount. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], OnchainAddress, OriginatingBankAccountUS, PaymentMethod, TransfersAccount]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/python/cdp/openapi_client/models/transfer_status.py b/python/cdp/openapi_client/models/transfer_status.py new file mode 100644 index 000000000..7dd394fd8 --- /dev/null +++ b/python/cdp/openapi_client/models/transfer_status.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class TransferStatus(str, Enum): + """ + The current status of the transfer, indicating what action you need to take next. Required when validateOnly is false. + """ + + """ + allowed enum values + """ + QUOTED = 'quoted' + PROCESSING = 'processing' + COMPLETED = 'completed' + FAILED = 'failed' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of TransferStatus from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/python/cdp/openapi_client/models/transfer_target.py b/python/cdp/openapi_client/models/transfer_target.py new file mode 100644 index 000000000..75e6f97b5 --- /dev/null +++ b/python/cdp/openapi_client/models/transfer_target.py @@ -0,0 +1,166 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from cdp.openapi_client.models.email_instrument import EmailInstrument +from cdp.openapi_client.models.onchain_address import OnchainAddress +from cdp.openapi_client.models.payment_method import PaymentMethod +from cdp.openapi_client.models.transfers_account import TransfersAccount +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +TRANSFERTARGET_ONE_OF_SCHEMAS = ["EmailInstrument", "OnchainAddress", "PaymentMethod", "TransfersAccount"] + +class TransferTarget(BaseModel): + """ + The target of the transfer. + """ + # data type: TransfersAccount + oneof_schema_1_validator: Optional[TransfersAccount] = None + # data type: PaymentMethod + oneof_schema_2_validator: Optional[PaymentMethod] = None + # data type: OnchainAddress + oneof_schema_3_validator: Optional[OnchainAddress] = None + # data type: EmailInstrument + oneof_schema_4_validator: Optional[EmailInstrument] = None + actual_instance: Optional[Union[EmailInstrument, OnchainAddress, PaymentMethod, TransfersAccount]] = None + one_of_schemas: Set[str] = { "EmailInstrument", "OnchainAddress", "PaymentMethod", "TransfersAccount" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = TransferTarget.model_construct() + error_messages = [] + match = 0 + # validate data type: TransfersAccount + if not isinstance(v, TransfersAccount): + error_messages.append(f"Error! Input type `{type(v)}` is not `TransfersAccount`") + else: + match += 1 + # validate data type: PaymentMethod + if not isinstance(v, PaymentMethod): + error_messages.append(f"Error! Input type `{type(v)}` is not `PaymentMethod`") + else: + match += 1 + # validate data type: OnchainAddress + if not isinstance(v, OnchainAddress): + error_messages.append(f"Error! Input type `{type(v)}` is not `OnchainAddress`") + else: + match += 1 + # validate data type: EmailInstrument + if not isinstance(v, EmailInstrument): + error_messages.append(f"Error! Input type `{type(v)}` is not `EmailInstrument`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in TransferTarget with oneOf schemas: EmailInstrument, OnchainAddress, PaymentMethod, TransfersAccount. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in TransferTarget with oneOf schemas: EmailInstrument, OnchainAddress, PaymentMethod, TransfersAccount. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into TransfersAccount + try: + instance.actual_instance = TransfersAccount.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into PaymentMethod + try: + instance.actual_instance = PaymentMethod.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into OnchainAddress + try: + instance.actual_instance = OnchainAddress.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into EmailInstrument + try: + instance.actual_instance = EmailInstrument.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into TransferTarget with oneOf schemas: EmailInstrument, OnchainAddress, PaymentMethod, TransfersAccount. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into TransferTarget with oneOf schemas: EmailInstrument, OnchainAddress, PaymentMethod, TransfersAccount. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], EmailInstrument, OnchainAddress, PaymentMethod, TransfersAccount]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/python/cdp/openapi_client/models/transfers_account.py b/python/cdp/openapi_client/models/transfers_account.py new file mode 100644 index 000000000..74feccb20 --- /dev/null +++ b/python/cdp/openapi_client/models/transfers_account.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing_extensions import Annotated +from typing import Optional, Set +from typing_extensions import Self + +class TransfersAccount(BaseModel): + """ + The Account specific details for the transfer. + """ # noqa: E501 + account_id: StrictStr = Field(description="The ID of the Account.", alias="accountId") + asset: Annotated[str, Field(min_length=1, strict=True, max_length=42)] = Field(description="The symbol of the asset (e.g., eth, usd, usdc, usdt).") + __properties: ClassVar[List[str]] = ["accountId", "asset"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TransfersAccount from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TransfersAccount from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "accountId": obj.get("accountId"), + "asset": obj.get("asset") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/travel_rule.py b/python/cdp/openapi_client/models/travel_rule.py new file mode 100644 index 000000000..7120c5b68 --- /dev/null +++ b/python/cdp/openapi_client/models/travel_rule.py @@ -0,0 +1,102 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictBool +from typing import Any, ClassVar, Dict, List, Optional +from cdp.openapi_client.models.travel_rule_beneficiary import TravelRuleBeneficiary +from cdp.openapi_client.models.travel_rule_originator import TravelRuleOriginator +from typing import Optional, Set +from typing_extensions import Self + +class TravelRule(BaseModel): + """ + Required Travel Rule fields differ by region. These requirements are determined based on which Coinbase entity the customer has signed the service agreement for. + """ # noqa: E501 + is_self: Optional[StrictBool] = Field(default=None, description="Indicates whether the user attests that the receiving wallet belongs to them.", alias="isSelf") + is_intermediary: Optional[StrictBool] = Field(default=None, description="Indicates whether Coinbase is being used as an intermediary Virtual Asset Service Provider (VASP) to send crypto on behalf of your customer. **Background:** The Travel Rule (FATF Recommendation 16) requires VASPs to share originator and beneficiary information for virtual asset transfers. When Coinbase acts as an intermediary, additional Travel Rule data must be provided to satisfy compliance requirements. **Set to `true` when:** - Your organization is a VASP using Coinbase to send crypto **on behalf of your end customer** - In this scenario, Coinbase acts as an intermediary in the transfer chain and handles Travel Rule data exchange with the beneficiary VASP **Set to `false` (or omit) when:** - You are transferring funds directly from your own Coinbase account, where **Coinbase is your primary VASP** rather than an intermediary for another institution **Impact on required fields:** When `isIntermediary` is `true`, you must provide the `originator` object with details about the original sender, including: - Originator name - Originator address - Your VASP information (`virtualAssetServiceProvider` object with `name`, `address`, and `identifier`) ", alias="isIntermediary") + originator: Optional[TravelRuleOriginator] = None + beneficiary: Optional[TravelRuleBeneficiary] = None + __properties: ClassVar[List[str]] = ["isSelf", "isIntermediary", "originator", "beneficiary"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TravelRule from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of originator + if self.originator: + _dict['originator'] = self.originator.to_dict() + # override the default output from pydantic by calling `to_dict()` of beneficiary + if self.beneficiary: + _dict['beneficiary'] = self.beneficiary.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TravelRule from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "isSelf": obj.get("isSelf"), + "isIntermediary": obj.get("isIntermediary"), + "originator": TravelRuleOriginator.from_dict(obj["originator"]) if obj.get("originator") is not None else None, + "beneficiary": TravelRuleBeneficiary.from_dict(obj["beneficiary"]) if obj.get("beneficiary") is not None else None + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/travel_rule_beneficiary.py b/python/cdp/openapi_client/models/travel_rule_beneficiary.py new file mode 100644 index 000000000..ccc61dd1b --- /dev/null +++ b/python/cdp/openapi_client/models/travel_rule_beneficiary.py @@ -0,0 +1,108 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional +from cdp.openapi_client.models.physical_address import PhysicalAddress +from typing import Optional, Set +from typing_extensions import Self + +class TravelRuleBeneficiary(BaseModel): + """ + Beneficiary (receiver) party. + """ # noqa: E501 + financial_institution: Optional[StrictStr] = Field(default=None, description="Name of the financial institution.", alias="financialInstitution") + name: Optional[StrictStr] = Field(default=None, description="Full name of the party.") + address: Optional[PhysicalAddress] = None + wallet_type: Optional[StrictStr] = Field(default=None, description="The type of the beneficiary's wallet.", alias="walletType") + __properties: ClassVar[List[str]] = ["financialInstitution", "name", "address", "walletType"] + + @field_validator('wallet_type') + def wallet_type_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['custodial', 'self_custody']): + raise ValueError("must be one of enum values ('custodial', 'self_custody')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TravelRuleBeneficiary from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of address + if self.address: + _dict['address'] = self.address.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TravelRuleBeneficiary from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "financialInstitution": obj.get("financialInstitution"), + "name": obj.get("name"), + "address": PhysicalAddress.from_dict(obj["address"]) if obj.get("address") is not None else None, + "walletType": obj.get("walletType") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/travel_rule_originator.py b/python/cdp/openapi_client/models/travel_rule_originator.py new file mode 100644 index 000000000..e7bdf6b56 --- /dev/null +++ b/python/cdp/openapi_client/models/travel_rule_originator.py @@ -0,0 +1,102 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from cdp.openapi_client.models.physical_address import PhysicalAddress +from cdp.openapi_client.models.travel_rule_originator_all_of_virtual_asset_service_provider import TravelRuleOriginatorAllOfVirtualAssetServiceProvider +from typing import Optional, Set +from typing_extensions import Self + +class TravelRuleOriginator(BaseModel): + """ + Originator (sender) party. + """ # noqa: E501 + financial_institution: Optional[StrictStr] = Field(default=None, description="Name of the financial institution.", alias="financialInstitution") + name: Optional[StrictStr] = Field(default=None, description="Full name of the party.") + address: Optional[PhysicalAddress] = None + virtual_asset_service_provider: Optional[TravelRuleOriginatorAllOfVirtualAssetServiceProvider] = Field(default=None, alias="virtualAssetServiceProvider") + __properties: ClassVar[List[str]] = ["financialInstitution", "name", "address", "virtualAssetServiceProvider"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TravelRuleOriginator from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of address + if self.address: + _dict['address'] = self.address.to_dict() + # override the default output from pydantic by calling `to_dict()` of virtual_asset_service_provider + if self.virtual_asset_service_provider: + _dict['virtualAssetServiceProvider'] = self.virtual_asset_service_provider.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TravelRuleOriginator from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "financialInstitution": obj.get("financialInstitution"), + "name": obj.get("name"), + "address": PhysicalAddress.from_dict(obj["address"]) if obj.get("address") is not None else None, + "virtualAssetServiceProvider": TravelRuleOriginatorAllOfVirtualAssetServiceProvider.from_dict(obj["virtualAssetServiceProvider"]) if obj.get("virtualAssetServiceProvider") is not None else None + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/travel_rule_originator_all_of_virtual_asset_service_provider.py b/python/cdp/openapi_client/models/travel_rule_originator_all_of_virtual_asset_service_provider.py new file mode 100644 index 000000000..fca5b0d7c --- /dev/null +++ b/python/cdp/openapi_client/models/travel_rule_originator_all_of_virtual_asset_service_provider.py @@ -0,0 +1,96 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from cdp.openapi_client.models.physical_address import PhysicalAddress +from typing import Optional, Set +from typing_extensions import Self + +class TravelRuleOriginatorAllOfVirtualAssetServiceProvider(BaseModel): + """ + Information about the originating Virtual Asset Service Provider (VASP) that handles cryptocurrency or other virtual assets on behalf of customers. + """ # noqa: E501 + name: Optional[StrictStr] = Field(default=None, description="The name of the originating Virtual Asset Service Provider (VASP).") + address: Optional[PhysicalAddress] = Field(default=None, description="The address of the originating Virtual Asset Service Provider (VASP).") + identifier: Optional[StrictStr] = Field(default=None, description="The Legal Entity Identifier of the originating Virtual Asset Service Provider (VASP).") + __properties: ClassVar[List[str]] = ["name", "address", "identifier"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TravelRuleOriginatorAllOfVirtualAssetServiceProvider from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of address + if self.address: + _dict['address'] = self.address.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TravelRuleOriginatorAllOfVirtualAssetServiceProvider from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "address": PhysicalAddress.from_dict(obj["address"]) if obj.get("address") is not None else None, + "identifier": obj.get("identifier") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/travel_rule_party.py b/python/cdp/openapi_client/models/travel_rule_party.py new file mode 100644 index 000000000..c7b120e29 --- /dev/null +++ b/python/cdp/openapi_client/models/travel_rule_party.py @@ -0,0 +1,96 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from cdp.openapi_client.models.physical_address import PhysicalAddress +from typing import Optional, Set +from typing_extensions import Self + +class TravelRuleParty(BaseModel): + """ + Information about a party (originator or beneficiary) for travel rule compliance. + """ # noqa: E501 + financial_institution: Optional[StrictStr] = Field(default=None, description="Name of the financial institution.", alias="financialInstitution") + name: Optional[StrictStr] = Field(default=None, description="Full name of the party.") + address: Optional[PhysicalAddress] = None + __properties: ClassVar[List[str]] = ["financialInstitution", "name", "address"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TravelRuleParty from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of address + if self.address: + _dict['address'] = self.address.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TravelRuleParty from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "financialInstitution": obj.get("financialInstitution"), + "name": obj.get("name"), + "address": PhysicalAddress.from_dict(obj["address"]) if obj.get("address") is not None else None + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/travel_rule_status.py b/python/cdp/openapi_client/models/travel_rule_status.py new file mode 100644 index 000000000..5b8ab8db9 --- /dev/null +++ b/python/cdp/openapi_client/models/travel_rule_status.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class TravelRuleStatus(str, Enum): + """ + The status of a travel rule submission. + """ + + """ + allowed enum values + """ + INCOMPLETE = 'incomplete' + COMPLETED = 'completed' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of TravelRuleStatus from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/python/cdp/openapi_client/models/x402_discovery_resource.py b/python/cdp/openapi_client/models/x402_discovery_resource.py index b9b22c0f9..66a4ce6e1 100644 --- a/python/cdp/openapi_client/models/x402_discovery_resource.py +++ b/python/cdp/openapi_client/models/x402_discovery_resource.py @@ -21,6 +21,7 @@ from datetime import datetime from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated from cdp.openapi_client.models.x402_payment_requirements import X402PaymentRequirements from cdp.openapi_client.models.x402_resource_quality import X402ResourceQuality from cdp.openapi_client.models.x402_version import X402Version @@ -39,7 +40,10 @@ class X402DiscoveryResource(BaseModel): accepts: Optional[List[X402PaymentRequirements]] = Field(default=None, description="Payment requirements accepted by the resource.") extensions: Optional[Dict[str, Any]] = Field(default=None, description="Map of x402 protocol extensions supported by the resource, keyed by extension name.") quality: Optional[X402ResourceQuality] = None - __properties: ClassVar[List[str]] = ["resource", "description", "type", "x402Version", "lastUpdated", "accepts", "extensions", "quality"] + service_name: Optional[StrictStr] = Field(default=None, description="Provider-supplied display name of the service this resource belongs to. This is a free-form label for grouping and presentation only — it is not a stable identifier, and two resources sharing the same `serviceName` are not guaranteed to belong to the same logical service. ", alias="serviceName") + tags: Optional[List[StrictStr]] = Field(default=None, description="Provider-supplied, low-cardinality string labels associated with the resource for client-side filtering and display. Values are free-form (no controlled vocabulary) and case-sensitive. Order is not significant and duplicates are not expected. ") + icon_url: Optional[Annotated[str, Field(min_length=11, strict=True, max_length=2048)]] = Field(default=None, description="URL of a square icon representing the service this resource belongs to. Distinct from a brand logo: this is intended for compact, list-view rendering (favicon-style) and is normalized to a square aspect ratio at ingestion. The image is moderated and re-hosted by Coinbase, so the URL is stable and safe to render directly in clients. Omitted when the provider did not supply an icon, when the supplied icon failed moderation, or when image processing was unavailable at ingestion time. ", alias="iconUrl") + __properties: ClassVar[List[str]] = ["resource", "description", "type", "x402Version", "lastUpdated", "accepts", "extensions", "quality", "serviceName", "tags", "iconUrl"] @field_validator('type') def type_validate_enum(cls, value): @@ -48,6 +52,16 @@ def type_validate_enum(cls, value): raise ValueError("must be one of enum values ('http', 'mcp')") return value + @field_validator('icon_url') + def icon_url_validate_regular_expression(cls, value): + """Validates the regular expression""" + if value is None: + return value + + if not re.match(r"^https?:\/\/.*$", value): + raise ValueError(r"must validate the regular expression /^https?:\/\/.*$/") + return value + model_config = ConfigDict( populate_by_name=True, validate_assignment=True, @@ -116,7 +130,10 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: "lastUpdated": obj.get("lastUpdated"), "accepts": [X402PaymentRequirements.from_dict(_item) for _item in obj["accepts"]] if obj.get("accepts") is not None else None, "extensions": obj.get("extensions"), - "quality": X402ResourceQuality.from_dict(obj["quality"]) if obj.get("quality") is not None else None + "quality": X402ResourceQuality.from_dict(obj["quality"]) if obj.get("quality") is not None else None, + "serviceName": obj.get("serviceName"), + "tags": obj.get("tags"), + "iconUrl": obj.get("iconUrl") }) return _obj diff --git a/python/cdp/openapi_client/test/test_account.py b/python/cdp/openapi_client/test/test_account.py new file mode 100644 index 000000000..be5f30748 --- /dev/null +++ b/python/cdp/openapi_client/test/test_account.py @@ -0,0 +1,62 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.account import Account + +class TestAccount(unittest.TestCase): + """Account unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Account: + """Test Account + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Account` + """ + model = Account() + if include_optional: + return Account( + account_id = 'account_af2937b0-9846-4fe7-bfe9-ccc22d935114', + type = 'prime', + owner = 'entity_af2937b0-9846-4fe7-bfe9-ccc22d935114', + name = 'My Business Account', + created_at = '2023-10-08T14:30:00Z', + updated_at = '2023-10-08T14:30:00Z' + ) + else: + return Account( + account_id = 'account_af2937b0-9846-4fe7-bfe9-ccc22d935114', + type = 'prime', + owner = 'entity_af2937b0-9846-4fe7-bfe9-ccc22d935114', + created_at = '2023-10-08T14:30:00Z', + updated_at = '2023-10-08T14:30:00Z', + ) + """ + + def testAccount(self): + """Test Account""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_account_type.py b/python/cdp/openapi_client/test/test_account_type.py new file mode 100644 index 000000000..5ca7a657c --- /dev/null +++ b/python/cdp/openapi_client/test/test_account_type.py @@ -0,0 +1,34 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.account_type import AccountType + +class TestAccountType(unittest.TestCase): + """AccountType unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testAccountType(self): + """Test AccountType""" + # inst = AccountType() + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_accounts_api.py b/python/cdp/openapi_client/test/test_accounts_api.py new file mode 100644 index 000000000..71786fc39 --- /dev/null +++ b/python/cdp/openapi_client/test/test_accounts_api.py @@ -0,0 +1,67 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.api.accounts_api import AccountsApi + + +class TestAccountsApi(unittest.IsolatedAsyncioTestCase): + """AccountsApi unit test stubs""" + + async def asyncSetUp(self) -> None: + self.api = AccountsApi() + + async def asyncTearDown(self) -> None: + await self.api.api_client.close() + + async def test_create_foundation_account(self) -> None: + """Test case for create_foundation_account + + Create account + """ + pass + + async def test_get_balance_by_asset(self) -> None: + """Test case for get_balance_by_asset + + Get balance for account + """ + pass + + async def test_get_foundation_account_by_id(self) -> None: + """Test case for get_foundation_account_by_id + + Get account + """ + pass + + async def test_list_balances(self) -> None: + """Test case for list_balances + + List balances for account + """ + pass + + async def test_list_foundation_accounts(self) -> None: + """Test case for list_foundation_accounts + + List accounts + """ + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_amount_detail.py b/python/cdp/openapi_client/test/test_amount_detail.py new file mode 100644 index 000000000..c71ebf6d2 --- /dev/null +++ b/python/cdp/openapi_client/test/test_amount_detail.py @@ -0,0 +1,55 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.amount_detail import AmountDetail + +class TestAmountDetail(unittest.TestCase): + """AmountDetail unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> AmountDetail: + """Test AmountDetail + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `AmountDetail` + """ + model = AmountDetail() + if include_optional: + return AmountDetail( + available = '2.5', + total = '3.0' + ) + else: + return AmountDetail( + available = '2.5', + total = '3.0', + ) + """ + + def testAmountDetail(self): + """Test AmountDetail""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_asset_type.py b/python/cdp/openapi_client/test/test_asset_type.py new file mode 100644 index 000000000..d78f50f18 --- /dev/null +++ b/python/cdp/openapi_client/test/test_asset_type.py @@ -0,0 +1,34 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.asset_type import AssetType + +class TestAssetType(unittest.TestCase): + """AssetType unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testAssetType(self): + """Test AssetType""" + # inst = AssetType() + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_balance.py b/python/cdp/openapi_client/test/test_balance.py new file mode 100644 index 000000000..f7d5d6579 --- /dev/null +++ b/python/cdp/openapi_client/test/test_balance.py @@ -0,0 +1,63 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.balance import Balance + +class TestBalance(unittest.TestCase): + """Balance unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Balance: + """Test Balance + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Balance` + """ + model = Balance() + if include_optional: + return Balance( + asset = {symbol=btc, type=crypto, name=Bitcoin, decimals=8}, + amount = { + 'key' : cdp.openapi_client.models.amount_detail.AmountDetail( + available = '2.5', + total = '3.0', ) + } + ) + else: + return Balance( + asset = {symbol=btc, type=crypto, name=Bitcoin, decimals=8}, + amount = { + 'key' : cdp.openapi_client.models.amount_detail.AmountDetail( + available = '2.5', + total = '3.0', ) + }, + ) + """ + + def testBalance(self): + """Test Balance""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_balances.py b/python/cdp/openapi_client/test/test_balances.py new file mode 100644 index 000000000..538446fbf --- /dev/null +++ b/python/cdp/openapi_client/test/test_balances.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.balances import Balances + +class TestBalances(unittest.TestCase): + """Balances unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Balances: + """Test Balances + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Balances` + """ + model = Balances() + if include_optional: + return Balances( + balances = [{asset={symbol=btc, type=crypto, name=Bitcoin, decimals=8}, amount={btc={available=2.5, total=3.0}, usd={available=252705.4, total=303246.48}}}] + ) + else: + return Balances( + balances = [{asset={symbol=btc, type=crypto, name=Bitcoin, decimals=8}, amount={btc={available=2.5, total=3.0}, usd={available=252705.4, total=303246.48}}}], + ) + """ + + def testBalances(self): + """Test Balances""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_balances_asset.py b/python/cdp/openapi_client/test/test_balances_asset.py new file mode 100644 index 000000000..88db662d3 --- /dev/null +++ b/python/cdp/openapi_client/test/test_balances_asset.py @@ -0,0 +1,59 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.balances_asset import BalancesAsset + +class TestBalancesAsset(unittest.TestCase): + """BalancesAsset unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> BalancesAsset: + """Test BalancesAsset + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `BalancesAsset` + """ + model = BalancesAsset() + if include_optional: + return BalancesAsset( + symbol = 'usd', + type = 'crypto', + name = '', + decimals = 56 + ) + else: + return BalancesAsset( + symbol = 'usd', + type = 'crypto', + name = '', + decimals = 56, + ) + """ + + def testBalancesAsset(self): + """Test BalancesAsset""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_create_account_request.py b/python/cdp/openapi_client/test/test_create_account_request.py new file mode 100644 index 000000000..2eba040e1 --- /dev/null +++ b/python/cdp/openapi_client/test/test_create_account_request.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.create_account_request import CreateAccountRequest + +class TestCreateAccountRequest(unittest.TestCase): + """CreateAccountRequest unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> CreateAccountRequest: + """Test CreateAccountRequest + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `CreateAccountRequest` + """ + model = CreateAccountRequest() + if include_optional: + return CreateAccountRequest( + name = 'My Business Account' + ) + else: + return CreateAccountRequest( + ) + """ + + def testCreateAccountRequest(self): + """Test CreateAccountRequest""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_create_crypto_deposit_destination_request.py b/python/cdp/openapi_client/test/test_create_crypto_deposit_destination_request.py new file mode 100644 index 000000000..af425e270 --- /dev/null +++ b/python/cdp/openapi_client/test/test_create_crypto_deposit_destination_request.py @@ -0,0 +1,59 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.create_crypto_deposit_destination_request import CreateCryptoDepositDestinationRequest + +class TestCreateCryptoDepositDestinationRequest(unittest.TestCase): + """CreateCryptoDepositDestinationRequest unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> CreateCryptoDepositDestinationRequest: + """Test CreateCryptoDepositDestinationRequest + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `CreateCryptoDepositDestinationRequest` + """ + model = CreateCryptoDepositDestinationRequest() + if include_optional: + return CreateCryptoDepositDestinationRequest( + account_id = 'account_af2937b0-9846-4fe7-bfe9-ccc22d935114', + type = 'crypto', + target = None, + metadata = {customer_id=cust_12345, order_reference=order-67890}, + crypto = {network=base} + ) + else: + return CreateCryptoDepositDestinationRequest( + account_id = 'account_af2937b0-9846-4fe7-bfe9-ccc22d935114', + type = 'crypto', + crypto = {network=base}, + ) + """ + + def testCreateCryptoDepositDestinationRequest(self): + """Test CreateCryptoDepositDestinationRequest""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_create_deposit_destination_crypto.py b/python/cdp/openapi_client/test/test_create_deposit_destination_crypto.py new file mode 100644 index 000000000..b4311eef6 --- /dev/null +++ b/python/cdp/openapi_client/test/test_create_deposit_destination_crypto.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.create_deposit_destination_crypto import CreateDepositDestinationCrypto + +class TestCreateDepositDestinationCrypto(unittest.TestCase): + """CreateDepositDestinationCrypto unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> CreateDepositDestinationCrypto: + """Test CreateDepositDestinationCrypto + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `CreateDepositDestinationCrypto` + """ + model = CreateDepositDestinationCrypto() + if include_optional: + return CreateDepositDestinationCrypto( + network = 'base' + ) + else: + return CreateDepositDestinationCrypto( + network = 'base', + ) + """ + + def testCreateDepositDestinationCrypto(self): + """Test CreateDepositDestinationCrypto""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_create_deposit_destination_request.py b/python/cdp/openapi_client/test/test_create_deposit_destination_request.py new file mode 100644 index 000000000..37e78111d --- /dev/null +++ b/python/cdp/openapi_client/test/test_create_deposit_destination_request.py @@ -0,0 +1,59 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.create_deposit_destination_request import CreateDepositDestinationRequest + +class TestCreateDepositDestinationRequest(unittest.TestCase): + """CreateDepositDestinationRequest unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> CreateDepositDestinationRequest: + """Test CreateDepositDestinationRequest + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `CreateDepositDestinationRequest` + """ + model = CreateDepositDestinationRequest() + if include_optional: + return CreateDepositDestinationRequest( + account_id = 'account_af2937b0-9846-4fe7-bfe9-ccc22d935114', + type = 'crypto', + target = None, + metadata = {customer_id=cust_12345, order_reference=order-67890}, + crypto = {network=base} + ) + else: + return CreateDepositDestinationRequest( + account_id = 'account_af2937b0-9846-4fe7-bfe9-ccc22d935114', + type = 'crypto', + crypto = {network=base}, + ) + """ + + def testCreateDepositDestinationRequest(self): + """Test CreateDepositDestinationRequest""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_create_deposit_destination_request_base.py b/python/cdp/openapi_client/test/test_create_deposit_destination_request_base.py new file mode 100644 index 000000000..ec70923d8 --- /dev/null +++ b/python/cdp/openapi_client/test/test_create_deposit_destination_request_base.py @@ -0,0 +1,57 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.create_deposit_destination_request_base import CreateDepositDestinationRequestBase + +class TestCreateDepositDestinationRequestBase(unittest.TestCase): + """CreateDepositDestinationRequestBase unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> CreateDepositDestinationRequestBase: + """Test CreateDepositDestinationRequestBase + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `CreateDepositDestinationRequestBase` + """ + model = CreateDepositDestinationRequestBase() + if include_optional: + return CreateDepositDestinationRequestBase( + account_id = 'account_af2937b0-9846-4fe7-bfe9-ccc22d935114', + type = 'crypto', + target = None, + metadata = {customer_id=cust_12345, order_reference=order-67890} + ) + else: + return CreateDepositDestinationRequestBase( + account_id = 'account_af2937b0-9846-4fe7-bfe9-ccc22d935114', + type = 'crypto', + ) + """ + + def testCreateDepositDestinationRequestBase(self): + """Test CreateDepositDestinationRequestBase""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_create_transfer_source.py b/python/cdp/openapi_client/test/test_create_transfer_source.py new file mode 100644 index 000000000..defb99d17 --- /dev/null +++ b/python/cdp/openapi_client/test/test_create_transfer_source.py @@ -0,0 +1,57 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.create_transfer_source import CreateTransferSource + +class TestCreateTransferSource(unittest.TestCase): + """CreateTransferSource unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> CreateTransferSource: + """Test CreateTransferSource + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `CreateTransferSource` + """ + model = CreateTransferSource() + if include_optional: + return CreateTransferSource( + account_id = '', + asset = 'usd', + payment_method_id = '' + ) + else: + return CreateTransferSource( + account_id = '', + asset = 'usd', + payment_method_id = '', + ) + """ + + def testCreateTransferSource(self): + """Test CreateTransferSource""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_crypto_deposit_destination.py b/python/cdp/openapi_client/test/test_crypto_deposit_destination.py new file mode 100644 index 000000000..66c1d5b17 --- /dev/null +++ b/python/cdp/openapi_client/test/test_crypto_deposit_destination.py @@ -0,0 +1,67 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.crypto_deposit_destination import CryptoDepositDestination + +class TestCryptoDepositDestination(unittest.TestCase): + """CryptoDepositDestination unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> CryptoDepositDestination: + """Test CryptoDepositDestination + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `CryptoDepositDestination` + """ + model = CryptoDepositDestination() + if include_optional: + return CryptoDepositDestination( + deposit_destination_id = 'depositDestination_af2937b0-9846-4fe7-bfe9-ccc22d935114', + account_id = 'account_af2937b0-9846-4fe7-bfe9-ccc22d935114', + type = 'crypto', + crypto = {network=base, address=0x742d35Cc6634C0532925a3b844Bc454e4438f44e}, + target = None, + status = 'active', + metadata = {customer_id=cust_12345, order_reference=order-67890}, + created_at = '2023-10-08T14:30:00Z', + updated_at = '2023-10-08T14:30:00Z' + ) + else: + return CryptoDepositDestination( + deposit_destination_id = 'depositDestination_af2937b0-9846-4fe7-bfe9-ccc22d935114', + account_id = 'account_af2937b0-9846-4fe7-bfe9-ccc22d935114', + type = 'crypto', + crypto = {network=base, address=0x742d35Cc6634C0532925a3b844Bc454e4438f44e}, + status = 'active', + created_at = '2023-10-08T14:30:00Z', + updated_at = '2023-10-08T14:30:00Z', + ) + """ + + def testCryptoDepositDestination(self): + """Test CryptoDepositDestination""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_deposit_destination.py b/python/cdp/openapi_client/test/test_deposit_destination.py new file mode 100644 index 000000000..f2f53e084 --- /dev/null +++ b/python/cdp/openapi_client/test/test_deposit_destination.py @@ -0,0 +1,67 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.deposit_destination import DepositDestination + +class TestDepositDestination(unittest.TestCase): + """DepositDestination unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> DepositDestination: + """Test DepositDestination + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `DepositDestination` + """ + model = DepositDestination() + if include_optional: + return DepositDestination( + deposit_destination_id = 'depositDestination_af2937b0-9846-4fe7-bfe9-ccc22d935114', + account_id = 'account_af2937b0-9846-4fe7-bfe9-ccc22d935114', + type = 'crypto', + crypto = {network=base, address=0x742d35Cc6634C0532925a3b844Bc454e4438f44e}, + target = None, + status = 'active', + metadata = {customer_id=cust_12345, order_reference=order-67890}, + created_at = '2023-10-08T14:30:00Z', + updated_at = '2023-10-08T14:30:00Z' + ) + else: + return DepositDestination( + deposit_destination_id = 'depositDestination_af2937b0-9846-4fe7-bfe9-ccc22d935114', + account_id = 'account_af2937b0-9846-4fe7-bfe9-ccc22d935114', + type = 'crypto', + crypto = {network=base, address=0x742d35Cc6634C0532925a3b844Bc454e4438f44e}, + status = 'active', + created_at = '2023-10-08T14:30:00Z', + updated_at = '2023-10-08T14:30:00Z', + ) + """ + + def testDepositDestination(self): + """Test DepositDestination""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_deposit_destination_crypto.py b/python/cdp/openapi_client/test/test_deposit_destination_crypto.py new file mode 100644 index 000000000..e62077f02 --- /dev/null +++ b/python/cdp/openapi_client/test/test_deposit_destination_crypto.py @@ -0,0 +1,55 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.deposit_destination_crypto import DepositDestinationCrypto + +class TestDepositDestinationCrypto(unittest.TestCase): + """DepositDestinationCrypto unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> DepositDestinationCrypto: + """Test DepositDestinationCrypto + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `DepositDestinationCrypto` + """ + model = DepositDestinationCrypto() + if include_optional: + return DepositDestinationCrypto( + network = 'base', + address = '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + ) + else: + return DepositDestinationCrypto( + network = 'base', + address = '0x742d35Cc6634C0532925a3b844Bc454e4438f44e', + ) + """ + + def testDepositDestinationCrypto(self): + """Test DepositDestinationCrypto""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_deposit_destination_reference.py b/python/cdp/openapi_client/test/test_deposit_destination_reference.py new file mode 100644 index 000000000..9e29f5c23 --- /dev/null +++ b/python/cdp/openapi_client/test/test_deposit_destination_reference.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.deposit_destination_reference import DepositDestinationReference + +class TestDepositDestinationReference(unittest.TestCase): + """DepositDestinationReference unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> DepositDestinationReference: + """Test DepositDestinationReference + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `DepositDestinationReference` + """ + model = DepositDestinationReference() + if include_optional: + return DepositDestinationReference( + id = 'depositDestination_af2937b0-9846-4fe7-bfe9-ccc22d935114' + ) + else: + return DepositDestinationReference( + id = 'depositDestination_af2937b0-9846-4fe7-bfe9-ccc22d935114', + ) + """ + + def testDepositDestinationReference(self): + """Test DepositDestinationReference""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_deposit_destination_status.py b/python/cdp/openapi_client/test/test_deposit_destination_status.py new file mode 100644 index 000000000..93845083e --- /dev/null +++ b/python/cdp/openapi_client/test/test_deposit_destination_status.py @@ -0,0 +1,34 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.deposit_destination_status import DepositDestinationStatus + +class TestDepositDestinationStatus(unittest.TestCase): + """DepositDestinationStatus unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testDepositDestinationStatus(self): + """Test DepositDestinationStatus""" + # inst = DepositDestinationStatus() + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_deposit_destination_target.py b/python/cdp/openapi_client/test/test_deposit_destination_target.py new file mode 100644 index 000000000..cd045b3c5 --- /dev/null +++ b/python/cdp/openapi_client/test/test_deposit_destination_target.py @@ -0,0 +1,54 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.deposit_destination_target import DepositDestinationTarget + +class TestDepositDestinationTarget(unittest.TestCase): + """DepositDestinationTarget unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> DepositDestinationTarget: + """Test DepositDestinationTarget + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `DepositDestinationTarget` + """ + model = DepositDestinationTarget() + if include_optional: + return DepositDestinationTarget( + account_id = 'account_af2937b0-9846-4fe7-bfe9-ccc22d935114', + asset = 'usd' + ) + else: + return DepositDestinationTarget( + asset = 'usd', + ) + """ + + def testDepositDestinationTarget(self): + """Test DepositDestinationTarget""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_deposit_destination_target_account.py b/python/cdp/openapi_client/test/test_deposit_destination_target_account.py new file mode 100644 index 000000000..2d1a3dde3 --- /dev/null +++ b/python/cdp/openapi_client/test/test_deposit_destination_target_account.py @@ -0,0 +1,54 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.deposit_destination_target_account import DepositDestinationTargetAccount + +class TestDepositDestinationTargetAccount(unittest.TestCase): + """DepositDestinationTargetAccount unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> DepositDestinationTargetAccount: + """Test DepositDestinationTargetAccount + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `DepositDestinationTargetAccount` + """ + model = DepositDestinationTargetAccount() + if include_optional: + return DepositDestinationTargetAccount( + account_id = 'account_af2937b0-9846-4fe7-bfe9-ccc22d935114', + asset = 'usd' + ) + else: + return DepositDestinationTargetAccount( + asset = 'usd', + ) + """ + + def testDepositDestinationTargetAccount(self): + """Test DepositDestinationTargetAccount""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_deposit_destinations_api.py b/python/cdp/openapi_client/test/test_deposit_destinations_api.py new file mode 100644 index 000000000..26046128a --- /dev/null +++ b/python/cdp/openapi_client/test/test_deposit_destinations_api.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.api.deposit_destinations_api import DepositDestinationsApi + + +class TestDepositDestinationsApi(unittest.IsolatedAsyncioTestCase): + """DepositDestinationsApi unit test stubs""" + + async def asyncSetUp(self) -> None: + self.api = DepositDestinationsApi() + + async def asyncTearDown(self) -> None: + await self.api.api_client.close() + + async def test_create_deposit_destination(self) -> None: + """Test case for create_deposit_destination + + Create deposit destination + """ + pass + + async def test_get_deposit_destination_by_id(self) -> None: + """Test case for get_deposit_destination_by_id + + Get deposit destination + """ + pass + + async def test_list_deposit_destinations(self) -> None: + """Test case for list_deposit_destinations + + List deposit destinations + """ + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_deposit_travel_rule_beneficiary.py b/python/cdp/openapi_client/test/test_deposit_travel_rule_beneficiary.py new file mode 100644 index 000000000..087e724b8 --- /dev/null +++ b/python/cdp/openapi_client/test/test_deposit_travel_rule_beneficiary.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.deposit_travel_rule_beneficiary import DepositTravelRuleBeneficiary + +class TestDepositTravelRuleBeneficiary(unittest.TestCase): + """DepositTravelRuleBeneficiary unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> DepositTravelRuleBeneficiary: + """Test DepositTravelRuleBeneficiary + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `DepositTravelRuleBeneficiary` + """ + model = DepositTravelRuleBeneficiary() + if include_optional: + return DepositTravelRuleBeneficiary( + name = 'Jane Smith' + ) + else: + return DepositTravelRuleBeneficiary( + ) + """ + + def testDepositTravelRuleBeneficiary(self): + """Test DepositTravelRuleBeneficiary""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_deposit_travel_rule_originator.py b/python/cdp/openapi_client/test/test_deposit_travel_rule_originator.py new file mode 100644 index 000000000..783f13c99 --- /dev/null +++ b/python/cdp/openapi_client/test/test_deposit_travel_rule_originator.py @@ -0,0 +1,63 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.deposit_travel_rule_originator import DepositTravelRuleOriginator + +class TestDepositTravelRuleOriginator(unittest.TestCase): + """DepositTravelRuleOriginator unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> DepositTravelRuleOriginator: + """Test DepositTravelRuleOriginator + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `DepositTravelRuleOriginator` + """ + model = DepositTravelRuleOriginator() + if include_optional: + return DepositTravelRuleOriginator( + name = 'John Doe', + address = cdp.openapi_client.models.physical_address.PhysicalAddress( + line1 = '123 Market St', + line2 = 'Suite 400', + city = 'San Francisco', + state = 'CA', + post_code = '94105', + country_code = 'US', ), + wallet_type = 'custodial', + virtual_asset_service_provider = {identifier=5493001KJTIIGC8Y1R17, name=Fidelity Digital Asset Services, LLC}, + personal_id = '123-45-6789', + date_of_birth = {day=15, month=08, year=1990} + ) + else: + return DepositTravelRuleOriginator( + ) + """ + + def testDepositTravelRuleOriginator(self): + """Test DepositTravelRuleOriginator""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_deposit_travel_rule_request.py b/python/cdp/openapi_client/test/test_deposit_travel_rule_request.py new file mode 100644 index 000000000..6e7ed38f6 --- /dev/null +++ b/python/cdp/openapi_client/test/test_deposit_travel_rule_request.py @@ -0,0 +1,54 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.deposit_travel_rule_request import DepositTravelRuleRequest + +class TestDepositTravelRuleRequest(unittest.TestCase): + """DepositTravelRuleRequest unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> DepositTravelRuleRequest: + """Test DepositTravelRuleRequest + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `DepositTravelRuleRequest` + """ + model = DepositTravelRuleRequest() + if include_optional: + return DepositTravelRuleRequest( + originator = {name=John Doe, address={line1=123 Main St, city=San Francisco, state=CA, postCode=94105, countryCode=US}, walletType=custodial, vasp={identifier=5493001KJTIIGC8Y1R17, name=Fidelity Digital Asset Services, LLC}}, + beneficiary = {name=Jane Smith}, + is_self = False + ) + else: + return DepositTravelRuleRequest( + ) + """ + + def testDepositTravelRuleRequest(self): + """Test DepositTravelRuleRequest""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_deposit_travel_rule_response.py b/python/cdp/openapi_client/test/test_deposit_travel_rule_response.py new file mode 100644 index 000000000..a4584c618 --- /dev/null +++ b/python/cdp/openapi_client/test/test_deposit_travel_rule_response.py @@ -0,0 +1,55 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.deposit_travel_rule_response import DepositTravelRuleResponse + +class TestDepositTravelRuleResponse(unittest.TestCase): + """DepositTravelRuleResponse unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> DepositTravelRuleResponse: + """Test DepositTravelRuleResponse + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `DepositTravelRuleResponse` + """ + model = DepositTravelRuleResponse() + if include_optional: + return DepositTravelRuleResponse( + status = 'incomplete', + missing_fields = [originator.address.countryCode], + reason = 'Originator date of birth is required.' + ) + else: + return DepositTravelRuleResponse( + status = 'incomplete', + ) + """ + + def testDepositTravelRuleResponse(self): + """Test DepositTravelRuleResponse""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_deposit_travel_rule_vasp.py b/python/cdp/openapi_client/test/test_deposit_travel_rule_vasp.py new file mode 100644 index 000000000..c2501103f --- /dev/null +++ b/python/cdp/openapi_client/test/test_deposit_travel_rule_vasp.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.deposit_travel_rule_vasp import DepositTravelRuleVasp + +class TestDepositTravelRuleVasp(unittest.TestCase): + """DepositTravelRuleVasp unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> DepositTravelRuleVasp: + """Test DepositTravelRuleVasp + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `DepositTravelRuleVasp` + """ + model = DepositTravelRuleVasp() + if include_optional: + return DepositTravelRuleVasp( + identifier = '5493001KJTIIGC8Y1R17', + name = 'Fidelity Digital Asset Services, LLC' + ) + else: + return DepositTravelRuleVasp( + ) + """ + + def testDepositTravelRuleVasp(self): + """Test DepositTravelRuleVasp""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_email_address.py b/python/cdp/openapi_client/test/test_email_address.py new file mode 100644 index 000000000..f9bf7026a --- /dev/null +++ b/python/cdp/openapi_client/test/test_email_address.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.email_address import EmailAddress + +class TestEmailAddress(unittest.TestCase): + """EmailAddress unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> EmailAddress: + """Test EmailAddress + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `EmailAddress` + """ + model = EmailAddress() + if include_optional: + return EmailAddress( + email = '' + ) + else: + return EmailAddress( + email = '', + ) + """ + + def testEmailAddress(self): + """Test EmailAddress""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_email_instrument.py b/python/cdp/openapi_client/test/test_email_instrument.py new file mode 100644 index 000000000..b3718dda6 --- /dev/null +++ b/python/cdp/openapi_client/test/test_email_instrument.py @@ -0,0 +1,55 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.email_instrument import EmailInstrument + +class TestEmailInstrument(unittest.TestCase): + """EmailInstrument unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> EmailInstrument: + """Test EmailInstrument + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `EmailInstrument` + """ + model = EmailInstrument() + if include_optional: + return EmailInstrument( + email = '', + asset = 'usd' + ) + else: + return EmailInstrument( + email = '', + asset = 'usd', + ) + """ + + def testEmailInstrument(self): + """Test EmailInstrument""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_embedded_wallets_api.py b/python/cdp/openapi_client/test/test_embedded_wallets_api.py index 9ccba6ca3..0ecb226c9 100644 --- a/python/cdp/openapi_client/test/test_embedded_wallets_api.py +++ b/python/cdp/openapi_client/test/test_embedded_wallets_api.py @@ -30,7 +30,7 @@ async def asyncTearDown(self) -> None: async def test_create_delegation_for_end_user_account(self) -> None: """Test case for create_delegation_for_end_user_account - Create account-scoped delegation for an end user account + Create account-scoped delegation for end user """ pass @@ -51,7 +51,7 @@ async def test_get_delegation_for_end_user(self) -> None: async def test_get_delegation_for_end_user_account(self) -> None: """Test case for get_delegation_for_end_user_account - Get account-scoped delegation for an end user account + Get account-scoped delegation for end user """ pass @@ -65,7 +65,7 @@ async def test_revoke_delegation_for_end_user(self) -> None: async def test_revoke_delegation_for_end_user_account(self) -> None: """Test case for revoke_delegation_for_end_user_account - Revoke account-scoped delegation for an end user account + Revoke account-scoped delegation for end user """ pass @@ -79,7 +79,7 @@ async def test_send_evm_asset_with_end_user_account(self) -> None: async def test_send_evm_transaction_with_end_user_account(self) -> None: """Test case for send_evm_transaction_with_end_user_account - Send a transaction with end user EVM account + Send transaction via end user EVM account """ pass @@ -93,49 +93,49 @@ async def test_send_solana_asset_with_end_user_account(self) -> None: async def test_send_solana_transaction_with_end_user_account(self) -> None: """Test case for send_solana_transaction_with_end_user_account - Send a transaction with end user Solana account + Send transaction via end user Solana account """ pass async def test_send_user_operation_with_end_user_account(self) -> None: """Test case for send_user_operation_with_end_user_account - Send a user operation for end user Smart Account + Send user operation for end user Smart Account """ pass async def test_sign_evm_message_with_end_user_account(self) -> None: """Test case for sign_evm_message_with_end_user_account - Sign an EIP-191 message with end user EVM account + Sign EIP-191 message via end user EVM account """ pass async def test_sign_evm_transaction_with_end_user_account(self) -> None: """Test case for sign_evm_transaction_with_end_user_account - Sign a transaction with end user EVM account + Sign transaction via end user EVM account """ pass async def test_sign_evm_typed_data_with_end_user_account(self) -> None: """Test case for sign_evm_typed_data_with_end_user_account - Sign EIP-712 typed data with end user EVM account + Sign EIP-712 typed data via end user EVM account """ pass async def test_sign_solana_message_with_end_user_account(self) -> None: """Test case for sign_solana_message_with_end_user_account - Sign a Base64 encoded message + Sign Base64-encoded message """ pass async def test_sign_solana_transaction_with_end_user_account(self) -> None: """Test case for sign_solana_transaction_with_end_user_account - Sign a transaction with end user Solana account + Sign transaction via end user Solana account """ pass diff --git a/python/cdp/openapi_client/test/test_end_user_accounts_api.py b/python/cdp/openapi_client/test/test_end_user_accounts_api.py index 120a209ed..23e01a406 100644 --- a/python/cdp/openapi_client/test/test_end_user_accounts_api.py +++ b/python/cdp/openapi_client/test/test_end_user_accounts_api.py @@ -30,42 +30,42 @@ async def asyncTearDown(self) -> None: async def test_add_end_user_evm_account(self) -> None: """Test case for add_end_user_evm_account - Add an EVM account to an end user + Add EVM account to end user """ pass async def test_add_end_user_evm_smart_account(self) -> None: """Test case for add_end_user_evm_smart_account - Add an EVM smart account to an end user + Add EVM smart account to end user """ pass async def test_add_end_user_solana_account(self) -> None: """Test case for add_end_user_solana_account - Add a Solana account to an end user + Add Solana account to end user """ pass async def test_create_end_user(self) -> None: """Test case for create_end_user - Create an end user + Create end user """ pass async def test_get_end_user(self) -> None: """Test case for get_end_user - Get an end user + Get end user """ pass async def test_import_end_user(self) -> None: """Test case for import_end_user - Import a private key for an end user + Import end user private key """ pass diff --git a/python/cdp/openapi_client/test/test_evm_accounts_api.py b/python/cdp/openapi_client/test/test_evm_accounts_api.py index 398a1f658..a8a5e6d37 100644 --- a/python/cdp/openapi_client/test/test_evm_accounts_api.py +++ b/python/cdp/openapi_client/test/test_evm_accounts_api.py @@ -30,7 +30,7 @@ async def asyncTearDown(self) -> None: async def test_create_evm_account(self) -> None: """Test case for create_evm_account - Create an EVM account + Create EVM account """ pass @@ -44,42 +44,42 @@ async def test_create_evm_eip7702_delegation(self) -> None: async def test_export_evm_account(self) -> None: """Test case for export_evm_account - Export an EVM account + Export EVM account """ pass async def test_export_evm_account_by_name(self) -> None: """Test case for export_evm_account_by_name - Export an EVM account by name + Export EVM account by name """ pass async def test_get_evm_account(self) -> None: """Test case for get_evm_account - Get an EVM account by address + Get EVM account by address """ pass async def test_get_evm_account_by_name(self) -> None: """Test case for get_evm_account_by_name - Get an EVM account by name + Get EVM account by name """ pass async def test_get_evm_eip7702_delegation_operation_by_id(self) -> None: """Test case for get_evm_eip7702_delegation_operation_by_id - Get EIP-7702 delegation operation for an operationID + Get EIP-7702 delegation operation by ID """ pass async def test_import_evm_account(self) -> None: """Test case for import_evm_account - Import an EVM account + Import EVM account """ pass @@ -93,28 +93,28 @@ async def test_list_evm_accounts(self) -> None: async def test_send_evm_transaction(self) -> None: """Test case for send_evm_transaction - Send a transaction + Send transaction """ pass async def test_sign_evm_hash(self) -> None: """Test case for sign_evm_hash - Sign a hash + Sign hash """ pass async def test_sign_evm_message(self) -> None: """Test case for sign_evm_message - Sign an EIP-191 message + Sign EIP-191 message """ pass async def test_sign_evm_transaction(self) -> None: """Test case for sign_evm_transaction - Sign a transaction + Sign transaction """ pass @@ -128,7 +128,7 @@ async def test_sign_evm_typed_data(self) -> None: async def test_update_evm_account(self) -> None: """Test case for update_evm_account - Update an EVM account + Update EVM account """ pass diff --git a/python/cdp/openapi_client/test/test_evm_smart_accounts_api.py b/python/cdp/openapi_client/test/test_evm_smart_accounts_api.py index f3f695628..95534919d 100644 --- a/python/cdp/openapi_client/test/test_evm_smart_accounts_api.py +++ b/python/cdp/openapi_client/test/test_evm_smart_accounts_api.py @@ -30,35 +30,35 @@ async def asyncTearDown(self) -> None: async def test_create_evm_smart_account(self) -> None: """Test case for create_evm_smart_account - Create a Smart Account + Create Smart Account """ pass async def test_create_spend_permission(self) -> None: """Test case for create_spend_permission - Create a spend permission + Create spend permission """ pass async def test_get_evm_smart_account(self) -> None: """Test case for get_evm_smart_account - Get a Smart Account by address + Get Smart Account by address """ pass async def test_get_evm_smart_account_by_name(self) -> None: """Test case for get_evm_smart_account_by_name - Get a Smart Account by name + Get Smart Account by name """ pass async def test_get_user_operation(self) -> None: """Test case for get_user_operation - Get a user operation + Get user operation """ pass @@ -79,35 +79,35 @@ async def test_list_spend_permissions(self) -> None: async def test_prepare_and_send_user_operation(self) -> None: """Test case for prepare_and_send_user_operation - Prepare and send a user operation for EVM Smart Account + Prepare and send user operation """ pass async def test_prepare_user_operation(self) -> None: """Test case for prepare_user_operation - Prepare a user operation + Prepare user operation """ pass async def test_revoke_spend_permission(self) -> None: """Test case for revoke_spend_permission - Revoke a spend permission + Revoke spend permission """ pass async def test_send_user_operation(self) -> None: """Test case for send_user_operation - Send a user operation + Send user operation """ pass async def test_update_evm_smart_account(self) -> None: """Test case for update_evm_smart_account - Update an EVM Smart Account + Update EVM Smart Account """ pass diff --git a/python/cdp/openapi_client/test/test_evm_swaps_api.py b/python/cdp/openapi_client/test/test_evm_swaps_api.py index 5cd72b385..512b2011b 100644 --- a/python/cdp/openapi_client/test/test_evm_swaps_api.py +++ b/python/cdp/openapi_client/test/test_evm_swaps_api.py @@ -30,14 +30,14 @@ async def asyncTearDown(self) -> None: async def test_create_evm_swap_quote(self) -> None: """Test case for create_evm_swap_quote - Create a swap quote + Create swap quote """ pass async def test_get_evm_swap_price(self) -> None: """Test case for get_evm_swap_price - Get a price estimate for a swap + Get swap price estimate """ pass diff --git a/python/cdp/openapi_client/test/test_fedwire_details.py b/python/cdp/openapi_client/test/test_fedwire_details.py new file mode 100644 index 000000000..fb4d868f9 --- /dev/null +++ b/python/cdp/openapi_client/test/test_fedwire_details.py @@ -0,0 +1,59 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.fedwire_details import FedwireDetails + +class TestFedwireDetails(unittest.TestCase): + """FedwireDetails unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> FedwireDetails: + """Test FedwireDetails + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `FedwireDetails` + """ + model = FedwireDetails() + if include_optional: + return FedwireDetails( + asset = 'usd', + bank_name = 'ALLY BANK', + account_last4 = '1234', + routing_number = '124003116' + ) + else: + return FedwireDetails( + asset = 'usd', + bank_name = 'ALLY BANK', + account_last4 = '1234', + routing_number = '124003116', + ) + """ + + def testFedwireDetails(self): + """Test FedwireDetails""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_fedwire_payment_method.py b/python/cdp/openapi_client/test/test_fedwire_payment_method.py new file mode 100644 index 000000000..5a4b5f679 --- /dev/null +++ b/python/cdp/openapi_client/test/test_fedwire_payment_method.py @@ -0,0 +1,63 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.fedwire_payment_method import FedwirePaymentMethod + +class TestFedwirePaymentMethod(unittest.TestCase): + """FedwirePaymentMethod unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> FedwirePaymentMethod: + """Test FedwirePaymentMethod + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `FedwirePaymentMethod` + """ + model = FedwirePaymentMethod() + if include_optional: + return FedwirePaymentMethod( + payment_method_id = 'paymentMethod_8e03978e-40d5-43e8-bc93-6894a57f9324', + active = True, + created_at = '2024-01-15T10:30:00Z', + updated_at = '2024-01-15T10:30:00Z', + payment_rail = 'fedwire', + fedwire = {asset=usd, bankName=ALLY BANK, accountLast4=1234, routingNumber=124003116} + ) + else: + return FedwirePaymentMethod( + payment_method_id = 'paymentMethod_8e03978e-40d5-43e8-bc93-6894a57f9324', + active = True, + created_at = '2024-01-15T10:30:00Z', + updated_at = '2024-01-15T10:30:00Z', + payment_rail = 'fedwire', + fedwire = {asset=usd, bankName=ALLY BANK, accountLast4=1234, routingNumber=124003116}, + ) + """ + + def testFedwirePaymentMethod(self): + """Test FedwirePaymentMethod""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_list_balances200_response.py b/python/cdp/openapi_client/test/test_list_balances200_response.py new file mode 100644 index 000000000..b0483182a --- /dev/null +++ b/python/cdp/openapi_client/test/test_list_balances200_response.py @@ -0,0 +1,54 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.list_balances200_response import ListBalances200Response + +class TestListBalances200Response(unittest.TestCase): + """ListBalances200Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> ListBalances200Response: + """Test ListBalances200Response + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `ListBalances200Response` + """ + model = ListBalances200Response() + if include_optional: + return ListBalances200Response( + balances = [{asset={symbol=btc, type=crypto, name=Bitcoin, decimals=8}, amount={btc={available=2.5, total=3.0}, usd={available=252705.4, total=303246.48}}}], + next_page_token = 'eyJsYXN0X2lkIjogImFiYzEyMyIsICJ0aW1lc3RhbXAiOiAxNzA3ODIzNzAxfQ==' + ) + else: + return ListBalances200Response( + balances = [{asset={symbol=btc, type=crypto, name=Bitcoin, decimals=8}, amount={btc={available=2.5, total=3.0}, usd={available=252705.4, total=303246.48}}}], + ) + """ + + def testListBalances200Response(self): + """Test ListBalances200Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_list_deposit_destinations200_response.py b/python/cdp/openapi_client/test/test_list_deposit_destinations200_response.py new file mode 100644 index 000000000..856914752 --- /dev/null +++ b/python/cdp/openapi_client/test/test_list_deposit_destinations200_response.py @@ -0,0 +1,58 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.list_deposit_destinations200_response import ListDepositDestinations200Response + +class TestListDepositDestinations200Response(unittest.TestCase): + """ListDepositDestinations200Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> ListDepositDestinations200Response: + """Test ListDepositDestinations200Response + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `ListDepositDestinations200Response` + """ + model = ListDepositDestinations200Response() + if include_optional: + return ListDepositDestinations200Response( + next_page_token = 'eyJsYXN0X2lkIjogImFiYzEyMyIsICJ0aW1lc3RhbXAiOiAxNzA3ODIzNzAxfQ==', + deposit_destinations = [ + null + ] + ) + else: + return ListDepositDestinations200Response( + deposit_destinations = [ + null + ], + ) + """ + + def testListDepositDestinations200Response(self): + """Test ListDepositDestinations200Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_list_foundation_accounts200_response.py b/python/cdp/openapi_client/test/test_list_foundation_accounts200_response.py new file mode 100644 index 000000000..b718ffda7 --- /dev/null +++ b/python/cdp/openapi_client/test/test_list_foundation_accounts200_response.py @@ -0,0 +1,70 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.list_foundation_accounts200_response import ListFoundationAccounts200Response + +class TestListFoundationAccounts200Response(unittest.TestCase): + """ListFoundationAccounts200Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> ListFoundationAccounts200Response: + """Test ListFoundationAccounts200Response + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `ListFoundationAccounts200Response` + """ + model = ListFoundationAccounts200Response() + if include_optional: + return ListFoundationAccounts200Response( + next_page_token = 'eyJsYXN0X2lkIjogImFiYzEyMyIsICJ0aW1lc3RhbXAiOiAxNzA3ODIzNzAxfQ==', + accounts = [ + cdp.openapi_client.models.account.Account( + account_id = 'account_af2937b0-9846-4fe7-bfe9-ccc22d935114', + type = 'prime', + owner = 'entity_af2937b0-9846-4fe7-bfe9-ccc22d935114', + name = 'My Business Account', + created_at = '2023-10-08T14:30:00Z', + updated_at = '2023-10-08T14:30:00Z', ) + ] + ) + else: + return ListFoundationAccounts200Response( + accounts = [ + cdp.openapi_client.models.account.Account( + account_id = 'account_af2937b0-9846-4fe7-bfe9-ccc22d935114', + type = 'prime', + owner = 'entity_af2937b0-9846-4fe7-bfe9-ccc22d935114', + name = 'My Business Account', + created_at = '2023-10-08T14:30:00Z', + updated_at = '2023-10-08T14:30:00Z', ) + ], + ) + """ + + def testListFoundationAccounts200Response(self): + """Test ListFoundationAccounts200Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_list_payment_methods200_response.py b/python/cdp/openapi_client/test/test_list_payment_methods200_response.py new file mode 100644 index 000000000..93fc38683 --- /dev/null +++ b/python/cdp/openapi_client/test/test_list_payment_methods200_response.py @@ -0,0 +1,58 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.list_payment_methods200_response import ListPaymentMethods200Response + +class TestListPaymentMethods200Response(unittest.TestCase): + """ListPaymentMethods200Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> ListPaymentMethods200Response: + """Test ListPaymentMethods200Response + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `ListPaymentMethods200Response` + """ + model = ListPaymentMethods200Response() + if include_optional: + return ListPaymentMethods200Response( + next_page_token = 'eyJsYXN0X2lkIjogImFiYzEyMyIsICJ0aW1lc3RhbXAiOiAxNzA3ODIzNzAxfQ==', + payment_methods = [ + null + ] + ) + else: + return ListPaymentMethods200Response( + payment_methods = [ + null + ], + ) + """ + + def testListPaymentMethods200Response(self): + """Test ListPaymentMethods200Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_list_transfers200_response.py b/python/cdp/openapi_client/test/test_list_transfers200_response.py new file mode 100644 index 000000000..5be97f2c1 --- /dev/null +++ b/python/cdp/openapi_client/test/test_list_transfers200_response.py @@ -0,0 +1,96 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.list_transfers200_response import ListTransfers200Response + +class TestListTransfers200Response(unittest.TestCase): + """ListTransfers200Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> ListTransfers200Response: + """Test ListTransfers200Response + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `ListTransfers200Response` + """ + model = ListTransfers200Response() + if include_optional: + return ListTransfers200Response( + next_page_token = 'eyJsYXN0X2lkIjogImFiYzEyMyIsICJ0aW1lc3RhbXAiOiAxNzA3ODIzNzAxfQ==', + transfers = [ + cdp.openapi_client.models.transfer.Transfer( + transfer_id = 'transfer_af2937b0-9846-4fe7-bfe9-ccc22d935114', + status = 'quoted', + source = {}, + target = {}, + source_amount = '103.50', + source_asset = usd, + target_amount = '100.00', + target_asset = usdc, + exchange_rate = {sourceAsset=usd, targetAsset=usdc, rate=1}, + fees = [{type=bank, amount=20, asset=usd}, {type=conversion, amount=1.00, asset=usdc}, {type=network, amount=0.01, asset=usdc}], + estimate = {exchangeRate={sourceAsset=usdc, targetAsset=eur, rate=0.85}, targetAmount=85.00, targetAsset=eur, fees=[{type=conversion, amount=0.01, asset=usdc}], estimatedAt=2023-10-08T14:30:00Z}, + completed_at = '2025-01-01T00:05:00Z', + failure_reason = 'Insufficient balance to complete this transfer.', + expires_at = '2025-01-01T00:15:00Z', + executed_at = '2025-01-01T00:01:30Z', + created_at = '2025-01-01T00:00:00Z', + updated_at = '2025-01-01T00:00:00Z', + metadata = {customer_id=cust_12345, order_reference=order-67890}, + details = {depositDestination={id=depositDestination_af2937b0-9846-4fe7-bfe9-ccc22d935114}, onchainTransactions=[{transactionHash=0x363cd3b3d4f49497cf5076150cd709307b90e9fc897fdd623546ea7b9313cecb, network=base}]}, ) + ] + ) + else: + return ListTransfers200Response( + transfers = [ + cdp.openapi_client.models.transfer.Transfer( + transfer_id = 'transfer_af2937b0-9846-4fe7-bfe9-ccc22d935114', + status = 'quoted', + source = {}, + target = {}, + source_amount = '103.50', + source_asset = usd, + target_amount = '100.00', + target_asset = usdc, + exchange_rate = {sourceAsset=usd, targetAsset=usdc, rate=1}, + fees = [{type=bank, amount=20, asset=usd}, {type=conversion, amount=1.00, asset=usdc}, {type=network, amount=0.01, asset=usdc}], + estimate = {exchangeRate={sourceAsset=usdc, targetAsset=eur, rate=0.85}, targetAmount=85.00, targetAsset=eur, fees=[{type=conversion, amount=0.01, asset=usdc}], estimatedAt=2023-10-08T14:30:00Z}, + completed_at = '2025-01-01T00:05:00Z', + failure_reason = 'Insufficient balance to complete this transfer.', + expires_at = '2025-01-01T00:15:00Z', + executed_at = '2025-01-01T00:01:30Z', + created_at = '2025-01-01T00:00:00Z', + updated_at = '2025-01-01T00:00:00Z', + metadata = {customer_id=cust_12345, order_reference=order-67890}, + details = {depositDestination={id=depositDestination_af2937b0-9846-4fe7-bfe9-ccc22d935114}, onchainTransactions=[{transactionHash=0x363cd3b3d4f49497cf5076150cd709307b90e9fc897fdd623546ea7b9313cecb, network=base}]}, ) + ], + ) + """ + + def testListTransfers200Response(self): + """Test ListTransfers200Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_network.py b/python/cdp/openapi_client/test/test_network.py new file mode 100644 index 000000000..d7b616c09 --- /dev/null +++ b/python/cdp/openapi_client/test/test_network.py @@ -0,0 +1,34 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.network import Network + +class TestNetwork(unittest.TestCase): + """Network unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testNetwork(self): + """Test Network""" + # inst = Network() + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_onchain_address.py b/python/cdp/openapi_client/test/test_onchain_address.py new file mode 100644 index 000000000..621ec3fc4 --- /dev/null +++ b/python/cdp/openapi_client/test/test_onchain_address.py @@ -0,0 +1,58 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.onchain_address import OnchainAddress + +class TestOnchainAddress(unittest.TestCase): + """OnchainAddress unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> OnchainAddress: + """Test OnchainAddress + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `OnchainAddress` + """ + model = OnchainAddress() + if include_optional: + return OnchainAddress( + address = '0x742d35Cc6634C0532925a3b844Bc454e4438f44e', + network = 'base', + destination_tag = '', + asset = 'usd' + ) + else: + return OnchainAddress( + address = '0x742d35Cc6634C0532925a3b844Bc454e4438f44e', + network = 'base', + asset = 'usd', + ) + """ + + def testOnchainAddress(self): + """Test OnchainAddress""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_originating_bank_account_us.py b/python/cdp/openapi_client/test/test_originating_bank_account_us.py new file mode 100644 index 000000000..ee004b904 --- /dev/null +++ b/python/cdp/openapi_client/test/test_originating_bank_account_us.py @@ -0,0 +1,57 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.originating_bank_account_us import OriginatingBankAccountUS + +class TestOriginatingBankAccountUS(unittest.TestCase): + """OriginatingBankAccountUS unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> OriginatingBankAccountUS: + """Test OriginatingBankAccountUS + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `OriginatingBankAccountUS` + """ + model = OriginatingBankAccountUS() + if include_optional: + return OriginatingBankAccountUS( + bank_name = 'Citibank, N.A.', + account_last4 = '6789', + currency = 'usd' + ) + else: + return OriginatingBankAccountUS( + bank_name = 'Citibank, N.A.', + account_last4 = '6789', + currency = 'usd', + ) + """ + + def testOriginatingBankAccountUS(self): + """Test OriginatingBankAccountUS""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_payment_method.py b/python/cdp/openapi_client/test/test_payment_method.py new file mode 100644 index 000000000..b2e39f564 --- /dev/null +++ b/python/cdp/openapi_client/test/test_payment_method.py @@ -0,0 +1,55 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.payment_method import PaymentMethod + +class TestPaymentMethod(unittest.TestCase): + """PaymentMethod unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> PaymentMethod: + """Test PaymentMethod + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `PaymentMethod` + """ + model = PaymentMethod() + if include_optional: + return PaymentMethod( + payment_method_id = '', + asset = 'usd' + ) + else: + return PaymentMethod( + payment_method_id = '', + asset = 'usd', + ) + """ + + def testPaymentMethod(self): + """Test PaymentMethod""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_payment_method_base.py b/python/cdp/openapi_client/test/test_payment_method_base.py new file mode 100644 index 000000000..2d1dd8523 --- /dev/null +++ b/python/cdp/openapi_client/test/test_payment_method_base.py @@ -0,0 +1,59 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.payment_method_base import PaymentMethodBase + +class TestPaymentMethodBase(unittest.TestCase): + """PaymentMethodBase unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> PaymentMethodBase: + """Test PaymentMethodBase + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `PaymentMethodBase` + """ + model = PaymentMethodBase() + if include_optional: + return PaymentMethodBase( + payment_method_id = 'paymentMethod_8e03978e-40d5-43e8-bc93-6894a57f9324', + active = True, + created_at = '2024-01-15T10:30:00Z', + updated_at = '2024-01-15T10:30:00Z' + ) + else: + return PaymentMethodBase( + payment_method_id = 'paymentMethod_8e03978e-40d5-43e8-bc93-6894a57f9324', + active = True, + created_at = '2024-01-15T10:30:00Z', + updated_at = '2024-01-15T10:30:00Z', + ) + """ + + def testPaymentMethodBase(self): + """Test PaymentMethodBase""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_payment_methods_api.py b/python/cdp/openapi_client/test/test_payment_methods_api.py new file mode 100644 index 000000000..622bd5040 --- /dev/null +++ b/python/cdp/openapi_client/test/test_payment_methods_api.py @@ -0,0 +1,46 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.api.payment_methods_api import PaymentMethodsApi + + +class TestPaymentMethodsApi(unittest.IsolatedAsyncioTestCase): + """PaymentMethodsApi unit test stubs""" + + async def asyncSetUp(self) -> None: + self.api = PaymentMethodsApi() + + async def asyncTearDown(self) -> None: + await self.api.api_client.close() + + async def test_get_payment_method(self) -> None: + """Test case for get_payment_method + + Get payment method + """ + pass + + async def test_list_payment_methods(self) -> None: + """Test case for list_payment_methods + + List payment methods + """ + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_payment_methods_payment_method.py b/python/cdp/openapi_client/test/test_payment_methods_payment_method.py new file mode 100644 index 000000000..597fe65a2 --- /dev/null +++ b/python/cdp/openapi_client/test/test_payment_methods_payment_method.py @@ -0,0 +1,67 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.payment_methods_payment_method import PaymentMethodsPaymentMethod + +class TestPaymentMethodsPaymentMethod(unittest.TestCase): + """PaymentMethodsPaymentMethod unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> PaymentMethodsPaymentMethod: + """Test PaymentMethodsPaymentMethod + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `PaymentMethodsPaymentMethod` + """ + model = PaymentMethodsPaymentMethod() + if include_optional: + return PaymentMethodsPaymentMethod( + payment_method_id = 'paymentMethod_8e03978e-40d5-43e8-bc93-6894a57f9324', + active = True, + created_at = '2024-01-15T10:30:00Z', + updated_at = '2024-01-15T10:30:00Z', + payment_rail = 'sepa', + fedwire = {asset=usd, bankName=ALLY BANK, accountLast4=1234, routingNumber=124003116}, + swift = {asset=eur, bankName=Deutsche Bank, accountLast4=5678, ibanLast4=5678, bic=DEUTDEFF}, + sepa = {asset=eur, bankName=ING Bank, ibanLast4=4300, bic=INGBNL2A} + ) + else: + return PaymentMethodsPaymentMethod( + payment_method_id = 'paymentMethod_8e03978e-40d5-43e8-bc93-6894a57f9324', + active = True, + created_at = '2024-01-15T10:30:00Z', + updated_at = '2024-01-15T10:30:00Z', + payment_rail = 'sepa', + fedwire = {asset=usd, bankName=ALLY BANK, accountLast4=1234, routingNumber=124003116}, + swift = {asset=eur, bankName=Deutsche Bank, accountLast4=5678, ibanLast4=5678, bic=DEUTDEFF}, + sepa = {asset=eur, bankName=ING Bank, ibanLast4=4300, bic=INGBNL2A}, + ) + """ + + def testPaymentMethodsPaymentMethod(self): + """Test PaymentMethodsPaymentMethod""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_physical_address.py b/python/cdp/openapi_client/test/test_physical_address.py new file mode 100644 index 000000000..2ad601418 --- /dev/null +++ b/python/cdp/openapi_client/test/test_physical_address.py @@ -0,0 +1,57 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.physical_address import PhysicalAddress + +class TestPhysicalAddress(unittest.TestCase): + """PhysicalAddress unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> PhysicalAddress: + """Test PhysicalAddress + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `PhysicalAddress` + """ + model = PhysicalAddress() + if include_optional: + return PhysicalAddress( + line1 = '123 Market St', + line2 = 'Suite 400', + city = 'San Francisco', + state = 'CA', + post_code = '94105', + country_code = 'US' + ) + else: + return PhysicalAddress( + ) + """ + + def testPhysicalAddress(self): + """Test PhysicalAddress""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_policy_engine_api.py b/python/cdp/openapi_client/test/test_policy_engine_api.py index 41b2d94cc..664ce2c92 100644 --- a/python/cdp/openapi_client/test/test_policy_engine_api.py +++ b/python/cdp/openapi_client/test/test_policy_engine_api.py @@ -30,21 +30,21 @@ async def asyncTearDown(self) -> None: async def test_create_policy(self) -> None: """Test case for create_policy - Create a policy + Create policy """ pass async def test_delete_policy(self) -> None: """Test case for delete_policy - Delete a policy + Delete policy """ pass async def test_get_policy_by_id(self) -> None: """Test case for get_policy_by_id - Get a policy by ID + Get policy by ID """ pass @@ -58,7 +58,7 @@ async def test_list_policies(self) -> None: async def test_update_policy(self) -> None: """Test case for update_policy - Update a policy + Update policy """ pass diff --git a/python/cdp/openapi_client/test/test_sepa_details.py b/python/cdp/openapi_client/test/test_sepa_details.py new file mode 100644 index 000000000..c400b2ef8 --- /dev/null +++ b/python/cdp/openapi_client/test/test_sepa_details.py @@ -0,0 +1,59 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.sepa_details import SepaDetails + +class TestSepaDetails(unittest.TestCase): + """SepaDetails unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> SepaDetails: + """Test SepaDetails + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `SepaDetails` + """ + model = SepaDetails() + if include_optional: + return SepaDetails( + asset = 'eur', + bank_name = 'ING Bank', + iban_last4 = '4300', + bic = 'INGBNL2A' + ) + else: + return SepaDetails( + asset = 'eur', + bank_name = 'ING Bank', + iban_last4 = '4300', + bic = 'INGBNL2A', + ) + """ + + def testSepaDetails(self): + """Test SepaDetails""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_sepa_payment_method.py b/python/cdp/openapi_client/test/test_sepa_payment_method.py new file mode 100644 index 000000000..5a2e84636 --- /dev/null +++ b/python/cdp/openapi_client/test/test_sepa_payment_method.py @@ -0,0 +1,63 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.sepa_payment_method import SepaPaymentMethod + +class TestSepaPaymentMethod(unittest.TestCase): + """SepaPaymentMethod unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> SepaPaymentMethod: + """Test SepaPaymentMethod + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `SepaPaymentMethod` + """ + model = SepaPaymentMethod() + if include_optional: + return SepaPaymentMethod( + payment_method_id = 'paymentMethod_8e03978e-40d5-43e8-bc93-6894a57f9324', + active = True, + created_at = '2024-01-15T10:30:00Z', + updated_at = '2024-01-15T10:30:00Z', + payment_rail = 'sepa', + sepa = {asset=eur, bankName=ING Bank, ibanLast4=4300, bic=INGBNL2A} + ) + else: + return SepaPaymentMethod( + payment_method_id = 'paymentMethod_8e03978e-40d5-43e8-bc93-6894a57f9324', + active = True, + created_at = '2024-01-15T10:30:00Z', + updated_at = '2024-01-15T10:30:00Z', + payment_rail = 'sepa', + sepa = {asset=eur, bankName=ING Bank, ibanLast4=4300, bic=INGBNL2A}, + ) + """ + + def testSepaPaymentMethod(self): + """Test SepaPaymentMethod""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_solana_accounts_api.py b/python/cdp/openapi_client/test/test_solana_accounts_api.py index 352f8b4a3..ed8a5dd0d 100644 --- a/python/cdp/openapi_client/test/test_solana_accounts_api.py +++ b/python/cdp/openapi_client/test/test_solana_accounts_api.py @@ -30,77 +30,77 @@ async def asyncTearDown(self) -> None: async def test_create_solana_account(self) -> None: """Test case for create_solana_account - Create a Solana account + Create Solana account """ pass async def test_export_solana_account(self) -> None: """Test case for export_solana_account - Export an Solana account + Export Solana account """ pass async def test_export_solana_account_by_name(self) -> None: """Test case for export_solana_account_by_name - Export a Solana account by name + Export Solana account by name """ pass async def test_get_solana_account(self) -> None: """Test case for get_solana_account - Get a Solana account by address + Get Solana account by address """ pass async def test_get_solana_account_by_name(self) -> None: """Test case for get_solana_account_by_name - Get a Solana account by name + Get Solana account by name """ pass async def test_import_solana_account(self) -> None: """Test case for import_solana_account - Import a Solana account + Import Solana account """ pass async def test_list_solana_accounts(self) -> None: """Test case for list_solana_accounts - List Solana accounts or get account by name + List Solana accounts """ pass async def test_send_solana_transaction(self) -> None: """Test case for send_solana_transaction - Send a Solana transaction + Send Solana transaction """ pass async def test_sign_solana_message(self) -> None: """Test case for sign_solana_message - Sign a message + Sign message """ pass async def test_sign_solana_transaction(self) -> None: """Test case for sign_solana_transaction - Sign a transaction + Sign transaction """ pass async def test_update_solana_account(self) -> None: """Test case for update_solana_account - Update a Solana account + Update Solana account """ pass diff --git a/python/cdp/openapi_client/test/test_sqlapi_api.py b/python/cdp/openapi_client/test/test_sqlapi_api.py index 448794f4e..b5773f72f 100644 --- a/python/cdp/openapi_client/test/test_sqlapi_api.py +++ b/python/cdp/openapi_client/test/test_sqlapi_api.py @@ -37,7 +37,7 @@ async def test_get_sql_grammar(self) -> None: async def test_get_sql_schema(self) -> None: """Test case for get_sql_schema - Get schemas details + Get schema details """ pass diff --git a/python/cdp/openapi_client/test/test_swift_details.py b/python/cdp/openapi_client/test/test_swift_details.py new file mode 100644 index 000000000..9b3976fcf --- /dev/null +++ b/python/cdp/openapi_client/test/test_swift_details.py @@ -0,0 +1,60 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.swift_details import SwiftDetails + +class TestSwiftDetails(unittest.TestCase): + """SwiftDetails unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> SwiftDetails: + """Test SwiftDetails + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `SwiftDetails` + """ + model = SwiftDetails() + if include_optional: + return SwiftDetails( + asset = 'eur', + bank_name = 'Deutsche Bank', + account_last4 = '5678', + iban_last4 = '5678', + bic = 'DEUTDEFF' + ) + else: + return SwiftDetails( + asset = 'eur', + bank_name = 'Deutsche Bank', + account_last4 = '5678', + bic = 'DEUTDEFF', + ) + """ + + def testSwiftDetails(self): + """Test SwiftDetails""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_swift_payment_method.py b/python/cdp/openapi_client/test/test_swift_payment_method.py new file mode 100644 index 000000000..cb6097465 --- /dev/null +++ b/python/cdp/openapi_client/test/test_swift_payment_method.py @@ -0,0 +1,63 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.swift_payment_method import SwiftPaymentMethod + +class TestSwiftPaymentMethod(unittest.TestCase): + """SwiftPaymentMethod unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> SwiftPaymentMethod: + """Test SwiftPaymentMethod + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `SwiftPaymentMethod` + """ + model = SwiftPaymentMethod() + if include_optional: + return SwiftPaymentMethod( + payment_method_id = 'paymentMethod_8e03978e-40d5-43e8-bc93-6894a57f9324', + active = True, + created_at = '2024-01-15T10:30:00Z', + updated_at = '2024-01-15T10:30:00Z', + payment_rail = 'swift', + swift = {asset=eur, bankName=Deutsche Bank, accountLast4=5678, ibanLast4=5678, bic=DEUTDEFF} + ) + else: + return SwiftPaymentMethod( + payment_method_id = 'paymentMethod_8e03978e-40d5-43e8-bc93-6894a57f9324', + active = True, + created_at = '2024-01-15T10:30:00Z', + updated_at = '2024-01-15T10:30:00Z', + payment_rail = 'swift', + swift = {asset=eur, bankName=Deutsche Bank, accountLast4=5678, ibanLast4=5678, bic=DEUTDEFF}, + ) + """ + + def testSwiftPaymentMethod(self): + """Test SwiftPaymentMethod""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_transfer.py b/python/cdp/openapi_client/test/test_transfer.py new file mode 100644 index 000000000..1421b8a97 --- /dev/null +++ b/python/cdp/openapi_client/test/test_transfer.py @@ -0,0 +1,72 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.transfer import Transfer + +class TestTransfer(unittest.TestCase): + """Transfer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Transfer: + """Test Transfer + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Transfer` + """ + model = Transfer() + if include_optional: + return Transfer( + transfer_id = 'transfer_af2937b0-9846-4fe7-bfe9-ccc22d935114', + status = 'quoted', + source = {}, + target = {}, + source_amount = '103.50', + source_asset = 'usd', + target_amount = '100.00', + target_asset = 'usd', + exchange_rate = {sourceAsset=usd, targetAsset=usdc, rate=1}, + fees = [{type=bank, amount=20, asset=usd}, {type=conversion, amount=1.00, asset=usdc}, {type=network, amount=0.01, asset=usdc}], + estimate = {exchangeRate={sourceAsset=usdc, targetAsset=eur, rate=0.85}, targetAmount=85.00, targetAsset=eur, fees=[{type=conversion, amount=0.01, asset=usdc}], estimatedAt=2023-10-08T14:30:00Z}, + completed_at = '2025-01-01T00:05:00Z', + failure_reason = 'Insufficient balance to complete this transfer.', + expires_at = '2025-01-01T00:15:00Z', + executed_at = '2025-01-01T00:01:30Z', + created_at = '2025-01-01T00:00:00Z', + updated_at = '2025-01-01T00:00:00Z', + metadata = {customer_id=cust_12345, order_reference=order-67890}, + details = {depositDestination={id=depositDestination_af2937b0-9846-4fe7-bfe9-ccc22d935114}, onchainTransactions=[{transactionHash=0x363cd3b3d4f49497cf5076150cd709307b90e9fc897fdd623546ea7b9313cecb, network=base}]} + ) + else: + return Transfer( + source = {}, + target = {}, + ) + """ + + def testTransfer(self): + """Test Transfer""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_transfer_details.py b/python/cdp/openapi_client/test/test_transfer_details.py new file mode 100644 index 000000000..3cac06a75 --- /dev/null +++ b/python/cdp/openapi_client/test/test_transfer_details.py @@ -0,0 +1,54 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.transfer_details import TransferDetails + +class TestTransferDetails(unittest.TestCase): + """TransferDetails unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TransferDetails: + """Test TransferDetails + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TransferDetails` + """ + model = TransferDetails() + if include_optional: + return TransferDetails( + deposit_destination = {id=depositDestination_af2937b0-9846-4fe7-bfe9-ccc22d935114}, + onchain_transactions = [{transactionHash=0x363cd3b3d4f49497cf5076150cd709307b90e9fc897fdd623546ea7b9313cecb, network=base}], + travel_rule = {status=incomplete, statusMessage=Originator date of birth is required.} + ) + else: + return TransferDetails( + ) + """ + + def testTransferDetails(self): + """Test TransferDetails""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_transfer_details_onchain_transactions_inner.py b/python/cdp/openapi_client/test/test_transfer_details_onchain_transactions_inner.py new file mode 100644 index 000000000..fca1ac185 --- /dev/null +++ b/python/cdp/openapi_client/test/test_transfer_details_onchain_transactions_inner.py @@ -0,0 +1,55 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.transfer_details_onchain_transactions_inner import TransferDetailsOnchainTransactionsInner + +class TestTransferDetailsOnchainTransactionsInner(unittest.TestCase): + """TransferDetailsOnchainTransactionsInner unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TransferDetailsOnchainTransactionsInner: + """Test TransferDetailsOnchainTransactionsInner + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TransferDetailsOnchainTransactionsInner` + """ + model = TransferDetailsOnchainTransactionsInner() + if include_optional: + return TransferDetailsOnchainTransactionsInner( + transaction_hash = '0x363cd3b3d4f49497cf5076150cd709307b90e9fc897fdd623546ea7b9313cecb', + network = 'base' + ) + else: + return TransferDetailsOnchainTransactionsInner( + transaction_hash = '0x363cd3b3d4f49497cf5076150cd709307b90e9fc897fdd623546ea7b9313cecb', + network = 'base', + ) + """ + + def testTransferDetailsOnchainTransactionsInner(self): + """Test TransferDetailsOnchainTransactionsInner""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_transfer_details_travel_rule.py b/python/cdp/openapi_client/test/test_transfer_details_travel_rule.py new file mode 100644 index 000000000..03a3ee320 --- /dev/null +++ b/python/cdp/openapi_client/test/test_transfer_details_travel_rule.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.transfer_details_travel_rule import TransferDetailsTravelRule + +class TestTransferDetailsTravelRule(unittest.TestCase): + """TransferDetailsTravelRule unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TransferDetailsTravelRule: + """Test TransferDetailsTravelRule + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TransferDetailsTravelRule` + """ + model = TransferDetailsTravelRule() + if include_optional: + return TransferDetailsTravelRule( + status = 'incomplete', + status_message = 'Originator date of birth is required.' + ) + else: + return TransferDetailsTravelRule( + ) + """ + + def testTransferDetailsTravelRule(self): + """Test TransferDetailsTravelRule""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_transfer_estimate.py b/python/cdp/openapi_client/test/test_transfer_estimate.py new file mode 100644 index 000000000..bde376f87 --- /dev/null +++ b/python/cdp/openapi_client/test/test_transfer_estimate.py @@ -0,0 +1,57 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.transfer_estimate import TransferEstimate + +class TestTransferEstimate(unittest.TestCase): + """TransferEstimate unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TransferEstimate: + """Test TransferEstimate + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TransferEstimate` + """ + model = TransferEstimate() + if include_optional: + return TransferEstimate( + exchange_rate = {sourceAsset=usd, targetAsset=usdc, rate=1}, + target_amount = '85.00', + target_asset = 'usd', + fees = [{type=bank, amount=20, asset=usd}, {type=conversion, amount=1.00, asset=usdc}, {type=network, amount=0.01, asset=usdc}], + estimated_at = '2023-10-08T14:30:00Z' + ) + else: + return TransferEstimate( + estimated_at = '2023-10-08T14:30:00Z', + ) + """ + + def testTransferEstimate(self): + """Test TransferEstimate""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_transfer_exchange_rate.py b/python/cdp/openapi_client/test/test_transfer_exchange_rate.py new file mode 100644 index 000000000..6ca3b1fbf --- /dev/null +++ b/python/cdp/openapi_client/test/test_transfer_exchange_rate.py @@ -0,0 +1,57 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.transfer_exchange_rate import TransferExchangeRate + +class TestTransferExchangeRate(unittest.TestCase): + """TransferExchangeRate unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TransferExchangeRate: + """Test TransferExchangeRate + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TransferExchangeRate` + """ + model = TransferExchangeRate() + if include_optional: + return TransferExchangeRate( + source_asset = 'usd', + target_asset = 'usd', + rate = '1' + ) + else: + return TransferExchangeRate( + source_asset = 'usd', + target_asset = 'usd', + rate = '1', + ) + """ + + def testTransferExchangeRate(self): + """Test TransferExchangeRate""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_transfer_fee.py b/python/cdp/openapi_client/test/test_transfer_fee.py new file mode 100644 index 000000000..0339e03b9 --- /dev/null +++ b/python/cdp/openapi_client/test/test_transfer_fee.py @@ -0,0 +1,57 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.transfer_fee import TransferFee + +class TestTransferFee(unittest.TestCase): + """TransferFee unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TransferFee: + """Test TransferFee + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TransferFee` + """ + model = TransferFee() + if include_optional: + return TransferFee( + type = 'network', + amount = '1500000', + asset = 'usd' + ) + else: + return TransferFee( + type = 'network', + amount = '1500000', + asset = 'usd', + ) + """ + + def testTransferFee(self): + """Test TransferFee""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_transfer_request.py b/python/cdp/openapi_client/test/test_transfer_request.py new file mode 100644 index 000000000..326093da5 --- /dev/null +++ b/python/cdp/openapi_client/test/test_transfer_request.py @@ -0,0 +1,65 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.transfer_request import TransferRequest + +class TestTransferRequest(unittest.TestCase): + """TransferRequest unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TransferRequest: + """Test TransferRequest + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TransferRequest` + """ + model = TransferRequest() + if include_optional: + return TransferRequest( + source = {}, + target = {}, + amount = '100.00', + asset = 'usd', + amount_type = 'source', + validate_only = False, + execute = True, + metadata = {customer_id=cust_12345, order_reference=order-67890}, + travel_rule = {isSelf=false, isIntermediary=true, originator={name=John Doe, address={line1=123 Main St, line2=Unit 201, city=Luxembourg, postCode=L-1234, countryCode=LU}, financialInstitution=PayPal, Inc., vasp={name=Fidelity Digital Asset Services, LLC, address={line1=123 Market St, line2=Suite 400, city=San Francisco, state=California, postCode=94105, countryCode=US}, identifier=5493001KJTIIGC8Y1R17}}, beneficiary={name=Jane Smith, address={line1=456 Oak Ave, city=Paris, postCode=75001, countryCode=FR}, walletType=custodial}} + ) + else: + return TransferRequest( + source = {}, + target = {}, + amount = '100.00', + asset = 'usd', + execute = True, + ) + """ + + def testTransferRequest(self): + """Test TransferRequest""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_transfer_source.py b/python/cdp/openapi_client/test/test_transfer_source.py new file mode 100644 index 000000000..4cdba68bd --- /dev/null +++ b/python/cdp/openapi_client/test/test_transfer_source.py @@ -0,0 +1,68 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.transfer_source import TransferSource + +class TestTransferSource(unittest.TestCase): + """TransferSource unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TransferSource: + """Test TransferSource + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TransferSource` + """ + model = TransferSource() + if include_optional: + return TransferSource( + account_id = '', + asset = 'usd', + payment_method_id = '', + address = '0x742d35Cc6634C0532925a3b844Bc454e4438f44e', + network = 'base', + destination_tag = '', + bank_name = 'Citibank, N.A.', + account_last4 = '6789', + currency = 'usd' + ) + else: + return TransferSource( + account_id = '', + asset = 'usd', + payment_method_id = '', + address = '0x742d35Cc6634C0532925a3b844Bc454e4438f44e', + network = 'base', + bank_name = 'Citibank, N.A.', + account_last4 = '6789', + currency = 'usd', + ) + """ + + def testTransferSource(self): + """Test TransferSource""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_transfer_status.py b/python/cdp/openapi_client/test/test_transfer_status.py new file mode 100644 index 000000000..4ce6b9743 --- /dev/null +++ b/python/cdp/openapi_client/test/test_transfer_status.py @@ -0,0 +1,34 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.transfer_status import TransferStatus + +class TestTransferStatus(unittest.TestCase): + """TransferStatus unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testTransferStatus(self): + """Test TransferStatus""" + # inst = TransferStatus() + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_transfer_target.py b/python/cdp/openapi_client/test/test_transfer_target.py new file mode 100644 index 000000000..90170e953 --- /dev/null +++ b/python/cdp/openapi_client/test/test_transfer_target.py @@ -0,0 +1,64 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.transfer_target import TransferTarget + +class TestTransferTarget(unittest.TestCase): + """TransferTarget unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TransferTarget: + """Test TransferTarget + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TransferTarget` + """ + model = TransferTarget() + if include_optional: + return TransferTarget( + account_id = '', + asset = 'usd', + payment_method_id = '', + address = '0x742d35Cc6634C0532925a3b844Bc454e4438f44e', + network = 'base', + destination_tag = '', + email = '' + ) + else: + return TransferTarget( + account_id = '', + asset = 'usd', + payment_method_id = '', + address = '0x742d35Cc6634C0532925a3b844Bc454e4438f44e', + network = 'base', + email = '', + ) + """ + + def testTransferTarget(self): + """Test TransferTarget""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_transfers_account.py b/python/cdp/openapi_client/test/test_transfers_account.py new file mode 100644 index 000000000..5290f24fe --- /dev/null +++ b/python/cdp/openapi_client/test/test_transfers_account.py @@ -0,0 +1,55 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.transfers_account import TransfersAccount + +class TestTransfersAccount(unittest.TestCase): + """TransfersAccount unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TransfersAccount: + """Test TransfersAccount + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TransfersAccount` + """ + model = TransfersAccount() + if include_optional: + return TransfersAccount( + account_id = '', + asset = 'usd' + ) + else: + return TransfersAccount( + account_id = '', + asset = 'usd', + ) + """ + + def testTransfersAccount(self): + """Test TransfersAccount""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_transfers_api.py b/python/cdp/openapi_client/test/test_transfers_api.py new file mode 100644 index 000000000..640560536 --- /dev/null +++ b/python/cdp/openapi_client/test/test_transfers_api.py @@ -0,0 +1,67 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.api.transfers_api import TransfersApi + + +class TestTransfersApi(unittest.IsolatedAsyncioTestCase): + """TransfersApi unit test stubs""" + + async def asyncSetUp(self) -> None: + self.api = TransfersApi() + + async def asyncTearDown(self) -> None: + await self.api.api_client.close() + + async def test_create_transfer(self) -> None: + """Test case for create_transfer + + Create transfer + """ + pass + + async def test_execute_fund_transfer(self) -> None: + """Test case for execute_fund_transfer + + Execute transfer + """ + pass + + async def test_get_transfer_by_id(self) -> None: + """Test case for get_transfer_by_id + + Get transfer + """ + pass + + async def test_list_transfers(self) -> None: + """Test case for list_transfers + + List transfers + """ + pass + + async def test_submit_deposit_travel_rule(self) -> None: + """Test case for submit_deposit_travel_rule + + Submit deposit travel rule information + """ + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_travel_rule.py b/python/cdp/openapi_client/test/test_travel_rule.py new file mode 100644 index 000000000..cbd05c0d4 --- /dev/null +++ b/python/cdp/openapi_client/test/test_travel_rule.py @@ -0,0 +1,55 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.travel_rule import TravelRule + +class TestTravelRule(unittest.TestCase): + """TravelRule unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TravelRule: + """Test TravelRule + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TravelRule` + """ + model = TravelRule() + if include_optional: + return TravelRule( + is_self = True, + is_intermediary = True, + originator = None, + beneficiary = None + ) + else: + return TravelRule( + ) + """ + + def testTravelRule(self): + """Test TravelRule""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_travel_rule_beneficiary.py b/python/cdp/openapi_client/test/test_travel_rule_beneficiary.py new file mode 100644 index 000000000..4239b39ed --- /dev/null +++ b/python/cdp/openapi_client/test/test_travel_rule_beneficiary.py @@ -0,0 +1,61 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.travel_rule_beneficiary import TravelRuleBeneficiary + +class TestTravelRuleBeneficiary(unittest.TestCase): + """TravelRuleBeneficiary unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TravelRuleBeneficiary: + """Test TravelRuleBeneficiary + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TravelRuleBeneficiary` + """ + model = TravelRuleBeneficiary() + if include_optional: + return TravelRuleBeneficiary( + financial_institution = 'PayPal, Inc.', + name = 'John Doe', + address = cdp.openapi_client.models.physical_address.PhysicalAddress( + line1 = '123 Market St', + line2 = 'Suite 400', + city = 'San Francisco', + state = 'CA', + post_code = '94105', + country_code = 'US', ), + wallet_type = 'custodial' + ) + else: + return TravelRuleBeneficiary( + ) + """ + + def testTravelRuleBeneficiary(self): + """Test TravelRuleBeneficiary""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_travel_rule_originator.py b/python/cdp/openapi_client/test/test_travel_rule_originator.py new file mode 100644 index 000000000..e36342721 --- /dev/null +++ b/python/cdp/openapi_client/test/test_travel_rule_originator.py @@ -0,0 +1,70 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.travel_rule_originator import TravelRuleOriginator + +class TestTravelRuleOriginator(unittest.TestCase): + """TravelRuleOriginator unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TravelRuleOriginator: + """Test TravelRuleOriginator + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TravelRuleOriginator` + """ + model = TravelRuleOriginator() + if include_optional: + return TravelRuleOriginator( + financial_institution = 'PayPal, Inc.', + name = 'John Doe', + address = cdp.openapi_client.models.physical_address.PhysicalAddress( + line1 = '123 Market St', + line2 = 'Suite 400', + city = 'San Francisco', + state = 'CA', + post_code = '94105', + country_code = 'US', ), + virtual_asset_service_provider = cdp.openapi_client.models.travel_rule_originator_all_of_virtual_asset_service_provider.TravelRuleOriginator_allOf_virtualAssetServiceProvider( + name = 'Fidelity Digital Asset Services, LLC', + address = cdp.openapi_client.models.physical_address.PhysicalAddress( + line1 = '123 Market St', + line2 = 'Suite 400', + city = 'San Francisco', + state = 'CA', + post_code = '94105', + country_code = 'US', ), + identifier = '5493001KJTIIGC8Y1R17', ) + ) + else: + return TravelRuleOriginator( + ) + """ + + def testTravelRuleOriginator(self): + """Test TravelRuleOriginator""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_travel_rule_originator_all_of_virtual_asset_service_provider.py b/python/cdp/openapi_client/test/test_travel_rule_originator_all_of_virtual_asset_service_provider.py new file mode 100644 index 000000000..39b576579 --- /dev/null +++ b/python/cdp/openapi_client/test/test_travel_rule_originator_all_of_virtual_asset_service_provider.py @@ -0,0 +1,60 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.travel_rule_originator_all_of_virtual_asset_service_provider import TravelRuleOriginatorAllOfVirtualAssetServiceProvider + +class TestTravelRuleOriginatorAllOfVirtualAssetServiceProvider(unittest.TestCase): + """TravelRuleOriginatorAllOfVirtualAssetServiceProvider unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TravelRuleOriginatorAllOfVirtualAssetServiceProvider: + """Test TravelRuleOriginatorAllOfVirtualAssetServiceProvider + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TravelRuleOriginatorAllOfVirtualAssetServiceProvider` + """ + model = TravelRuleOriginatorAllOfVirtualAssetServiceProvider() + if include_optional: + return TravelRuleOriginatorAllOfVirtualAssetServiceProvider( + name = 'Fidelity Digital Asset Services, LLC', + address = cdp.openapi_client.models.physical_address.PhysicalAddress( + line1 = '123 Market St', + line2 = 'Suite 400', + city = 'San Francisco', + state = 'CA', + post_code = '94105', + country_code = 'US', ), + identifier = '5493001KJTIIGC8Y1R17' + ) + else: + return TravelRuleOriginatorAllOfVirtualAssetServiceProvider( + ) + """ + + def testTravelRuleOriginatorAllOfVirtualAssetServiceProvider(self): + """Test TravelRuleOriginatorAllOfVirtualAssetServiceProvider""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_travel_rule_party.py b/python/cdp/openapi_client/test/test_travel_rule_party.py new file mode 100644 index 000000000..9c89c22e6 --- /dev/null +++ b/python/cdp/openapi_client/test/test_travel_rule_party.py @@ -0,0 +1,60 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.travel_rule_party import TravelRuleParty + +class TestTravelRuleParty(unittest.TestCase): + """TravelRuleParty unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TravelRuleParty: + """Test TravelRuleParty + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TravelRuleParty` + """ + model = TravelRuleParty() + if include_optional: + return TravelRuleParty( + financial_institution = 'PayPal, Inc.', + name = 'John Doe', + address = cdp.openapi_client.models.physical_address.PhysicalAddress( + line1 = '123 Market St', + line2 = 'Suite 400', + city = 'San Francisco', + state = 'CA', + post_code = '94105', + country_code = 'US', ) + ) + else: + return TravelRuleParty( + ) + """ + + def testTravelRuleParty(self): + """Test TravelRuleParty""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_travel_rule_status.py b/python/cdp/openapi_client/test/test_travel_rule_status.py new file mode 100644 index 000000000..2801ae933 --- /dev/null +++ b/python/cdp/openapi_client/test/test_travel_rule_status.py @@ -0,0 +1,34 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.travel_rule_status import TravelRuleStatus + +class TestTravelRuleStatus(unittest.TestCase): + """TravelRuleStatus unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testTravelRuleStatus(self): + """Test TravelRuleStatus""" + # inst = TravelRuleStatus() + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_webhooks_api.py b/python/cdp/openapi_client/test/test_webhooks_api.py index 4fd79a6c5..90749b2dc 100644 --- a/python/cdp/openapi_client/test/test_webhooks_api.py +++ b/python/cdp/openapi_client/test/test_webhooks_api.py @@ -44,7 +44,7 @@ async def test_delete_webhook_subscription(self) -> None: async def test_get_webhook_subscription(self) -> None: """Test case for get_webhook_subscription - Get webhook subscription details + Get webhook subscription """ pass diff --git a/python/cdp/openapi_client/test/test_x402_discovery_merchant_response.py b/python/cdp/openapi_client/test/test_x402_discovery_merchant_response.py index 9e6f93d60..2b399d73e 100644 --- a/python/cdp/openapi_client/test/test_x402_discovery_merchant_response.py +++ b/python/cdp/openapi_client/test/test_x402_discovery_merchant_response.py @@ -38,14 +38,14 @@ def make_instance(self, include_optional) -> X402DiscoveryMerchantResponse: return X402DiscoveryMerchantResponse( x402_version = 2, pay_to = '0x742d35Cc6634C0532925a3b844Bc454e4438f44e', - resources = [{resource=https://api.example.com/premium/data, description=Premium API access for data analysis., type=http, x402Version=2, lastUpdated=2024-01-15T10:30:00Z, accepts=[{scheme=exact, network=eip155:8453, amount=1000000, payTo=0x742d35Cc6634C0532925a3b844Bc454e4438f44e, asset=0x036CbD53842c5426634e7929541eC2318f3dCF7e, maxTimeoutSeconds=60}], extensions={bazaar={info={input={type=http, method=POST}}, schema={}}}, quality={l30DaysTotalCalls=42, l30DaysUniquePayers=15, lastCalledAt=2024-01-15T10:30:00Z}}], + resources = [{resource=https://api.example.com/premium/data, description=Premium API access for data analysis., type=http, x402Version=2, lastUpdated=2024-01-15T10:30:00Z, accepts=[{scheme=exact, network=eip155:8453, amount=1000000, payTo=0x742d35Cc6634C0532925a3b844Bc454e4438f44e, asset=0x036CbD53842c5426634e7929541eC2318f3dCF7e, maxTimeoutSeconds=60}], extensions={bazaar={info={input={type=http, method=POST}}, schema={}}}, quality={l30DaysTotalCalls=42, l30DaysUniquePayers=15, lastCalledAt=2024-01-15T10:30:00Z}, serviceName=Premium Data API, tags=[data, analytics], iconUrl=https://res.cloudinary.com/bdb-prod/image/upload/...}], pagination = {limit=20, offset=0, total=10} ) else: return X402DiscoveryMerchantResponse( x402_version = 2, pay_to = '0x742d35Cc6634C0532925a3b844Bc454e4438f44e', - resources = [{resource=https://api.example.com/premium/data, description=Premium API access for data analysis., type=http, x402Version=2, lastUpdated=2024-01-15T10:30:00Z, accepts=[{scheme=exact, network=eip155:8453, amount=1000000, payTo=0x742d35Cc6634C0532925a3b844Bc454e4438f44e, asset=0x036CbD53842c5426634e7929541eC2318f3dCF7e, maxTimeoutSeconds=60}], extensions={bazaar={info={input={type=http, method=POST}}, schema={}}}, quality={l30DaysTotalCalls=42, l30DaysUniquePayers=15, lastCalledAt=2024-01-15T10:30:00Z}}], + resources = [{resource=https://api.example.com/premium/data, description=Premium API access for data analysis., type=http, x402Version=2, lastUpdated=2024-01-15T10:30:00Z, accepts=[{scheme=exact, network=eip155:8453, amount=1000000, payTo=0x742d35Cc6634C0532925a3b844Bc454e4438f44e, asset=0x036CbD53842c5426634e7929541eC2318f3dCF7e, maxTimeoutSeconds=60}], extensions={bazaar={info={input={type=http, method=POST}}, schema={}}}, quality={l30DaysTotalCalls=42, l30DaysUniquePayers=15, lastCalledAt=2024-01-15T10:30:00Z}, serviceName=Premium Data API, tags=[data, analytics], iconUrl=https://res.cloudinary.com/bdb-prod/image/upload/...}], pagination = {limit=20, offset=0, total=10}, ) """ diff --git a/python/cdp/openapi_client/test/test_x402_discovery_resource.py b/python/cdp/openapi_client/test/test_x402_discovery_resource.py index fed780b78..00d624878 100644 --- a/python/cdp/openapi_client/test/test_x402_discovery_resource.py +++ b/python/cdp/openapi_client/test/test_x402_discovery_resource.py @@ -43,7 +43,10 @@ def make_instance(self, include_optional) -> X402DiscoveryResource: last_updated = '2024-01-15T10:30:00Z', accepts = [{scheme=exact, network=eip155:8453, amount=1000000, payTo=0x742d35Cc6634C0532925a3b844Bc454e4438f44e, asset=0x036CbD53842c5426634e7929541eC2318f3dCF7e, maxTimeoutSeconds=60}], extensions = {bazaar={info={input={type=http, method=GET}}, schema={}}}, - quality = {l30DaysTotalCalls=42, l30DaysUniquePayers=15, lastCalledAt=2024-01-15T10:30:00Z} + quality = {l30DaysTotalCalls=42, l30DaysUniquePayers=15, lastCalledAt=2024-01-15T10:30:00Z}, + service_name = 'Weather API', + tags = [weather, data], + icon_url = 'https://example.com' ) else: return X402DiscoveryResource( diff --git a/python/cdp/openapi_client/test/test_x402_discovery_resources_response.py b/python/cdp/openapi_client/test/test_x402_discovery_resources_response.py index 4034fbc2b..74b57b0ee 100644 --- a/python/cdp/openapi_client/test/test_x402_discovery_resources_response.py +++ b/python/cdp/openapi_client/test/test_x402_discovery_resources_response.py @@ -37,13 +37,13 @@ def make_instance(self, include_optional) -> X402DiscoveryResourcesResponse: if include_optional: return X402DiscoveryResourcesResponse( x402_version = 2, - items = [], + items = [{resource=https://api.example.com/weather/forecast, description=Real-time weather forecast data., type=http, x402Version=2, lastUpdated=2024-01-15T10:30:00Z, accepts=[{scheme=exact, network=eip155:8453, amount=1000000, payTo=0x742d35Cc6634C0532925a3b844Bc454e4438f44e, asset=0x036CbD53842c5426634e7929541eC2318f3dCF7e, maxTimeoutSeconds=60}], extensions={bazaar={info={input={type=http, method=GET}}, schema={}}}, quality={l30DaysTotalCalls=42, l30DaysUniquePayers=15, lastCalledAt=2024-01-15T10:30:00Z}, serviceName=Weather API, tags=[weather, data], iconUrl=https://res.cloudinary.com/bdb-prod/image/upload/...}], pagination = {limit=100, offset=0, total=1000} ) else: return X402DiscoveryResourcesResponse( x402_version = 2, - items = [], + items = [{resource=https://api.example.com/weather/forecast, description=Real-time weather forecast data., type=http, x402Version=2, lastUpdated=2024-01-15T10:30:00Z, accepts=[{scheme=exact, network=eip155:8453, amount=1000000, payTo=0x742d35Cc6634C0532925a3b844Bc454e4438f44e, asset=0x036CbD53842c5426634e7929541eC2318f3dCF7e, maxTimeoutSeconds=60}], extensions={bazaar={info={input={type=http, method=GET}}, schema={}}}, quality={l30DaysTotalCalls=42, l30DaysUniquePayers=15, lastCalledAt=2024-01-15T10:30:00Z}, serviceName=Weather API, tags=[weather, data], iconUrl=https://res.cloudinary.com/bdb-prod/image/upload/...}], pagination = {limit=100, offset=0, total=1000}, ) """ diff --git a/python/cdp/openapi_client/test/test_x402_facilitator_api.py b/python/cdp/openapi_client/test/test_x402_facilitator_api.py index 160a90c80..b3fcf5b5a 100644 --- a/python/cdp/openapi_client/test/test_x402_facilitator_api.py +++ b/python/cdp/openapi_client/test/test_x402_facilitator_api.py @@ -37,7 +37,7 @@ async def test_list_x402_discovery_merchant(self) -> None: async def test_list_x402_discovery_resources(self) -> None: """Test case for list_x402_discovery_resources - List discovered x402 resources + List x402 resources """ pass @@ -58,7 +58,7 @@ async def test_search_x402_resources(self) -> None: async def test_settle_x402_payment(self) -> None: """Test case for settle_x402_payment - Settle a payment + Settle payment """ pass @@ -72,7 +72,7 @@ async def test_supported_x402_payment_kinds(self) -> None: async def test_verify_x402_payment(self) -> None: """Test case for verify_x402_payment - Verify a payment + Verify payment """ pass diff --git a/python/cdp/openapi_client/test/test_x402_search_resources_response.py b/python/cdp/openapi_client/test/test_x402_search_resources_response.py index 2bf21ba2d..de787c2d3 100644 --- a/python/cdp/openapi_client/test/test_x402_search_resources_response.py +++ b/python/cdp/openapi_client/test/test_x402_search_resources_response.py @@ -36,14 +36,14 @@ def make_instance(self, include_optional) -> X402SearchResourcesResponse: model = X402SearchResourcesResponse() if include_optional: return X402SearchResourcesResponse( - resources = [], + resources = [{resource=https://api.example.com/weather/forecast, description=Real-time weather forecast data., type=http, x402Version=2, lastUpdated=2024-01-15T10:30:00Z, accepts=[{scheme=exact, network=eip155:8453, amount=1000000, payTo=0x742d35Cc6634C0532925a3b844Bc454e4438f44e, asset=0x036CbD53842c5426634e7929541eC2318f3dCF7e, maxTimeoutSeconds=60}], extensions={bazaar={info={input={type=http, method=GET}}, schema={}}}, quality={l30DaysTotalCalls=42, l30DaysUniquePayers=15, lastCalledAt=2024-01-15T10:30:00Z}, serviceName=Weather API, tags=[weather, data], iconUrl=https://res.cloudinary.com/bdb-prod/image/upload/...}], partial_results = False, search_method = 'text', x402_version = 2 ) else: return X402SearchResourcesResponse( - resources = [], + resources = [{resource=https://api.example.com/weather/forecast, description=Real-time weather forecast data., type=http, x402Version=2, lastUpdated=2024-01-15T10:30:00Z, accepts=[{scheme=exact, network=eip155:8453, amount=1000000, payTo=0x742d35Cc6634C0532925a3b844Bc454e4438f44e, asset=0x036CbD53842c5426634e7929541eC2318f3dCF7e, maxTimeoutSeconds=60}], extensions={bazaar={info={input={type=http, method=GET}}, schema={}}}, quality={l30DaysTotalCalls=42, l30DaysUniquePayers=15, lastCalledAt=2024-01-15T10:30:00Z}, serviceName=Weather API, tags=[weather, data], iconUrl=https://res.cloudinary.com/bdb-prod/image/upload/...}], partial_results = False, x402_version = 2, ) diff --git a/rust/src/api.rs b/rust/src/api.rs index f976a601f..3e3fa6235 100644 --- a/rust/src/api.rs +++ b/rust/src/api.rs @@ -740,6 +740,245 @@ pub mod types { value.parse() } } + ///`Account` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "type": "object", + /// "required": [ + /// "accountId", + /// "createdAt", + /// "owner", + /// "type", + /// "updatedAt" + /// ], + /// "properties": { + /// "accountId": { + /// "$ref": "#/components/schemas/AccountId" + /// }, + /// "createdAt": { + /// "description": "The timestamp when the account was created.", + /// "examples": [ + /// "2023-10-08T14:30:00Z" + /// ], + /// "type": "string", + /// "format": "date-time" + /// }, + /// "name": { + /// "$ref": "#/components/schemas/AccountName" + /// }, + /// "owner": { + /// "$ref": "#/components/schemas/Owner" + /// }, + /// "type": { + /// "$ref": "#/components/schemas/AccountType" + /// }, + /// "updatedAt": { + /// "description": "The timestamp when the account was last updated.", + /// "examples": [ + /// "2023-10-08T14:30:00Z" + /// ], + /// "type": "string", + /// "format": "date-time" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct Account { + #[serde(rename = "accountId")] + pub account_id: AccountId, + ///The timestamp when the account was created. + #[serde(rename = "createdAt")] + pub created_at: ::chrono::DateTime<::chrono::offset::Utc>, + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub name: ::std::option::Option, + pub owner: Owner, + #[serde(rename = "type")] + pub type_: AccountType, + ///The timestamp when the account was last updated. + #[serde(rename = "updatedAt")] + pub updated_at: ::chrono::DateTime<::chrono::offset::Utc>, + } + impl ::std::convert::From<&Account> for Account { + fn from(value: &Account) -> Self { + value.clone() + } + } + impl Account { + pub fn builder() -> builder::Account { + Default::default() + } + } + ///The ID of the Account, which is a UUID prefixed by the string `account_`. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The ID of the Account, which is a UUID prefixed by the string `account_`.", + /// "examples": [ + /// "account_af2937b0-9846-4fe7-bfe9-ccc22d935114" + /// ], + /// "type": "string", + /// "pattern": "^account_[a-f0-9\\-]{36}$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct AccountId(::std::string::String); + impl ::std::ops::Deref for AccountId { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: AccountId) -> Self { + value.0 + } + } + impl ::std::convert::From<&AccountId> for AccountId { + fn from(value: &AccountId) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for AccountId { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^account_[a-f0-9\\-]{36}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^account_[a-f0-9\\-]{36}$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for AccountId { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for AccountId { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for AccountId { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for AccountId { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///An optional name for the account. Must be 1-64 characters and can only contain alphanumeric characters, hyphens, and spaces. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "An optional name for the account. Must be 1-64 characters and can only contain alphanumeric characters, hyphens, and spaces.", + /// "examples": [ + /// "My Business Account" + /// ], + /// "type": "string", + /// "maxLength": 64, + /// "pattern": "^[a-zA-Z0-9 -]{1,64}$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct AccountName(::std::string::String); + impl ::std::ops::Deref for AccountName { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: AccountName) -> Self { + value.0 + } + } + impl ::std::convert::From<&AccountName> for AccountName { + fn from(value: &AccountName) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for AccountName { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + if value.chars().count() > 64usize { + return Err("longer than 64 characters".into()); + } + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^[a-zA-Z0-9 -]{1,64}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^[a-zA-Z0-9 -]{1,64}$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for AccountName { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for AccountName { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for AccountName { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for AccountName { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } ///Response containing token addresses that an account has received. /// ///
JSON schema @@ -913,6 +1152,92 @@ pub mod types { }) } } + ///The type of the Account. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The type of the Account.", + /// "examples": [ + /// "prime" + /// ], + /// "type": "string", + /// "enum": [ + /// "prime", + /// "business", + /// "cdp" + /// ] + ///} + /// ``` + ///
+ #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum AccountType { + #[serde(rename = "prime")] + Prime, + #[serde(rename = "business")] + Business, + #[serde(rename = "cdp")] + Cdp, + } + impl ::std::convert::From<&Self> for AccountType { + fn from(value: &AccountType) -> Self { + value.clone() + } + } + impl ::std::fmt::Display for AccountType { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Prime => f.write_str("prime"), + Self::Business => f.write_str("business"), + Self::Cdp => f.write_str("cdp"), + } + } + } + impl ::std::str::FromStr for AccountType { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "prime" => Ok(Self::Prime), + "business" => Ok(Self::Business), + "cdp" => Ok(Self::Cdp), + _ => Err("invalid value".into()), + } + } + } + impl ::std::convert::TryFrom<&str> for AccountType { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for AccountType { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for AccountType { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } ///`AddEndUserEvmAccountResponse` /// ///
JSON schema @@ -1525,6 +1850,54 @@ pub mod types { }) } } + ///Available and total amounts for a specific currency. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "Available and total amounts for a specific currency.", + /// "type": "object", + /// "required": [ + /// "available", + /// "total" + /// ], + /// "properties": { + /// "available": { + /// "description": "The amount that is currently available to be used.", + /// "examples": [ + /// "2.5" + /// ], + /// "type": "string" + /// }, + /// "total": { + /// "description": "The total amount, including the amount that is currently on hold.", + /// "examples": [ + /// "3.0" + /// ], + /// "type": "string" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct AmountDetail { + ///The amount that is currently available to be used. + pub available: ::std::string::String, + ///The total amount, including the amount that is currently on hold. + pub total: ::std::string::String, + } + impl ::std::convert::From<&AmountDetail> for AmountDetail { + fn from(value: &AmountDetail) -> Self { + value.clone() + } + } + impl AmountDetail { + pub fn builder() -> builder::AmountDetail { + Default::default() + } + } ///The symbol of the asset (e.g., eth, usd, usdc, usdt). /// ///
JSON schema @@ -1606,6 +1979,87 @@ pub mod types { }) } } + ///The type of the asset. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The type of the asset.", + /// "examples": [ + /// "crypto" + /// ], + /// "type": "string", + /// "enum": [ + /// "fiat", + /// "crypto" + /// ] + ///} + /// ``` + ///
+ #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum AssetType { + #[serde(rename = "fiat")] + Fiat, + #[serde(rename = "crypto")] + Crypto, + } + impl ::std::convert::From<&Self> for AssetType { + fn from(value: &AssetType) -> Self { + value.clone() + } + } + impl ::std::fmt::Display for AssetType { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Fiat => f.write_str("fiat"), + Self::Crypto => f.write_str("crypto"), + } + } + } + impl ::std::str::FromStr for AssetType { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "fiat" => Ok(Self::Fiat), + "crypto" => Ok(Self::Crypto), + _ => Err("invalid value".into()), + } + } + } + impl ::std::convert::TryFrom<&str> for AssetType { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for AssetType { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for AssetType { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } ///Information about how the end user is authenticated. /// ///
JSON schema @@ -1754,6 +2208,229 @@ pub mod types { Self(value) } } + ///A balance of an asset. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "A balance of an asset.", + /// "examples": [ + /// { + /// "amount": { + /// "btc": { + /// "available": "2.5", + /// "total": "3.0" + /// }, + /// "usd": { + /// "available": "252705.4", + /// "total": "303246.48" + /// } + /// }, + /// "asset": { + /// "decimals": 8, + /// "name": "Bitcoin", + /// "symbol": "btc", + /// "type": "crypto" + /// } + /// } + /// ], + /// "type": "object", + /// "required": [ + /// "amount", + /// "asset" + /// ], + /// "properties": { + /// "amount": { + /// "description": "Amount details denominated in different assets. \n- The keys represent the asset symbols (e.g., \"btc\", \"usd\"), - Each value contains available and total amounts. - There will always be an entry for the asset specified in the `asset` field.", + /// "type": "object", + /// "additionalProperties": { + /// "$ref": "#/components/schemas/AmountDetail" + /// } + /// }, + /// "asset": { + /// "$ref": "#/components/schemas/balances_Asset" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct Balance { + /**Amount details denominated in different assets. + - The keys represent the asset symbols (e.g., "btc", "usd"), - Each value contains available and total amounts. - There will always be an entry for the asset specified in the `asset` field.*/ + pub amount: ::std::collections::HashMap<::std::string::String, AmountDetail>, + pub asset: BalancesAsset, + } + impl ::std::convert::From<&Balance> for Balance { + fn from(value: &Balance) -> Self { + value.clone() + } + } + impl Balance { + pub fn builder() -> builder::Balance { + Default::default() + } + } + ///A list of balances for an account. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "A list of balances for an account.", + /// "examples": [ + /// { + /// "balances": [ + /// { + /// "amount": { + /// "btc": { + /// "available": "2.5", + /// "total": "3.0" + /// }, + /// "usd": { + /// "available": "252705.4", + /// "total": "303246.48" + /// } + /// }, + /// "asset": { + /// "decimals": 8, + /// "name": "Bitcoin", + /// "symbol": "btc", + /// "type": "crypto" + /// } + /// }, + /// { + /// "amount": { + /// "usd": { + /// "available": "90", + /// "total": "100" + /// } + /// }, + /// "asset": { + /// "decimals": 2, + /// "name": "United States Dollar", + /// "symbol": "usd", + /// "type": "fiat" + /// } + /// } + /// ] + /// } + /// ], + /// "type": "object", + /// "required": [ + /// "balances" + /// ], + /// "properties": { + /// "balances": { + /// "description": "The list of balances.", + /// "examples": [ + /// [ + /// { + /// "amount": { + /// "btc": { + /// "available": "2.5", + /// "total": "3.0" + /// }, + /// "usd": { + /// "available": "252705.4", + /// "total": "303246.48" + /// } + /// }, + /// "asset": { + /// "decimals": 8, + /// "name": "Bitcoin", + /// "symbol": "btc", + /// "type": "crypto" + /// } + /// } + /// ] + /// ], + /// "type": "array", + /// "items": { + /// "$ref": "#/components/schemas/Balance" + /// } + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct Balances { + ///The list of balances. + pub balances: ::std::vec::Vec, + } + impl ::std::convert::From<&Balances> for Balances { + fn from(value: &Balances) -> Self { + value.clone() + } + } + impl Balances { + pub fn builder() -> builder::Balances { + Default::default() + } + } + ///An asset, e.g. fiat or crypto. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "An asset, e.g. fiat or crypto.", + /// "examples": [ + /// { + /// "decimals": 8, + /// "name": "Bitcoin", + /// "symbol": "btc", + /// "type": "crypto" + /// } + /// ], + /// "type": "object", + /// "required": [ + /// "decimals", + /// "name", + /// "symbol", + /// "type" + /// ], + /// "properties": { + /// "decimals": { + /// "description": "The number of decimals (i.e. significant digits to the right of the decimal point) supported for the asset.", + /// "type": "integer" + /// }, + /// "name": { + /// "description": "The name of the asset.", + /// "type": "string" + /// }, + /// "symbol": { + /// "$ref": "#/components/schemas/Asset" + /// }, + /// "type": { + /// "$ref": "#/components/schemas/AssetType" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct BalancesAsset { + ///The number of decimals (i.e. significant digits to the right of the decimal point) supported for the asset. + pub decimals: i64, + ///The name of the asset. + pub name: ::std::string::String, + pub symbol: Asset, + #[serde(rename = "type")] + pub type_: AssetType, + } + impl ::std::convert::From<&BalancesAsset> for BalancesAsset { + fn from(value: &BalancesAsset) -> Self { + value.clone() + } + } + impl BalancesAsset { + pub fn builder() -> builder::BalancesAsset { + Default::default() + } + } ///A blockchain address. Format varies by network (e.g., 0x-prefixed for EVM, base58 for Solana). /// ///
JSON schema @@ -3374,6 +4051,193 @@ pub mod types { }) } } + ///`CreateAccountRequest` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "type": "object", + /// "properties": { + /// "name": { + /// "$ref": "#/components/schemas/AccountName" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct CreateAccountRequest { + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub name: ::std::option::Option, + } + impl ::std::convert::From<&CreateAccountRequest> for CreateAccountRequest { + fn from(value: &CreateAccountRequest) -> Self { + value.clone() + } + } + impl ::std::default::Default for CreateAccountRequest { + fn default() -> Self { + Self { + name: Default::default(), + } + } + } + impl CreateAccountRequest { + pub fn builder() -> builder::CreateAccountRequest { + Default::default() + } + } + ///`CreateCryptoDepositDestinationRequest` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "examples": [ + /// { + /// "accountId": "account_af2937b0-9846-4fe7-bfe9-ccc22d935114", + /// "crypto": { + /// "network": "base" + /// }, + /// "metadata": { + /// "customer_id": "123e4567-e89b-12d3-a456-426614174000", + /// "reference": "order-12345" + /// }, + /// "target": { + /// "accountId": "account_af2937b0-9846-4fe7-bfe9-ccc22d935114", + /// "asset": "usd" + /// }, + /// "type": "crypto" + /// } + /// ], + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/CreateDepositDestinationRequestBase" + /// }, + /// { + /// "type": "object", + /// "required": [ + /// "crypto" + /// ], + /// "properties": { + /// "crypto": { + /// "description": "Crypto-specific details. Required when `type` is `crypto`.", + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/CreateDepositDestinationCrypto" + /// } + /// ] + /// }, + /// "type": { + /// "type": "string", + /// "enum": [ + /// "crypto" + /// ] + /// } + /// } + /// } + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct CreateCryptoDepositDestinationRequest { + #[serde(rename = "accountId")] + pub account_id: AccountId, + ///Crypto-specific details. Required when `type` is `crypto`. + pub crypto: CreateDepositDestinationCrypto, + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub metadata: ::std::option::Option, + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub target: ::std::option::Option, + #[serde(rename = "type")] + pub type_: CreateCryptoDepositDestinationRequestType, + } + impl ::std::convert::From<&CreateCryptoDepositDestinationRequest> + for CreateCryptoDepositDestinationRequest + { + fn from(value: &CreateCryptoDepositDestinationRequest) -> Self { + value.clone() + } + } + impl CreateCryptoDepositDestinationRequest { + pub fn builder() -> builder::CreateCryptoDepositDestinationRequest { + Default::default() + } + } + ///`CreateCryptoDepositDestinationRequestType` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "type": "string", + /// "enum": [ + /// "crypto" + /// ] + ///} + /// ``` + ///
+ #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum CreateCryptoDepositDestinationRequestType { + #[serde(rename = "crypto")] + Crypto, + } + impl ::std::convert::From<&Self> for CreateCryptoDepositDestinationRequestType { + fn from(value: &CreateCryptoDepositDestinationRequestType) -> Self { + value.clone() + } + } + impl ::std::fmt::Display for CreateCryptoDepositDestinationRequestType { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Crypto => f.write_str("crypto"), + } + } + } + impl ::std::str::FromStr for CreateCryptoDepositDestinationRequestType { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "crypto" => Ok(Self::Crypto), + _ => Err("invalid value".into()), + } + } + } + impl ::std::convert::TryFrom<&str> for CreateCryptoDepositDestinationRequestType { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for CreateCryptoDepositDestinationRequestType { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for CreateCryptoDepositDestinationRequestType { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } ///`CreateDelegationForEndUserAccountBody` /// ///
JSON schema @@ -3814,6 +4678,228 @@ pub mod types { }) } } + ///Crypto-specific details for creating a deposit destination. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "Crypto-specific details for creating a deposit destination.", + /// "examples": [ + /// { + /// "network": "base" + /// } + /// ], + /// "type": "object", + /// "required": [ + /// "network" + /// ], + /// "properties": { + /// "network": { + /// "$ref": "#/components/schemas/Network" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct CreateDepositDestinationCrypto { + pub network: Network, + } + impl ::std::convert::From<&CreateDepositDestinationCrypto> for CreateDepositDestinationCrypto { + fn from(value: &CreateDepositDestinationCrypto) -> Self { + value.clone() + } + } + impl CreateDepositDestinationCrypto { + pub fn builder() -> builder::CreateDepositDestinationCrypto { + Default::default() + } + } + ///Request to create a new deposit destination. Provide the type-specific details matching the chosen `type`. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "Request to create a new deposit destination. Provide the type-specific details matching the chosen `type`.", + /// "oneOf": [ + /// { + /// "$ref": "#/components/schemas/CreateCryptoDepositDestinationRequest" + /// } + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + #[serde(transparent)] + pub struct CreateDepositDestinationRequest(pub CreateCryptoDepositDestinationRequest); + impl ::std::ops::Deref for CreateDepositDestinationRequest { + type Target = CreateCryptoDepositDestinationRequest; + fn deref(&self) -> &CreateCryptoDepositDestinationRequest { + &self.0 + } + } + impl ::std::convert::From + for CreateCryptoDepositDestinationRequest + { + fn from(value: CreateDepositDestinationRequest) -> Self { + value.0 + } + } + impl ::std::convert::From<&CreateDepositDestinationRequest> for CreateDepositDestinationRequest { + fn from(value: &CreateDepositDestinationRequest) -> Self { + value.clone() + } + } + impl ::std::convert::From + for CreateDepositDestinationRequest + { + fn from(value: CreateCryptoDepositDestinationRequest) -> Self { + Self(value) + } + } + ///Common fields for creating a deposit destination. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "Common fields for creating a deposit destination.", + /// "examples": [ + /// { + /// "accountId": "account_af2937b0-9846-4fe7-bfe9-ccc22d935114", + /// "target": { + /// "accountId": "account_af2937b0-9846-4fe7-bfe9-ccc22d935114", + /// "asset": "usd" + /// }, + /// "type": "crypto" + /// } + /// ], + /// "type": "object", + /// "required": [ + /// "accountId", + /// "type" + /// ], + /// "properties": { + /// "accountId": { + /// "$ref": "#/components/schemas/AccountId" + /// }, + /// "metadata": { + /// "$ref": "#/components/schemas/Metadata" + /// }, + /// "target": { + /// "$ref": "#/components/schemas/DepositDestinationTarget" + /// }, + /// "type": { + /// "$ref": "#/components/schemas/DepositDestinationType" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct CreateDepositDestinationRequestBase { + #[serde(rename = "accountId")] + pub account_id: AccountId, + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub metadata: ::std::option::Option, + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub target: ::std::option::Option, + #[serde(rename = "type")] + pub type_: DepositDestinationType, + } + impl ::std::convert::From<&CreateDepositDestinationRequestBase> + for CreateDepositDestinationRequestBase + { + fn from(value: &CreateDepositDestinationRequestBase) -> Self { + value.clone() + } + } + impl CreateDepositDestinationRequestBase { + pub fn builder() -> builder::CreateDepositDestinationRequestBase { + Default::default() + } + } + ///`CreateDepositDestinationXIdempotencyKey` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "type": "string", + /// "maxLength": 128, + /// "minLength": 1 + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct CreateDepositDestinationXIdempotencyKey(::std::string::String); + impl ::std::ops::Deref for CreateDepositDestinationXIdempotencyKey { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: CreateDepositDestinationXIdempotencyKey) -> Self { + value.0 + } + } + impl ::std::convert::From<&CreateDepositDestinationXIdempotencyKey> + for CreateDepositDestinationXIdempotencyKey + { + fn from(value: &CreateDepositDestinationXIdempotencyKey) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for CreateDepositDestinationXIdempotencyKey { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + if value.chars().count() > 128usize { + return Err("longer than 128 characters".into()); + } + if value.chars().count() < 1usize { + return Err("shorter than 1 characters".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for CreateDepositDestinationXIdempotencyKey { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for CreateDepositDestinationXIdempotencyKey { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for CreateDepositDestinationXIdempotencyKey { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for CreateDepositDestinationXIdempotencyKey { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } ///`CreateEndUserBody` /// ///
JSON schema @@ -6634,6 +7720,85 @@ pub mod types { }) } } + ///`CreateFoundationAccountXIdempotencyKey` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "type": "string", + /// "maxLength": 128, + /// "minLength": 1 + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct CreateFoundationAccountXIdempotencyKey(::std::string::String); + impl ::std::ops::Deref for CreateFoundationAccountXIdempotencyKey { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: CreateFoundationAccountXIdempotencyKey) -> Self { + value.0 + } + } + impl ::std::convert::From<&CreateFoundationAccountXIdempotencyKey> + for CreateFoundationAccountXIdempotencyKey + { + fn from(value: &CreateFoundationAccountXIdempotencyKey) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for CreateFoundationAccountXIdempotencyKey { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + if value.chars().count() > 128usize { + return Err("longer than 128 characters".into()); + } + if value.chars().count() < 1usize { + return Err("shorter than 1 characters".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for CreateFoundationAccountXIdempotencyKey { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for CreateFoundationAccountXIdempotencyKey { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for CreateFoundationAccountXIdempotencyKey { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for CreateFoundationAccountXIdempotencyKey { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } ///`CreateOnrampOrderBody` /// ///
JSON schema @@ -10157,6 +11322,327 @@ pub mod types { Self::SwapUnavailableResponse(value) } } + ///The source of the transfer. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The source of the transfer.", + /// "examples": [ + /// {} + /// ], + /// "oneOf": [ + /// { + /// "$ref": "#/components/schemas/transfers_Account" + /// }, + /// { + /// "$ref": "#/components/schemas/PaymentMethod" + /// } + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + #[serde(untagged)] + pub enum CreateTransferSource { + TransfersAccount(TransfersAccount), + PaymentMethod(PaymentMethod), + } + impl ::std::convert::From<&Self> for CreateTransferSource { + fn from(value: &CreateTransferSource) -> Self { + value.clone() + } + } + impl ::std::convert::From for CreateTransferSource { + fn from(value: TransfersAccount) -> Self { + Self::TransfersAccount(value) + } + } + impl ::std::convert::From for CreateTransferSource { + fn from(value: PaymentMethod) -> Self { + Self::PaymentMethod(value) + } + } + ///`CreateTransferXIdempotencyKey` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "type": "string", + /// "maxLength": 128, + /// "minLength": 1 + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct CreateTransferXIdempotencyKey(::std::string::String); + impl ::std::ops::Deref for CreateTransferXIdempotencyKey { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: CreateTransferXIdempotencyKey) -> Self { + value.0 + } + } + impl ::std::convert::From<&CreateTransferXIdempotencyKey> for CreateTransferXIdempotencyKey { + fn from(value: &CreateTransferXIdempotencyKey) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for CreateTransferXIdempotencyKey { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + if value.chars().count() > 128usize { + return Err("longer than 128 characters".into()); + } + if value.chars().count() < 1usize { + return Err("shorter than 1 characters".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for CreateTransferXIdempotencyKey { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for CreateTransferXIdempotencyKey { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for CreateTransferXIdempotencyKey { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for CreateTransferXIdempotencyKey { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///A cryptocurrency deposit destination. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "A cryptocurrency deposit destination.", + /// "examples": [ + /// { + /// "accountId": "account_af2937b0-9846-4fe7-bfe9-ccc22d935114", + /// "createdAt": "2023-10-08T14:30:00Z", + /// "crypto": { + /// "address": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "network": "base" + /// }, + /// "depositDestinationId": "depositDestination_af2937b0-9846-4fe7-bfe9-ccc22d935114", + /// "metadata": { + /// "customer_id": "123e4567-e89b-12d3-a456-426614174000", + /// "reference": "order-12345" + /// }, + /// "status": "active", + /// "target": { + /// "accountId": "account_bf3847c1-a957-5ae8-cfa0-ddd33e046225", + /// "asset": "usd" + /// }, + /// "type": "crypto", + /// "updatedAt": "2023-10-08T14:30:00Z" + /// } + /// ], + /// "type": "object", + /// "required": [ + /// "accountId", + /// "createdAt", + /// "crypto", + /// "depositDestinationId", + /// "status", + /// "type", + /// "updatedAt" + /// ], + /// "properties": { + /// "accountId": { + /// "$ref": "#/components/schemas/AccountId" + /// }, + /// "createdAt": { + /// "description": "The timestamp when the deposit destination was created.", + /// "examples": [ + /// "2023-10-08T14:30:00Z" + /// ], + /// "type": "string", + /// "format": "date-time" + /// }, + /// "crypto": { + /// "description": "Crypto-specific details for this deposit destination. Always populated in responses. Contains the network and address.", + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/DepositDestinationCrypto" + /// } + /// ] + /// }, + /// "depositDestinationId": { + /// "$ref": "#/components/schemas/DepositDestinationId" + /// }, + /// "metadata": { + /// "$ref": "#/components/schemas/Metadata" + /// }, + /// "status": { + /// "$ref": "#/components/schemas/DepositDestinationStatus" + /// }, + /// "target": { + /// "$ref": "#/components/schemas/DepositDestinationTarget" + /// }, + /// "type": { + /// "description": "The type of deposit destination.", + /// "examples": [ + /// "crypto" + /// ], + /// "type": "string", + /// "enum": [ + /// "crypto" + /// ] + /// }, + /// "updatedAt": { + /// "description": "The timestamp when the deposit destination was last updated.", + /// "examples": [ + /// "2023-10-08T14:30:00Z" + /// ], + /// "type": "string", + /// "format": "date-time" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct CryptoDepositDestination { + #[serde(rename = "accountId")] + pub account_id: AccountId, + ///The timestamp when the deposit destination was created. + #[serde(rename = "createdAt")] + pub created_at: ::chrono::DateTime<::chrono::offset::Utc>, + ///Crypto-specific details for this deposit destination. Always populated in responses. Contains the network and address. + pub crypto: DepositDestinationCrypto, + #[serde(rename = "depositDestinationId")] + pub deposit_destination_id: DepositDestinationId, + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub metadata: ::std::option::Option, + pub status: DepositDestinationStatus, + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub target: ::std::option::Option, + ///The type of deposit destination. + #[serde(rename = "type")] + pub type_: CryptoDepositDestinationType, + ///The timestamp when the deposit destination was last updated. + #[serde(rename = "updatedAt")] + pub updated_at: ::chrono::DateTime<::chrono::offset::Utc>, + } + impl ::std::convert::From<&CryptoDepositDestination> for CryptoDepositDestination { + fn from(value: &CryptoDepositDestination) -> Self { + value.clone() + } + } + impl CryptoDepositDestination { + pub fn builder() -> builder::CryptoDepositDestination { + Default::default() + } + } + ///The type of deposit destination. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The type of deposit destination.", + /// "examples": [ + /// "crypto" + /// ], + /// "type": "string", + /// "enum": [ + /// "crypto" + /// ] + ///} + /// ``` + ///
+ #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum CryptoDepositDestinationType { + #[serde(rename = "crypto")] + Crypto, + } + impl ::std::convert::From<&Self> for CryptoDepositDestinationType { + fn from(value: &CryptoDepositDestinationType) -> Self { + value.clone() + } + } + impl ::std::fmt::Display for CryptoDepositDestinationType { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Crypto => f.write_str("crypto"), + } + } + } + impl ::std::str::FromStr for CryptoDepositDestinationType { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "crypto" => Ok(Self::Crypto), + _ => Err("invalid value".into()), + } + } + } + impl ::std::convert::TryFrom<&str> for CryptoDepositDestinationType { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for CryptoDepositDestinationType { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for CryptoDepositDestinationType { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } ///Date of birth. /// ///
JSON schema @@ -10660,56 +12146,145 @@ pub mod types { }) } } - ///A human-readable description. + ///A deposit destination for receiving funds to an account. /// ///
JSON schema /// /// ```json ///{ - /// "description": "A human-readable description.", + /// "description": "A deposit destination for receiving funds to an account.", + /// "oneOf": [ + /// { + /// "$ref": "#/components/schemas/CryptoDepositDestination" + /// } + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + #[serde(transparent)] + pub struct DepositDestination(pub CryptoDepositDestination); + impl ::std::ops::Deref for DepositDestination { + type Target = CryptoDepositDestination; + fn deref(&self) -> &CryptoDepositDestination { + &self.0 + } + } + impl ::std::convert::From for CryptoDepositDestination { + fn from(value: DepositDestination) -> Self { + value.0 + } + } + impl ::std::convert::From<&DepositDestination> for DepositDestination { + fn from(value: &DepositDestination) -> Self { + value.clone() + } + } + impl ::std::convert::From for DepositDestination { + fn from(value: CryptoDepositDestination) -> Self { + Self(value) + } + } + ///Crypto-specific deposit destination details. In responses, this object is always present. Contains the network and address for the deposit destination. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "Crypto-specific deposit destination details. In responses, this object is always present. Contains the network and address for the deposit destination.", /// "examples": [ - /// "A description of the resource." + /// { + /// "address": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "network": "base" + /// } + /// ], + /// "type": "object", + /// "required": [ + /// "address", + /// "network" + /// ], + /// "properties": { + /// "address": { + /// "$ref": "#/components/schemas/BlockchainAddress" + /// }, + /// "network": { + /// "$ref": "#/components/schemas/Network" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct DepositDestinationCrypto { + pub address: BlockchainAddress, + pub network: Network, + } + impl ::std::convert::From<&DepositDestinationCrypto> for DepositDestinationCrypto { + fn from(value: &DepositDestinationCrypto) -> Self { + value.clone() + } + } + impl DepositDestinationCrypto { + pub fn builder() -> builder::DepositDestinationCrypto { + Default::default() + } + } + ///The ID of the Deposit Destination, which is a UUID prefixed by the string `depositDestination_`. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The ID of the Deposit Destination, which is a UUID prefixed by the string `depositDestination_`.", + /// "examples": [ + /// "depositDestination_af2937b0-9846-4fe7-bfe9-ccc22d935114" /// ], /// "type": "string", - /// "maxLength": 500 + /// "pattern": "^depositDestination_[a-f0-9\\-]{36}$" ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct Description(::std::string::String); - impl ::std::ops::Deref for Description { + pub struct DepositDestinationId(::std::string::String); + impl ::std::ops::Deref for DepositDestinationId { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: Description) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: DepositDestinationId) -> Self { value.0 } } - impl ::std::convert::From<&Description> for Description { - fn from(value: &Description) -> Self { + impl ::std::convert::From<&DepositDestinationId> for DepositDestinationId { + fn from(value: &DepositDestinationId) -> Self { value.clone() } } - impl ::std::str::FromStr for Description { + impl ::std::str::FromStr for DepositDestinationId { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - if value.chars().count() > 500usize { - return Err("longer than 500 characters".into()); + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^depositDestination_[a-f0-9\\-]{36}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err( + "doesn't match pattern \"^depositDestination_[a-f0-9\\-]{36}$\"".into(), + ); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for Description { + impl ::std::convert::TryFrom<&str> for DepositDestinationId { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for Description { + impl ::std::convert::TryFrom<&::std::string::String> for DepositDestinationId { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -10717,7 +12292,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for Description { + impl ::std::convert::TryFrom<::std::string::String> for DepositDestinationId { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -10725,7 +12300,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for Description { + impl<'de> ::serde::Deserialize<'de> for DepositDestinationId { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -10737,82 +12312,59 @@ pub mod types { }) } } - ///Information about an end user who authenticates using a JWT issued by the developer. + ///A reference to the deposit destination associated with the transfer. /// ///
JSON schema /// /// ```json ///{ - /// "title": "DeveloperJWTAuthentication", - /// "description": "Information about an end user who authenticates using a JWT issued by the developer.", + /// "description": "A reference to the deposit destination associated with the transfer.", + /// "examples": [ + /// { + /// "id": "depositDestination_af2937b0-9846-4fe7-bfe9-ccc22d935114" + /// } + /// ], /// "type": "object", /// "required": [ - /// "kid", - /// "sub", - /// "type" + /// "id" /// ], /// "properties": { - /// "kid": { - /// "description": "The key ID of the JWK used to sign the JWT.", - /// "examples": [ - /// "NjVBRjY5MDlCMUIwNzU4RTA2QzZFMDQ4QzQ2MDAyQjVDNjk1RTM2Qg" - /// ], - /// "type": "string" - /// }, - /// "sub": { - /// "description": "The unique identifier for the end user that is captured in the `sub` claim of the JWT.", - /// "examples": [ - /// "e051beeb-7163-4527-a5b6-35e301529ff2" - /// ], - /// "type": "string" - /// }, - /// "type": { - /// "description": "The type of authentication information.", - /// "examples": [ - /// "jwt" - /// ], - /// "type": "string", - /// "enum": [ - /// "jwt" - /// ] + /// "id": { + /// "$ref": "#/components/schemas/DepositDestinationId" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct DeveloperJwtAuthentication { - ///The key ID of the JWK used to sign the JWT. - pub kid: ::std::string::String, - ///The unique identifier for the end user that is captured in the `sub` claim of the JWT. - pub sub: ::std::string::String, - ///The type of authentication information. - #[serde(rename = "type")] - pub type_: DeveloperJwtAuthenticationType, + pub struct DepositDestinationReference { + pub id: DepositDestinationId, } - impl ::std::convert::From<&DeveloperJwtAuthentication> for DeveloperJwtAuthentication { - fn from(value: &DeveloperJwtAuthentication) -> Self { + impl ::std::convert::From<&DepositDestinationReference> for DepositDestinationReference { + fn from(value: &DepositDestinationReference) -> Self { value.clone() } } - impl DeveloperJwtAuthentication { - pub fn builder() -> builder::DeveloperJwtAuthentication { + impl DepositDestinationReference { + pub fn builder() -> builder::DepositDestinationReference { Default::default() } } - ///The type of authentication information. + ///The status of the deposit destination. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The type of authentication information.", + /// "description": "The status of the deposit destination.", /// "examples": [ - /// "jwt" + /// "active" /// ], /// "type": "string", /// "enum": [ - /// "jwt" + /// "active", + /// "inactive", + /// "pending" /// ] ///} /// ``` @@ -10829,38 +12381,46 @@ pub mod types { PartialEq, PartialOrd, )] - pub enum DeveloperJwtAuthenticationType { - #[serde(rename = "jwt")] - Jwt, + pub enum DepositDestinationStatus { + #[serde(rename = "active")] + Active, + #[serde(rename = "inactive")] + Inactive, + #[serde(rename = "pending")] + Pending, } - impl ::std::convert::From<&Self> for DeveloperJwtAuthenticationType { - fn from(value: &DeveloperJwtAuthenticationType) -> Self { + impl ::std::convert::From<&Self> for DepositDestinationStatus { + fn from(value: &DepositDestinationStatus) -> Self { value.clone() } } - impl ::std::fmt::Display for DeveloperJwtAuthenticationType { + impl ::std::fmt::Display for DepositDestinationStatus { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match *self { - Self::Jwt => f.write_str("jwt"), + Self::Active => f.write_str("active"), + Self::Inactive => f.write_str("inactive"), + Self::Pending => f.write_str("pending"), } } } - impl ::std::str::FromStr for DeveloperJwtAuthenticationType { + impl ::std::str::FromStr for DepositDestinationStatus { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { match value { - "jwt" => Ok(Self::Jwt), + "active" => Ok(Self::Active), + "inactive" => Ok(Self::Inactive), + "pending" => Ok(Self::Pending), _ => Err("invalid value".into()), } } } - impl ::std::convert::TryFrom<&str> for DeveloperJwtAuthenticationType { + impl ::std::convert::TryFrom<&str> for DepositDestinationStatus { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for DeveloperJwtAuthenticationType { + impl ::std::convert::TryFrom<&::std::string::String> for DepositDestinationStatus { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -10868,7 +12428,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for DeveloperJwtAuthenticationType { + impl ::std::convert::TryFrom<::std::string::String> for DepositDestinationStatus { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -10876,165 +12436,176 @@ pub mod types { value.parse() } } - ///The domain of the EIP-712 typed data. + ///The intended target for deposited funds. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The domain of the EIP-712 typed data.", + /// "description": "The intended target for deposited funds.", + /// "oneOf": [ + /// { + /// "$ref": "#/components/schemas/DepositDestinationTargetAccount" + /// } + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + #[serde(transparent)] + pub struct DepositDestinationTarget(pub DepositDestinationTargetAccount); + impl ::std::ops::Deref for DepositDestinationTarget { + type Target = DepositDestinationTargetAccount; + fn deref(&self) -> &DepositDestinationTargetAccount { + &self.0 + } + } + impl ::std::convert::From for DepositDestinationTargetAccount { + fn from(value: DepositDestinationTarget) -> Self { + value.0 + } + } + impl ::std::convert::From<&DepositDestinationTarget> for DepositDestinationTarget { + fn from(value: &DepositDestinationTarget) -> Self { + value.clone() + } + } + impl ::std::convert::From for DepositDestinationTarget { + fn from(value: DepositDestinationTargetAccount) -> Self { + Self(value) + } + } + ///The account and asset where incoming deposits should be credited. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "title": "Target Account", + /// "description": "The account and asset where incoming deposits should be credited.", /// "examples": [ /// { - /// "chainId": 1, - /// "name": "Permit2", - /// "verifyingContract": "0x000000000022D473030F116dDEE9F6B43aC78BA3" + /// "accountId": "account_af2937b0-9846-4fe7-bfe9-ccc22d935114", + /// "asset": "usd" /// } /// ], /// "type": "object", + /// "required": [ + /// "asset" + /// ], /// "properties": { - /// "chainId": { - /// "description": "The chain ID of the EVM network.", - /// "examples": [ - /// 1 - /// ], - /// "type": "integer", - /// "format": "int64" - /// }, - /// "name": { - /// "description": "The name of the DApp or protocol.", - /// "examples": [ - /// "Permit2" - /// ], - /// "type": "string" - /// }, - /// "salt": { - /// "description": "The optional 32-byte 0x-prefixed hex salt for domain separation.", - /// "examples": [ - /// "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" - /// ], - /// "type": "string", - /// "pattern": "^0x[a-fA-F0-9]{64}$" - /// }, - /// "verifyingContract": { - /// "description": "The 0x-prefixed EVM address of the verifying smart contract.", - /// "examples": [ - /// "0x000000000022D473030F116dDEE9F6B43aC78BA3" - /// ], - /// "type": "string", - /// "pattern": "^0x[a-fA-F0-9]{40}$" + /// "accountId": { + /// "description": "The ID of the CDP Account to which deposited funds should be transferred.", + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/AccountId" + /// } + /// ] /// }, - /// "version": { - /// "description": "The version of the DApp or protocol.", + /// "asset": { + /// "description": "The symbol of the asset that should land in the target account.", /// "examples": [ - /// "1" + /// "usd" /// ], - /// "type": "string" + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/Asset" + /// } + /// ] /// } - /// } + /// }, + /// "additionalProperties": false ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct Eip712Domain { - ///The chain ID of the EVM network. - #[serde( - rename = "chainId", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub chain_id: ::std::option::Option, - ///The name of the DApp or protocol. - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub name: ::std::option::Option<::std::string::String>, - ///The optional 32-byte 0x-prefixed hex salt for domain separation. - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub salt: ::std::option::Option, - ///The 0x-prefixed EVM address of the verifying smart contract. + #[serde(deny_unknown_fields)] + pub struct DepositDestinationTargetAccount { + ///The ID of the CDP Account to which deposited funds should be transferred. #[serde( - rename = "verifyingContract", + rename = "accountId", default, skip_serializing_if = "::std::option::Option::is_none" )] - pub verifying_contract: ::std::option::Option, - ///The version of the DApp or protocol. - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub version: ::std::option::Option<::std::string::String>, + pub account_id: ::std::option::Option, + ///The symbol of the asset that should land in the target account. + pub asset: Asset, } - impl ::std::convert::From<&Eip712Domain> for Eip712Domain { - fn from(value: &Eip712Domain) -> Self { + impl ::std::convert::From<&DepositDestinationTargetAccount> for DepositDestinationTargetAccount { + fn from(value: &DepositDestinationTargetAccount) -> Self { value.clone() } } - impl ::std::default::Default for Eip712Domain { - fn default() -> Self { - Self { - chain_id: Default::default(), - name: Default::default(), - salt: Default::default(), - verifying_contract: Default::default(), - version: Default::default(), - } - } - } - impl Eip712Domain { - pub fn builder() -> builder::Eip712Domain { + impl DepositDestinationTargetAccount { + pub fn builder() -> builder::DepositDestinationTargetAccount { Default::default() } } - ///The optional 32-byte 0x-prefixed hex salt for domain separation. + ///The type of deposit destination. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The optional 32-byte 0x-prefixed hex salt for domain separation.", + /// "description": "The type of deposit destination.", /// "examples": [ - /// "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" + /// "crypto" /// ], /// "type": "string", - /// "pattern": "^0x[a-fA-F0-9]{64}$" + /// "oneOf": [ + /// { + /// "enum": [ + /// "crypto" + /// ] + /// } + /// ] ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct Eip712DomainSalt(::std::string::String); - impl ::std::ops::Deref for Eip712DomainSalt { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } + #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum DepositDestinationType { + #[serde(rename = "crypto")] + Crypto, } - impl ::std::convert::From for ::std::string::String { - fn from(value: Eip712DomainSalt) -> Self { - value.0 + impl ::std::convert::From<&Self> for DepositDestinationType { + fn from(value: &DepositDestinationType) -> Self { + value.clone() } } - impl ::std::convert::From<&Eip712DomainSalt> for Eip712DomainSalt { - fn from(value: &Eip712DomainSalt) -> Self { - value.clone() + impl ::std::fmt::Display for DepositDestinationType { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Crypto => f.write_str("crypto"), + } } } - impl ::std::str::FromStr for Eip712DomainSalt { + impl ::std::str::FromStr for DepositDestinationType { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[a-fA-F0-9]{64}$").unwrap() - }); - if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[a-fA-F0-9]{64}$\"".into()); + match value { + "crypto" => Ok(Self::Crypto), + _ => Err("invalid value".into()), } - Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for Eip712DomainSalt { + impl ::std::convert::TryFrom<&str> for DepositDestinationType { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for Eip712DomainSalt { + impl ::std::convert::TryFrom<&::std::string::String> for DepositDestinationType { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -11042,7 +12613,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for Eip712DomainSalt { + impl ::std::convert::TryFrom<::std::string::String> for DepositDestinationType { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -11050,72 +12621,248 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for Eip712DomainSalt { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) + ///Beneficiary information for a deposit travel rule submission. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "Beneficiary information for a deposit travel rule submission.", + /// "examples": [ + /// { + /// "name": "Jane Smith" + /// } + /// ], + /// "type": "object", + /// "properties": { + /// "name": { + /// "description": "Full name of the beneficiary.", + /// "examples": [ + /// "Jane Smith" + /// ], + /// "type": "string" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct DepositTravelRuleBeneficiary { + ///Full name of the beneficiary. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub name: ::std::option::Option<::std::string::String>, + } + impl ::std::convert::From<&DepositTravelRuleBeneficiary> for DepositTravelRuleBeneficiary { + fn from(value: &DepositTravelRuleBeneficiary) -> Self { + value.clone() } } - ///The 0x-prefixed EVM address of the verifying smart contract. + impl ::std::default::Default for DepositTravelRuleBeneficiary { + fn default() -> Self { + Self { + name: Default::default(), + } + } + } + impl DepositTravelRuleBeneficiary { + pub fn builder() -> builder::DepositTravelRuleBeneficiary { + Default::default() + } + } + ///Originator information for a deposit travel rule submission. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The 0x-prefixed EVM address of the verifying smart contract.", + /// "description": "Originator information for a deposit travel rule submission.", /// "examples": [ - /// "0x000000000022D473030F116dDEE9F6B43aC78BA3" + /// { + /// "address": { + /// "city": "San Francisco", + /// "countryCode": "US", + /// "line1": "123 Main St", + /// "postCode": "94105", + /// "state": "CA" + /// }, + /// "name": "John Doe", + /// "vasp": { + /// "identifier": "5493001KJTIIGC8Y1R17", + /// "name": "Fidelity Digital Asset Services, LLC" + /// }, + /// "walletType": "custodial" + /// } /// ], - /// "type": "string", - /// "pattern": "^0x[a-fA-F0-9]{40}$" + /// "type": "object", + /// "properties": { + /// "address": { + /// "$ref": "#/components/schemas/PhysicalAddress" + /// }, + /// "dateOfBirth": { + /// "$ref": "#/components/schemas/DateOfBirth" + /// }, + /// "name": { + /// "description": "Full name of the originator.", + /// "examples": [ + /// "John Doe" + /// ], + /// "type": "string" + /// }, + /// "personalId": { + /// "description": "Government-issued personal identification number for the originator.", + /// "examples": [ + /// "123-45-6789" + /// ], + /// "type": "string" + /// }, + /// "virtualAssetServiceProvider": { + /// "$ref": "#/components/schemas/DepositTravelRuleVasp" + /// }, + /// "walletType": { + /// "description": "The type of the originator's wallet.", + /// "examples": [ + /// "custodial" + /// ], + /// "type": "string", + /// "enum": [ + /// "custodial", + /// "self_custody" + /// ], + /// "x-enum-descriptions": [ + /// "The originator's wallet is held by a custodial service.", + /// "The originator's wallet is self-custodied." + /// ] + /// } + /// } ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct Eip712DomainVerifyingContract(::std::string::String); - impl ::std::ops::Deref for Eip712DomainVerifyingContract { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 + #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct DepositTravelRuleOriginator { + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub address: ::std::option::Option, + #[serde( + rename = "dateOfBirth", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub date_of_birth: ::std::option::Option, + ///Full name of the originator. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub name: ::std::option::Option<::std::string::String>, + ///Government-issued personal identification number for the originator. + #[serde( + rename = "personalId", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub personal_id: ::std::option::Option<::std::string::String>, + #[serde( + rename = "virtualAssetServiceProvider", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub virtual_asset_service_provider: ::std::option::Option, + ///The type of the originator's wallet. + #[serde( + rename = "walletType", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub wallet_type: ::std::option::Option, + } + impl ::std::convert::From<&DepositTravelRuleOriginator> for DepositTravelRuleOriginator { + fn from(value: &DepositTravelRuleOriginator) -> Self { + value.clone() } } - impl ::std::convert::From for ::std::string::String { - fn from(value: Eip712DomainVerifyingContract) -> Self { - value.0 + impl ::std::default::Default for DepositTravelRuleOriginator { + fn default() -> Self { + Self { + address: Default::default(), + date_of_birth: Default::default(), + name: Default::default(), + personal_id: Default::default(), + virtual_asset_service_provider: Default::default(), + wallet_type: Default::default(), + } } } - impl ::std::convert::From<&Eip712DomainVerifyingContract> for Eip712DomainVerifyingContract { - fn from(value: &Eip712DomainVerifyingContract) -> Self { + impl DepositTravelRuleOriginator { + pub fn builder() -> builder::DepositTravelRuleOriginator { + Default::default() + } + } + ///The type of the originator's wallet. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The type of the originator's wallet.", + /// "examples": [ + /// "custodial" + /// ], + /// "type": "string", + /// "enum": [ + /// "custodial", + /// "self_custody" + /// ], + /// "x-enum-descriptions": [ + /// "The originator's wallet is held by a custodial service.", + /// "The originator's wallet is self-custodied." + /// ] + ///} + /// ``` + ///
+ #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum DepositTravelRuleOriginatorWalletType { + #[serde(rename = "custodial")] + Custodial, + #[serde(rename = "self_custody")] + SelfCustody, + } + impl ::std::convert::From<&Self> for DepositTravelRuleOriginatorWalletType { + fn from(value: &DepositTravelRuleOriginatorWalletType) -> Self { value.clone() } } - impl ::std::str::FromStr for Eip712DomainVerifyingContract { + impl ::std::fmt::Display for DepositTravelRuleOriginatorWalletType { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Custodial => f.write_str("custodial"), + Self::SelfCustody => f.write_str("self_custody"), + } + } + } + impl ::std::str::FromStr for DepositTravelRuleOriginatorWalletType { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[a-fA-F0-9]{40}$").unwrap() - }); - if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[a-fA-F0-9]{40}$\"".into()); + match value { + "custodial" => Ok(Self::Custodial), + "self_custody" => Ok(Self::SelfCustody), + _ => Err("invalid value".into()), } - Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for Eip712DomainVerifyingContract { + impl ::std::convert::TryFrom<&str> for DepositTravelRuleOriginatorWalletType { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for Eip712DomainVerifyingContract { + impl ::std::convert::TryFrom<&::std::string::String> for DepositTravelRuleOriginatorWalletType { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -11123,7 +12870,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for Eip712DomainVerifyingContract { + impl ::std::convert::TryFrom<::std::string::String> for DepositTravelRuleOriginatorWalletType { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -11131,265 +12878,330 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for Eip712DomainVerifyingContract { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) - } - } - ///The message to sign using EIP-712. + ///Request body for submitting travel rule information for a deposit transfer. Required fields vary by jurisdiction. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The message to sign using EIP-712.", + /// "description": "Request body for submitting travel rule information for a deposit transfer. Required fields vary by jurisdiction.", /// "examples": [ /// { - /// "domain": { - /// "chainId": 1, - /// "name": "Permit2", - /// "verifyingContract": "0x000000000022D473030F116dDEE9F6B43aC78BA3" + /// "beneficiary": { + /// "name": "Jane Smith" /// }, - /// "message": { - /// "deadline": "1717123200", - /// "nonce": "123456", - /// "permitted": { - /// "amount": "1000000", - /// "token": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" + /// "isSelf": false, + /// "originator": { + /// "address": { + /// "city": "San Francisco", + /// "countryCode": "US", + /// "line1": "123 Main St", + /// "postCode": "94105", + /// "state": "CA" /// }, - /// "spender": "0xFfFfFfFFfFFfFFfFFfFFFFFffFFFffffFfFFFfFf" - /// }, - /// "primaryType": "PermitTransferFrom", - /// "types": { - /// "EIP712Domain": [ - /// { - /// "name": "name", - /// "type": "string" - /// }, - /// { - /// "name": "chainId", - /// "type": "uint256" - /// }, - /// { - /// "name": "verifyingContract", - /// "type": "address" - /// } - /// ], - /// "PermitTransferFrom": [ - /// { - /// "name": "permitted", - /// "type": "TokenPermissions" - /// }, - /// { - /// "name": "spender", - /// "type": "address" - /// }, - /// { - /// "name": "nonce", - /// "type": "uint256" - /// }, - /// { - /// "name": "deadline", - /// "type": "uint256" - /// } - /// ], - /// "TokenPermissions": [ - /// { - /// "name": "token", - /// "type": "address" - /// }, - /// { - /// "name": "amount", - /// "type": "uint256" - /// } - /// ] + /// "name": "John Doe" /// } /// } /// ], /// "type": "object", + /// "properties": { + /// "beneficiary": { + /// "$ref": "#/components/schemas/DepositTravelRuleBeneficiary" + /// }, + /// "isSelf": { + /// "description": "Indicates whether the user attests that the originating wallet belongs to them.", + /// "examples": [ + /// false + /// ], + /// "type": "boolean" + /// }, + /// "originator": { + /// "$ref": "#/components/schemas/DepositTravelRuleOriginator" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct DepositTravelRuleRequest { + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub beneficiary: ::std::option::Option, + ///Indicates whether the user attests that the originating wallet belongs to them. + #[serde( + rename = "isSelf", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub is_self: ::std::option::Option, + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub originator: ::std::option::Option, + } + impl ::std::convert::From<&DepositTravelRuleRequest> for DepositTravelRuleRequest { + fn from(value: &DepositTravelRuleRequest) -> Self { + value.clone() + } + } + impl ::std::default::Default for DepositTravelRuleRequest { + fn default() -> Self { + Self { + beneficiary: Default::default(), + is_self: Default::default(), + originator: Default::default(), + } + } + } + impl DepositTravelRuleRequest { + pub fn builder() -> builder::DepositTravelRuleRequest { + Default::default() + } + } + ///Response from submitting travel rule information for a deposit transfer. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "Response from submitting travel rule information for a deposit transfer.", + /// "examples": [ + /// { + /// "missingFields": [ + /// "originator.address.countryCode" + /// ], + /// "status": "incomplete" + /// } + /// ], + /// "type": "object", /// "required": [ - /// "domain", - /// "message", - /// "primaryType", - /// "types" + /// "status" /// ], /// "properties": { - /// "domain": { - /// "$ref": "#/components/schemas/EIP712Domain" - /// }, - /// "message": { - /// "description": "The message to sign. The structure of this message must match the `primaryType` struct in the `types` object.", + /// "missingFields": { + /// "description": "List of field paths that are still required to complete travel rule compliance. Each entry is a dot-separated path (e.g., \"originator.name\", \"originator.address.countryCode\"). Empty when status is \"completed\".", /// "examples": [ - /// { - /// "deadline": "1716239020", - /// "nonce": "0", - /// "permitted": { - /// "amount": "1000000", - /// "token": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" - /// }, - /// "spender": "0x1111111254EEB25477B68fb85Ed929f73A960582" - /// } + /// [ + /// "originator.address.countryCode" + /// ] /// ], - /// "type": "object" + /// "type": "array", + /// "items": { + /// "examples": [ + /// "originator.name" + /// ], + /// "type": "string" + /// } /// }, - /// "primaryType": { - /// "description": "The primary type of the message. This is the name of the struct in the `types` object that is the root of the message.", + /// "reason": { + /// "description": "Additional context about the current status. Present when status is `incomplete` to explain what needs to be fixed before the transfer can proceed.", /// "examples": [ - /// "PermitTransferFrom" + /// "Originator date of birth is required." /// ], /// "type": "string" /// }, - /// "types": { - /// "$ref": "#/components/schemas/EIP712Types" + /// "status": { + /// "$ref": "#/components/schemas/TravelRuleStatus" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct Eip712Message { - pub domain: Eip712Domain, - ///The message to sign. The structure of this message must match the `primaryType` struct in the `types` object. - pub message: ::serde_json::Map<::std::string::String, ::serde_json::Value>, - ///The primary type of the message. This is the name of the struct in the `types` object that is the root of the message. - #[serde(rename = "primaryType")] - pub primary_type: ::std::string::String, - pub types: Eip712Types, + pub struct DepositTravelRuleResponse { + ///List of field paths that are still required to complete travel rule compliance. Each entry is a dot-separated path (e.g., "originator.name", "originator.address.countryCode"). Empty when status is "completed". + #[serde( + rename = "missingFields", + default, + skip_serializing_if = "::std::vec::Vec::is_empty" + )] + pub missing_fields: ::std::vec::Vec<::std::string::String>, + ///Additional context about the current status. Present when status is `incomplete` to explain what needs to be fixed before the transfer can proceed. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub reason: ::std::option::Option<::std::string::String>, + pub status: TravelRuleStatus, } - impl ::std::convert::From<&Eip712Message> for Eip712Message { - fn from(value: &Eip712Message) -> Self { + impl ::std::convert::From<&DepositTravelRuleResponse> for DepositTravelRuleResponse { + fn from(value: &DepositTravelRuleResponse) -> Self { value.clone() } } - impl Eip712Message { - pub fn builder() -> builder::Eip712Message { + impl DepositTravelRuleResponse { + pub fn builder() -> builder::DepositTravelRuleResponse { Default::default() } } - /**A mapping of struct names to an array of type objects (name + type). - Each key corresponds to a type name (e.g., "`EIP712Domain`", "`PermitTransferFrom`"). - */ + ///Information about the Virtual Asset Service Provider (VASP) for a deposit travel rule submission. /// ///
JSON schema /// /// ```json ///{ - /// "description": "A mapping of struct names to an array of type objects (name + type).\nEach key corresponds to a type name (e.g., \"`EIP712Domain`\", \"`PermitTransferFrom`\").\n", + /// "description": "Information about the Virtual Asset Service Provider (VASP) for a deposit travel rule submission.", /// "examples": [ /// { - /// "EIP712Domain": [ - /// { - /// "name": "name", - /// "type": "string" - /// }, - /// { - /// "name": "chainId", - /// "type": "uint256" - /// }, - /// { - /// "name": "verifyingContract", - /// "type": "address" - /// } + /// "identifier": "5493001KJTIIGC8Y1R17", + /// "name": "Fidelity Digital Asset Services, LLC" + /// } + /// ], + /// "type": "object", + /// "properties": { + /// "identifier": { + /// "description": "The Legal Entity Identifier (LEI) of the Virtual Asset Service Provider (VASP).", + /// "examples": [ + /// "5493001KJTIIGC8Y1R17" /// ], - /// "PermitTransferFrom": [ - /// { - /// "name": "permitted", - /// "type": "TokenPermissions" - /// }, - /// { - /// "name": "spender", - /// "type": "address" - /// }, - /// { - /// "name": "nonce", - /// "type": "uint256" - /// }, - /// { - /// "name": "deadline", - /// "type": "uint256" - /// } + /// "type": "string" + /// }, + /// "name": { + /// "description": "The name of the Virtual Asset Service Provider (VASP).", + /// "examples": [ + /// "Fidelity Digital Asset Services, LLC" /// ], - /// "TokenPermissions": [ - /// { - /// "name": "token", - /// "type": "address" - /// }, - /// { - /// "name": "amount", - /// "type": "uint256" - /// } - /// ] + /// "type": "string" /// } - /// ], - /// "type": "object" + /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct DepositTravelRuleVasp { + ///The Legal Entity Identifier (LEI) of the Virtual Asset Service Provider (VASP). + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub identifier: ::std::option::Option<::std::string::String>, + ///The name of the Virtual Asset Service Provider (VASP). + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub name: ::std::option::Option<::std::string::String>, + } + impl ::std::convert::From<&DepositTravelRuleVasp> for DepositTravelRuleVasp { + fn from(value: &DepositTravelRuleVasp) -> Self { + value.clone() + } + } + impl ::std::default::Default for DepositTravelRuleVasp { + fn default() -> Self { + Self { + identifier: Default::default(), + name: Default::default(), + } + } + } + impl DepositTravelRuleVasp { + pub fn builder() -> builder::DepositTravelRuleVasp { + Default::default() + } + } + ///A human-readable description. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "A human-readable description.", + /// "examples": [ + /// "A description of the resource." + /// ], + /// "type": "string", + /// "maxLength": 500 + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct Eip712Types(pub ::serde_json::Map<::std::string::String, ::serde_json::Value>); - impl ::std::ops::Deref for Eip712Types { - type Target = ::serde_json::Map<::std::string::String, ::serde_json::Value>; - fn deref(&self) -> &::serde_json::Map<::std::string::String, ::serde_json::Value> { + pub struct Description(::std::string::String); + impl ::std::ops::Deref for Description { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From - for ::serde_json::Map<::std::string::String, ::serde_json::Value> - { - fn from(value: Eip712Types) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: Description) -> Self { value.0 } } - impl ::std::convert::From<&Eip712Types> for Eip712Types { - fn from(value: &Eip712Types) -> Self { + impl ::std::convert::From<&Description> for Description { + fn from(value: &Description) -> Self { value.clone() } } - impl ::std::convert::From<::serde_json::Map<::std::string::String, ::serde_json::Value>> - for Eip712Types - { - fn from(value: ::serde_json::Map<::std::string::String, ::serde_json::Value>) -> Self { - Self(value) + impl ::std::str::FromStr for Description { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + if value.chars().count() > 500usize { + return Err("longer than 500 characters".into()); + } + Ok(Self(value.to_string())) } } - ///Information about an end user who authenticates using a one-time password sent to their email address. + impl ::std::convert::TryFrom<&str> for Description { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for Description { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for Description { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for Description { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///Information about an end user who authenticates using a JWT issued by the developer. /// ///
JSON schema /// /// ```json ///{ - /// "title": "EmailAuthentication", - /// "description": "Information about an end user who authenticates using a one-time password sent to their email address.", + /// "title": "DeveloperJWTAuthentication", + /// "description": "Information about an end user who authenticates using a JWT issued by the developer.", /// "type": "object", /// "required": [ - /// "email", + /// "kid", + /// "sub", /// "type" /// ], /// "properties": { - /// "email": { - /// "description": "The email address of the end user.", + /// "kid": { + /// "description": "The key ID of the JWK used to sign the JWT.", /// "examples": [ - /// "user@example.com" + /// "NjVBRjY5MDlCMUIwNzU4RTA2QzZFMDQ4QzQ2MDAyQjVDNjk1RTM2Qg" /// ], - /// "type": "string", - /// "format": "email" + /// "type": "string" + /// }, + /// "sub": { + /// "description": "The unique identifier for the end user that is captured in the `sub` claim of the JWT.", + /// "examples": [ + /// "e051beeb-7163-4527-a5b6-35e301529ff2" + /// ], + /// "type": "string" /// }, /// "type": { /// "description": "The type of authentication information.", /// "examples": [ - /// "email" + /// "jwt" /// ], /// "type": "string", /// "enum": [ - /// "email" + /// "jwt" /// ] /// } /// } @@ -11397,20 +13209,22 @@ pub mod types { /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct EmailAuthentication { - ///The email address of the end user. - pub email: ::std::string::String, + pub struct DeveloperJwtAuthentication { + ///The key ID of the JWK used to sign the JWT. + pub kid: ::std::string::String, + ///The unique identifier for the end user that is captured in the `sub` claim of the JWT. + pub sub: ::std::string::String, ///The type of authentication information. #[serde(rename = "type")] - pub type_: EmailAuthenticationType, + pub type_: DeveloperJwtAuthenticationType, } - impl ::std::convert::From<&EmailAuthentication> for EmailAuthentication { - fn from(value: &EmailAuthentication) -> Self { + impl ::std::convert::From<&DeveloperJwtAuthentication> for DeveloperJwtAuthentication { + fn from(value: &DeveloperJwtAuthentication) -> Self { value.clone() } } - impl EmailAuthentication { - pub fn builder() -> builder::EmailAuthentication { + impl DeveloperJwtAuthentication { + pub fn builder() -> builder::DeveloperJwtAuthentication { Default::default() } } @@ -11422,11 +13236,11 @@ pub mod types { ///{ /// "description": "The type of authentication information.", /// "examples": [ - /// "email" + /// "jwt" /// ], /// "type": "string", /// "enum": [ - /// "email" + /// "jwt" /// ] ///} /// ``` @@ -11443,38 +13257,38 @@ pub mod types { PartialEq, PartialOrd, )] - pub enum EmailAuthenticationType { - #[serde(rename = "email")] - Email, + pub enum DeveloperJwtAuthenticationType { + #[serde(rename = "jwt")] + Jwt, } - impl ::std::convert::From<&Self> for EmailAuthenticationType { - fn from(value: &EmailAuthenticationType) -> Self { + impl ::std::convert::From<&Self> for DeveloperJwtAuthenticationType { + fn from(value: &DeveloperJwtAuthenticationType) -> Self { value.clone() } } - impl ::std::fmt::Display for EmailAuthenticationType { + impl ::std::fmt::Display for DeveloperJwtAuthenticationType { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match *self { - Self::Email => f.write_str("email"), + Self::Jwt => f.write_str("jwt"), } } } - impl ::std::str::FromStr for EmailAuthenticationType { + impl ::std::str::FromStr for DeveloperJwtAuthenticationType { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { match value { - "email" => Ok(Self::Email), + "jwt" => Ok(Self::Jwt), _ => Err("invalid value".into()), } } } - impl ::std::convert::TryFrom<&str> for EmailAuthenticationType { + impl ::std::convert::TryFrom<&str> for DeveloperJwtAuthenticationType { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for EmailAuthenticationType { + impl ::std::convert::TryFrom<&::std::string::String> for DeveloperJwtAuthenticationType { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -11482,7 +13296,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for EmailAuthenticationType { + impl ::std::convert::TryFrom<::std::string::String> for DeveloperJwtAuthenticationType { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -11490,313 +13304,165 @@ pub mod types { value.parse() } } - ///Information about the end user. + ///The domain of the EIP-712 typed data. /// ///
JSON schema /// /// ```json ///{ - /// "description": "Information about the end user.", - /// "type": "object", - /// "required": [ - /// "authenticationMethods", - /// "createdAt", - /// "evmAccountObjects", - /// "evmAccounts", - /// "evmSmartAccountObjects", - /// "evmSmartAccounts", - /// "solanaAccountObjects", - /// "solanaAccounts", - /// "userId" + /// "description": "The domain of the EIP-712 typed data.", + /// "examples": [ + /// { + /// "chainId": 1, + /// "name": "Permit2", + /// "verifyingContract": "0x000000000022D473030F116dDEE9F6B43aC78BA3" + /// } /// ], + /// "type": "object", /// "properties": { - /// "authenticationMethods": { - /// "$ref": "#/components/schemas/AuthenticationMethods" - /// }, - /// "createdAt": { - /// "description": "The date and time when the end user was created, in ISO 8601 format.", - /// "examples": [ - /// "2025-01-15T10:30:00Z" - /// ], - /// "type": "string", - /// "format": "date-time" - /// }, - /// "evmAccountObjects": { - /// "description": "The list of EVM accounts associated with the end user. End users can have up to 10 EVM accounts.", - /// "examples": [ - /// [ - /// { - /// "address": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "createdAt": "2025-01-15T10:30:00Z" - /// }, - /// { - /// "address": "0x1234567890abcdef1234567890abcdef12345678", - /// "createdAt": "2025-01-15T11:00:00Z" - /// } - /// ] - /// ], - /// "type": "array", - /// "items": { - /// "$ref": "#/components/schemas/EndUserEvmAccount" - /// } - /// }, - /// "evmAccounts": { - /// "description": "**DEPRECATED**: Use `evmAccountObjects` instead for richer account information. The list of EVM account addresses associated with the end user. End users can have up to 10 EVM accounts.", - /// "deprecated": true, + /// "chainId": { + /// "description": "The chain ID of the EVM network.", /// "examples": [ - /// [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" - /// ] + /// 1 /// ], - /// "type": "array", - /// "items": { - /// "description": "The address of the EVM account associated with the end user.", - /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" - /// } + /// "type": "integer", + /// "format": "int64" /// }, - /// "evmSmartAccountObjects": { - /// "description": "The list of EVM smart accounts associated with the end user. Each EVM EOA can own one smart account.", + /// "name": { + /// "description": "The name of the DApp or protocol.", /// "examples": [ - /// [ - /// { - /// "address": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "createdAt": "2025-01-15T12:00:00Z", - /// "ownerAddresses": [ - /// "0x1234567890abcdef1234567890abcdef12345678", - /// "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd" - /// ] - /// } - /// ] + /// "Permit2" /// ], - /// "type": "array", - /// "items": { - /// "$ref": "#/components/schemas/EndUserEvmSmartAccount" - /// } + /// "type": "string" /// }, - /// "evmSmartAccounts": { - /// "description": "**DEPRECATED**: Use `evmSmartAccountObjects` instead for richer account information including owner relationships. The list of EVM smart account addresses associated with the end user. Each EVM EOA can own one smart account.", - /// "deprecated": true, + /// "salt": { + /// "description": "The optional 32-byte 0x-prefixed hex salt for domain separation.", /// "examples": [ - /// [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" - /// ] + /// "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" /// ], - /// "type": "array", - /// "items": { - /// "description": "The address of the EVM smart account associated with the end user.", - /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" - /// } - /// }, - /// "mfaMethods": { - /// "$ref": "#/components/schemas/MFAMethods" + /// "type": "string", + /// "pattern": "^0x[a-fA-F0-9]{64}$" /// }, - /// "solanaAccountObjects": { - /// "description": "The list of Solana accounts associated with the end user. End users can have up to 10 Solana accounts.", + /// "verifyingContract": { + /// "description": "The 0x-prefixed EVM address of the verifying smart contract.", /// "examples": [ - /// [ - /// { - /// "address": "HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT", - /// "createdAt": "2025-01-15T10:30:00Z" - /// }, - /// { - /// "address": "9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin", - /// "createdAt": "2025-01-15T11:30:00Z" - /// } - /// ] + /// "0x000000000022D473030F116dDEE9F6B43aC78BA3" /// ], - /// "type": "array", - /// "items": { - /// "$ref": "#/components/schemas/EndUserSolanaAccount" - /// } + /// "type": "string", + /// "pattern": "^0x[a-fA-F0-9]{40}$" /// }, - /// "solanaAccounts": { - /// "description": "**DEPRECATED**: Use `solanaAccountObjects` instead for richer account information. The list of Solana account addresses associated with the end user. End users can have up to 10 Solana accounts.", - /// "deprecated": true, + /// "version": { + /// "description": "The version of the DApp or protocol.", /// "examples": [ - /// [ - /// "HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT" - /// ] + /// "1" /// ], - /// "type": "array", - /// "items": { - /// "description": "The base58 encoded address of the Solana account associated with the end user.", - /// "examples": [ - /// "HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT" - /// ], - /// "type": "string", - /// "pattern": "^[1-9A-HJ-NP-Za-km-z]{32,44}$" - /// } - /// }, - /// "userId": { - /// "description": "A stable, unique identifier for the end user. The `userId` must be unique across all end users in the developer's CDP Project. It must be between 1 and 100 characters long and can only contain alphanumeric characters and hyphens.", - /// "examples": [ - /// "e051beeb-7163-4527-a5b6-35e301529ff2" - /// ], - /// "type": "string", - /// "pattern": "^[a-zA-Z0-9-]{1,100}$" + /// "type": "string" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct EndUser { - #[serde(rename = "authenticationMethods")] - pub authentication_methods: AuthenticationMethods, - ///The date and time when the end user was created, in ISO 8601 format. - #[serde(rename = "createdAt")] - pub created_at: ::chrono::DateTime<::chrono::offset::Utc>, - ///The list of EVM accounts associated with the end user. End users can have up to 10 EVM accounts. - #[serde(rename = "evmAccountObjects")] - pub evm_account_objects: ::std::vec::Vec, - ///**DEPRECATED**: Use `evmAccountObjects` instead for richer account information. The list of EVM account addresses associated with the end user. End users can have up to 10 EVM accounts. - #[serde(rename = "evmAccounts")] - pub evm_accounts: ::std::vec::Vec, - ///The list of EVM smart accounts associated with the end user. Each EVM EOA can own one smart account. - #[serde(rename = "evmSmartAccountObjects")] - pub evm_smart_account_objects: ::std::vec::Vec, - ///**DEPRECATED**: Use `evmSmartAccountObjects` instead for richer account information including owner relationships. The list of EVM smart account addresses associated with the end user. Each EVM EOA can own one smart account. - #[serde(rename = "evmSmartAccounts")] - pub evm_smart_accounts: ::std::vec::Vec, + pub struct Eip712Domain { + ///The chain ID of the EVM network. #[serde( - rename = "mfaMethods", + rename = "chainId", default, skip_serializing_if = "::std::option::Option::is_none" )] - pub mfa_methods: ::std::option::Option, - ///The list of Solana accounts associated with the end user. End users can have up to 10 Solana accounts. - #[serde(rename = "solanaAccountObjects")] - pub solana_account_objects: ::std::vec::Vec, - ///**DEPRECATED**: Use `solanaAccountObjects` instead for richer account information. The list of Solana account addresses associated with the end user. End users can have up to 10 Solana accounts. - #[serde(rename = "solanaAccounts")] - pub solana_accounts: ::std::vec::Vec, - ///A stable, unique identifier for the end user. The `userId` must be unique across all end users in the developer's CDP Project. It must be between 1 and 100 characters long and can only contain alphanumeric characters and hyphens. - #[serde(rename = "userId")] - pub user_id: EndUserUserId, + pub chain_id: ::std::option::Option, + ///The name of the DApp or protocol. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub name: ::std::option::Option<::std::string::String>, + ///The optional 32-byte 0x-prefixed hex salt for domain separation. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub salt: ::std::option::Option, + ///The 0x-prefixed EVM address of the verifying smart contract. + #[serde( + rename = "verifyingContract", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub verifying_contract: ::std::option::Option, + ///The version of the DApp or protocol. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub version: ::std::option::Option<::std::string::String>, } - impl ::std::convert::From<&EndUser> for EndUser { - fn from(value: &EndUser) -> Self { + impl ::std::convert::From<&Eip712Domain> for Eip712Domain { + fn from(value: &Eip712Domain) -> Self { value.clone() } } - impl EndUser { - pub fn builder() -> builder::EndUser { - Default::default() - } - } - ///Information about an EVM account associated with an end user. - /// - ///
JSON schema - /// - /// ```json - ///{ - /// "description": "Information about an EVM account associated with an end user.", - /// "type": "object", - /// "required": [ - /// "address", - /// "createdAt" - /// ], - /// "properties": { - /// "address": { - /// "description": "The address of the EVM account.", - /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" - /// }, - /// "createdAt": { - /// "description": "The date and time when the account was created, in ISO 8601 format.", - /// "examples": [ - /// "2025-01-15T10:30:00Z" - /// ], - /// "type": "string", - /// "format": "date-time" - /// } - /// } - ///} - /// ``` - ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct EndUserEvmAccount { - ///The address of the EVM account. - pub address: EndUserEvmAccountAddress, - ///The date and time when the account was created, in ISO 8601 format. - #[serde(rename = "createdAt")] - pub created_at: ::chrono::DateTime<::chrono::offset::Utc>, - } - impl ::std::convert::From<&EndUserEvmAccount> for EndUserEvmAccount { - fn from(value: &EndUserEvmAccount) -> Self { - value.clone() + impl ::std::default::Default for Eip712Domain { + fn default() -> Self { + Self { + chain_id: Default::default(), + name: Default::default(), + salt: Default::default(), + verifying_contract: Default::default(), + version: Default::default(), + } } } - impl EndUserEvmAccount { - pub fn builder() -> builder::EndUserEvmAccount { + impl Eip712Domain { + pub fn builder() -> builder::Eip712Domain { Default::default() } } - ///The address of the EVM account. + ///The optional 32-byte 0x-prefixed hex salt for domain separation. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The address of the EVM account.", + /// "description": "The optional 32-byte 0x-prefixed hex salt for domain separation.", /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" /// ], /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// "pattern": "^0x[a-fA-F0-9]{64}$" ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct EndUserEvmAccountAddress(::std::string::String); - impl ::std::ops::Deref for EndUserEvmAccountAddress { + pub struct Eip712DomainSalt(::std::string::String); + impl ::std::ops::Deref for Eip712DomainSalt { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: EndUserEvmAccountAddress) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: Eip712DomainSalt) -> Self { value.0 } } - impl ::std::convert::From<&EndUserEvmAccountAddress> for EndUserEvmAccountAddress { - fn from(value: &EndUserEvmAccountAddress) -> Self { + impl ::std::convert::From<&Eip712DomainSalt> for Eip712DomainSalt { + fn from(value: &Eip712DomainSalt) -> Self { value.clone() } } - impl ::std::str::FromStr for EndUserEvmAccountAddress { + impl ::std::str::FromStr for Eip712DomainSalt { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() + ::regress::Regex::new("^0x[a-fA-F0-9]{64}$").unwrap() }); if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); + return Err("doesn't match pattern \"^0x[a-fA-F0-9]{64}$\"".into()); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for EndUserEvmAccountAddress { + impl ::std::convert::TryFrom<&str> for Eip712DomainSalt { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for EndUserEvmAccountAddress { + impl ::std::convert::TryFrom<&::std::string::String> for Eip712DomainSalt { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -11804,7 +13470,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for EndUserEvmAccountAddress { + impl ::std::convert::TryFrom<::std::string::String> for Eip712DomainSalt { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -11812,7 +13478,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for EndUserEvmAccountAddress { + impl<'de> ::serde::Deserialize<'de> for Eip712DomainSalt { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -11824,60 +13490,60 @@ pub mod types { }) } } - ///The address of the EVM account associated with the end user. + ///The 0x-prefixed EVM address of the verifying smart contract. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The address of the EVM account associated with the end user.", + /// "description": "The 0x-prefixed EVM address of the verifying smart contract.", /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// "0x000000000022D473030F116dDEE9F6B43aC78BA3" /// ], /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// "pattern": "^0x[a-fA-F0-9]{40}$" ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct EndUserEvmAccountsItem(::std::string::String); - impl ::std::ops::Deref for EndUserEvmAccountsItem { + pub struct Eip712DomainVerifyingContract(::std::string::String); + impl ::std::ops::Deref for Eip712DomainVerifyingContract { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: EndUserEvmAccountsItem) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: Eip712DomainVerifyingContract) -> Self { value.0 } } - impl ::std::convert::From<&EndUserEvmAccountsItem> for EndUserEvmAccountsItem { - fn from(value: &EndUserEvmAccountsItem) -> Self { + impl ::std::convert::From<&Eip712DomainVerifyingContract> for Eip712DomainVerifyingContract { + fn from(value: &Eip712DomainVerifyingContract) -> Self { value.clone() } } - impl ::std::str::FromStr for EndUserEvmAccountsItem { + impl ::std::str::FromStr for Eip712DomainVerifyingContract { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() + ::regress::Regex::new("^0x[a-fA-F0-9]{40}$").unwrap() }); if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); + return Err("doesn't match pattern \"^0x[a-fA-F0-9]{40}$\"".into()); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for EndUserEvmAccountsItem { + impl ::std::convert::TryFrom<&str> for Eip712DomainVerifyingContract { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for EndUserEvmAccountsItem { + impl ::std::convert::TryFrom<&::std::string::String> for Eip712DomainVerifyingContract { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -11885,7 +13551,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for EndUserEvmAccountsItem { + impl ::std::convert::TryFrom<::std::string::String> for Eip712DomainVerifyingContract { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -11893,7 +13559,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for EndUserEvmAccountsItem { + impl<'de> ::serde::Deserialize<'de> for Eip712DomainVerifyingContract { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -11905,297 +13571,380 @@ pub mod types { }) } } - ///Information about an EVM smart account associated with an end user. + ///The message to sign using EIP-712. /// ///
JSON schema /// /// ```json ///{ - /// "description": "Information about an EVM smart account associated with an end user.", + /// "description": "The message to sign using EIP-712.", + /// "examples": [ + /// { + /// "domain": { + /// "chainId": 1, + /// "name": "Permit2", + /// "verifyingContract": "0x000000000022D473030F116dDEE9F6B43aC78BA3" + /// }, + /// "message": { + /// "deadline": "1717123200", + /// "nonce": "123456", + /// "permitted": { + /// "amount": "1000000", + /// "token": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" + /// }, + /// "spender": "0xFfFfFfFFfFFfFFfFFfFFFFFffFFFffffFfFFFfFf" + /// }, + /// "primaryType": "PermitTransferFrom", + /// "types": { + /// "EIP712Domain": [ + /// { + /// "name": "name", + /// "type": "string" + /// }, + /// { + /// "name": "chainId", + /// "type": "uint256" + /// }, + /// { + /// "name": "verifyingContract", + /// "type": "address" + /// } + /// ], + /// "PermitTransferFrom": [ + /// { + /// "name": "permitted", + /// "type": "TokenPermissions" + /// }, + /// { + /// "name": "spender", + /// "type": "address" + /// }, + /// { + /// "name": "nonce", + /// "type": "uint256" + /// }, + /// { + /// "name": "deadline", + /// "type": "uint256" + /// } + /// ], + /// "TokenPermissions": [ + /// { + /// "name": "token", + /// "type": "address" + /// }, + /// { + /// "name": "amount", + /// "type": "uint256" + /// } + /// ] + /// } + /// } + /// ], /// "type": "object", /// "required": [ - /// "address", - /// "createdAt", - /// "ownerAddresses" + /// "domain", + /// "message", + /// "primaryType", + /// "types" /// ], /// "properties": { - /// "address": { - /// "description": "The address of the EVM smart account.", - /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// "domain": { + /// "$ref": "#/components/schemas/EIP712Domain" /// }, - /// "createdAt": { - /// "description": "The date and time when the account was created, in ISO 8601 format.", + /// "message": { + /// "description": "The message to sign. The structure of this message must match the `primaryType` struct in the `types` object.", /// "examples": [ - /// "2025-01-15T10:30:00Z" + /// { + /// "deadline": "1716239020", + /// "nonce": "0", + /// "permitted": { + /// "amount": "1000000", + /// "token": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" + /// }, + /// "spender": "0x1111111254EEB25477B68fb85Ed929f73A960582" + /// } /// ], - /// "type": "string", - /// "format": "date-time" + /// "type": "object" /// }, - /// "ownerAddresses": { - /// "description": "The addresses of the EVM EOA accounts that own this smart account. Smart accounts can have multiple owners, such as when spend permissions are enabled.", + /// "primaryType": { + /// "description": "The primary type of the message. This is the name of the struct in the `types` object that is the root of the message.", /// "examples": [ - /// [ - /// "0x1234567890abcdef1234567890abcdef12345678", - /// "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd" - /// ] + /// "PermitTransferFrom" /// ], - /// "type": "array", - /// "items": { - /// "description": "The address of an EVM EOA account that owns this smart account.", - /// "examples": [ - /// "0x1234567890abcdef1234567890abcdef12345678" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" - /// } + /// "type": "string" + /// }, + /// "types": { + /// "$ref": "#/components/schemas/EIP712Types" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct EndUserEvmSmartAccount { - ///The address of the EVM smart account. - pub address: EndUserEvmSmartAccountAddress, - ///The date and time when the account was created, in ISO 8601 format. - #[serde(rename = "createdAt")] - pub created_at: ::chrono::DateTime<::chrono::offset::Utc>, - ///The addresses of the EVM EOA accounts that own this smart account. Smart accounts can have multiple owners, such as when spend permissions are enabled. - #[serde(rename = "ownerAddresses")] - pub owner_addresses: ::std::vec::Vec, + pub struct Eip712Message { + pub domain: Eip712Domain, + ///The message to sign. The structure of this message must match the `primaryType` struct in the `types` object. + pub message: ::serde_json::Map<::std::string::String, ::serde_json::Value>, + ///The primary type of the message. This is the name of the struct in the `types` object that is the root of the message. + #[serde(rename = "primaryType")] + pub primary_type: ::std::string::String, + pub types: Eip712Types, } - impl ::std::convert::From<&EndUserEvmSmartAccount> for EndUserEvmSmartAccount { - fn from(value: &EndUserEvmSmartAccount) -> Self { + impl ::std::convert::From<&Eip712Message> for Eip712Message { + fn from(value: &Eip712Message) -> Self { value.clone() } } - impl EndUserEvmSmartAccount { - pub fn builder() -> builder::EndUserEvmSmartAccount { + impl Eip712Message { + pub fn builder() -> builder::Eip712Message { Default::default() } } - ///The address of the EVM smart account. + /**A mapping of struct names to an array of type objects (name + type). + Each key corresponds to a type name (e.g., "`EIP712Domain`", "`PermitTransferFrom`"). + */ /// ///
JSON schema /// /// ```json ///{ - /// "description": "The address of the EVM smart account.", + /// "description": "A mapping of struct names to an array of type objects (name + type).\nEach key corresponds to a type name (e.g., \"`EIP712Domain`\", \"`PermitTransferFrom`\").\n", /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// { + /// "EIP712Domain": [ + /// { + /// "name": "name", + /// "type": "string" + /// }, + /// { + /// "name": "chainId", + /// "type": "uint256" + /// }, + /// { + /// "name": "verifyingContract", + /// "type": "address" + /// } + /// ], + /// "PermitTransferFrom": [ + /// { + /// "name": "permitted", + /// "type": "TokenPermissions" + /// }, + /// { + /// "name": "spender", + /// "type": "address" + /// }, + /// { + /// "name": "nonce", + /// "type": "uint256" + /// }, + /// { + /// "name": "deadline", + /// "type": "uint256" + /// } + /// ], + /// "TokenPermissions": [ + /// { + /// "name": "token", + /// "type": "address" + /// }, + /// { + /// "name": "amount", + /// "type": "uint256" + /// } + /// ] + /// } /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// "type": "object" ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] #[serde(transparent)] - pub struct EndUserEvmSmartAccountAddress(::std::string::String); - impl ::std::ops::Deref for EndUserEvmSmartAccountAddress { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { + pub struct Eip712Types(pub ::serde_json::Map<::std::string::String, ::serde_json::Value>); + impl ::std::ops::Deref for Eip712Types { + type Target = ::serde_json::Map<::std::string::String, ::serde_json::Value>; + fn deref(&self) -> &::serde_json::Map<::std::string::String, ::serde_json::Value> { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: EndUserEvmSmartAccountAddress) -> Self { + impl ::std::convert::From + for ::serde_json::Map<::std::string::String, ::serde_json::Value> + { + fn from(value: Eip712Types) -> Self { value.0 } } - impl ::std::convert::From<&EndUserEvmSmartAccountAddress> for EndUserEvmSmartAccountAddress { - fn from(value: &EndUserEvmSmartAccountAddress) -> Self { + impl ::std::convert::From<&Eip712Types> for Eip712Types { + fn from(value: &Eip712Types) -> Self { value.clone() } } - impl ::std::str::FromStr for EndUserEvmSmartAccountAddress { - type Err = self::error::ConversionError; - fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() - }); - if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); - } - Ok(Self(value.to_string())) - } - } - impl ::std::convert::TryFrom<&str> for EndUserEvmSmartAccountAddress { - type Error = self::error::ConversionError; - fn try_from(value: &str) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<&::std::string::String> for EndUserEvmSmartAccountAddress { - type Error = self::error::ConversionError; - fn try_from( - value: &::std::string::String, - ) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<::std::string::String> for EndUserEvmSmartAccountAddress { - type Error = self::error::ConversionError; - fn try_from( - value: ::std::string::String, - ) -> ::std::result::Result { - value.parse() - } - } - impl<'de> ::serde::Deserialize<'de> for EndUserEvmSmartAccountAddress { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) + impl ::std::convert::From<::serde_json::Map<::std::string::String, ::serde_json::Value>> + for Eip712Types + { + fn from(value: ::serde_json::Map<::std::string::String, ::serde_json::Value>) -> Self { + Self(value) } } - ///The address of an EVM EOA account that owns this smart account. + ///The target of the payment is an email address. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The address of an EVM EOA account that owns this smart account.", + /// "title": "Email Address", + /// "description": "The target of the payment is an email address.", /// "examples": [ - /// "0x1234567890abcdef1234567890abcdef12345678" + /// { + /// "email": "recipient@example.com" + /// } /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// "type": "object", + /// "required": [ + /// "email" + /// ], + /// "properties": { + /// "email": { + /// "description": "The email address of the recipient. The recipient will need to have an account with Coinbase or onboard to Coinbase to receive the payment.", + /// "type": "string", + /// "format": "email" + /// } + /// } ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct EndUserEvmSmartAccountOwnerAddressesItem(::std::string::String); - impl ::std::ops::Deref for EndUserEvmSmartAccountOwnerAddressesItem { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } + #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct EmailAddress { + ///The email address of the recipient. The recipient will need to have an account with Coinbase or onboard to Coinbase to receive the payment. + pub email: ::std::string::String, } - impl ::std::convert::From for ::std::string::String { - fn from(value: EndUserEvmSmartAccountOwnerAddressesItem) -> Self { - value.0 + impl ::std::convert::From<&EmailAddress> for EmailAddress { + fn from(value: &EmailAddress) -> Self { + value.clone() } } - impl ::std::convert::From<&EndUserEvmSmartAccountOwnerAddressesItem> - for EndUserEvmSmartAccountOwnerAddressesItem - { - fn from(value: &EndUserEvmSmartAccountOwnerAddressesItem) -> Self { - value.clone() + impl EmailAddress { + pub fn builder() -> builder::EmailAddress { + Default::default() } } - impl ::std::str::FromStr for EndUserEvmSmartAccountOwnerAddressesItem { - type Err = self::error::ConversionError; - fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() - }); - if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); - } - Ok(Self(value.to_string())) - } - } - impl ::std::convert::TryFrom<&str> for EndUserEvmSmartAccountOwnerAddressesItem { - type Error = self::error::ConversionError; - fn try_from(value: &str) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<&::std::string::String> for EndUserEvmSmartAccountOwnerAddressesItem { - type Error = self::error::ConversionError; - fn try_from( - value: &::std::string::String, - ) -> ::std::result::Result { - value.parse() - } + ///Information about an end user who authenticates using a one-time password sent to their email address. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "title": "EmailAuthentication", + /// "description": "Information about an end user who authenticates using a one-time password sent to their email address.", + /// "type": "object", + /// "required": [ + /// "email", + /// "type" + /// ], + /// "properties": { + /// "email": { + /// "description": "The email address of the end user.", + /// "examples": [ + /// "user@example.com" + /// ], + /// "type": "string", + /// "format": "email" + /// }, + /// "type": { + /// "description": "The type of authentication information.", + /// "examples": [ + /// "email" + /// ], + /// "type": "string", + /// "enum": [ + /// "email" + /// ] + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct EmailAuthentication { + ///The email address of the end user. + pub email: ::std::string::String, + ///The type of authentication information. + #[serde(rename = "type")] + pub type_: EmailAuthenticationType, } - impl ::std::convert::TryFrom<::std::string::String> for EndUserEvmSmartAccountOwnerAddressesItem { - type Error = self::error::ConversionError; - fn try_from( - value: ::std::string::String, - ) -> ::std::result::Result { - value.parse() + impl ::std::convert::From<&EmailAuthentication> for EmailAuthentication { + fn from(value: &EmailAuthentication) -> Self { + value.clone() } } - impl<'de> ::serde::Deserialize<'de> for EndUserEvmSmartAccountOwnerAddressesItem { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) + impl EmailAuthentication { + pub fn builder() -> builder::EmailAuthentication { + Default::default() } } - ///The address of the EVM smart account associated with the end user. + ///The type of authentication information. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The address of the EVM smart account associated with the end user.", + /// "description": "The type of authentication information.", /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// "email" /// ], /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// "enum": [ + /// "email" + /// ] ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct EndUserEvmSmartAccountsItem(::std::string::String); - impl ::std::ops::Deref for EndUserEvmSmartAccountsItem { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } + #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum EmailAuthenticationType { + #[serde(rename = "email")] + Email, } - impl ::std::convert::From for ::std::string::String { - fn from(value: EndUserEvmSmartAccountsItem) -> Self { - value.0 + impl ::std::convert::From<&Self> for EmailAuthenticationType { + fn from(value: &EmailAuthenticationType) -> Self { + value.clone() } } - impl ::std::convert::From<&EndUserEvmSmartAccountsItem> for EndUserEvmSmartAccountsItem { - fn from(value: &EndUserEvmSmartAccountsItem) -> Self { - value.clone() + impl ::std::fmt::Display for EmailAuthenticationType { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Email => f.write_str("email"), + } } } - impl ::std::str::FromStr for EndUserEvmSmartAccountsItem { + impl ::std::str::FromStr for EmailAuthenticationType { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() - }); - if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); + match value { + "email" => Ok(Self::Email), + _ => Err("invalid value".into()), } - Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for EndUserEvmSmartAccountsItem { + impl ::std::convert::TryFrom<&str> for EmailAuthenticationType { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for EndUserEvmSmartAccountsItem { + impl ::std::convert::TryFrom<&::std::string::String> for EmailAuthenticationType { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -12203,7 +13952,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for EndUserEvmSmartAccountsItem { + impl ::std::convert::TryFrom<::std::string::String> for EmailAuthenticationType { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -12211,25 +13960,270 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for EndUserEvmSmartAccountsItem { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) + ///The target of the payment is an email address. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "title": "Email Instrument", + /// "description": "The target of the payment is an email address.", + /// "examples": [ + /// { + /// "asset": "usd", + /// "email": "recipient@example.com" + /// } + /// ], + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/EmailAddress" + /// }, + /// { + /// "type": "object", + /// "required": [ + /// "asset" + /// ], + /// "properties": { + /// "asset": { + /// "description": "Asset symbol of the payment received by the recipient.", + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/Asset" + /// } + /// ] + /// } + /// } + /// } + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct EmailInstrument { + ///Asset symbol of the payment received by the recipient. + pub asset: Asset, + ///The email address of the recipient. The recipient will need to have an account with Coinbase or onboard to Coinbase to receive the payment. + pub email: ::std::string::String, + } + impl ::std::convert::From<&EmailInstrument> for EmailInstrument { + fn from(value: &EmailInstrument) -> Self { + value.clone() } } - ///Information about a Solana account associated with an end user. + impl EmailInstrument { + pub fn builder() -> builder::EmailInstrument { + Default::default() + } + } + ///Information about the end user. /// ///
JSON schema /// /// ```json ///{ - /// "description": "Information about a Solana account associated with an end user.", + /// "description": "Information about the end user.", + /// "type": "object", + /// "required": [ + /// "authenticationMethods", + /// "createdAt", + /// "evmAccountObjects", + /// "evmAccounts", + /// "evmSmartAccountObjects", + /// "evmSmartAccounts", + /// "solanaAccountObjects", + /// "solanaAccounts", + /// "userId" + /// ], + /// "properties": { + /// "authenticationMethods": { + /// "$ref": "#/components/schemas/AuthenticationMethods" + /// }, + /// "createdAt": { + /// "description": "The date and time when the end user was created, in ISO 8601 format.", + /// "examples": [ + /// "2025-01-15T10:30:00Z" + /// ], + /// "type": "string", + /// "format": "date-time" + /// }, + /// "evmAccountObjects": { + /// "description": "The list of EVM accounts associated with the end user. End users can have up to 10 EVM accounts.", + /// "examples": [ + /// [ + /// { + /// "address": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "createdAt": "2025-01-15T10:30:00Z" + /// }, + /// { + /// "address": "0x1234567890abcdef1234567890abcdef12345678", + /// "createdAt": "2025-01-15T11:00:00Z" + /// } + /// ] + /// ], + /// "type": "array", + /// "items": { + /// "$ref": "#/components/schemas/EndUserEvmAccount" + /// } + /// }, + /// "evmAccounts": { + /// "description": "**DEPRECATED**: Use `evmAccountObjects` instead for richer account information. The list of EVM account addresses associated with the end user. End users can have up to 10 EVM accounts.", + /// "deprecated": true, + /// "examples": [ + /// [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ] + /// ], + /// "type": "array", + /// "items": { + /// "description": "The address of the EVM account associated with the end user.", + /// "examples": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// } + /// }, + /// "evmSmartAccountObjects": { + /// "description": "The list of EVM smart accounts associated with the end user. Each EVM EOA can own one smart account.", + /// "examples": [ + /// [ + /// { + /// "address": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "createdAt": "2025-01-15T12:00:00Z", + /// "ownerAddresses": [ + /// "0x1234567890abcdef1234567890abcdef12345678", + /// "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd" + /// ] + /// } + /// ] + /// ], + /// "type": "array", + /// "items": { + /// "$ref": "#/components/schemas/EndUserEvmSmartAccount" + /// } + /// }, + /// "evmSmartAccounts": { + /// "description": "**DEPRECATED**: Use `evmSmartAccountObjects` instead for richer account information including owner relationships. The list of EVM smart account addresses associated with the end user. Each EVM EOA can own one smart account.", + /// "deprecated": true, + /// "examples": [ + /// [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ] + /// ], + /// "type": "array", + /// "items": { + /// "description": "The address of the EVM smart account associated with the end user.", + /// "examples": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// } + /// }, + /// "mfaMethods": { + /// "$ref": "#/components/schemas/MFAMethods" + /// }, + /// "solanaAccountObjects": { + /// "description": "The list of Solana accounts associated with the end user. End users can have up to 10 Solana accounts.", + /// "examples": [ + /// [ + /// { + /// "address": "HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT", + /// "createdAt": "2025-01-15T10:30:00Z" + /// }, + /// { + /// "address": "9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin", + /// "createdAt": "2025-01-15T11:30:00Z" + /// } + /// ] + /// ], + /// "type": "array", + /// "items": { + /// "$ref": "#/components/schemas/EndUserSolanaAccount" + /// } + /// }, + /// "solanaAccounts": { + /// "description": "**DEPRECATED**: Use `solanaAccountObjects` instead for richer account information. The list of Solana account addresses associated with the end user. End users can have up to 10 Solana accounts.", + /// "deprecated": true, + /// "examples": [ + /// [ + /// "HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT" + /// ] + /// ], + /// "type": "array", + /// "items": { + /// "description": "The base58 encoded address of the Solana account associated with the end user.", + /// "examples": [ + /// "HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT" + /// ], + /// "type": "string", + /// "pattern": "^[1-9A-HJ-NP-Za-km-z]{32,44}$" + /// } + /// }, + /// "userId": { + /// "description": "A stable, unique identifier for the end user. The `userId` must be unique across all end users in the developer's CDP Project. It must be between 1 and 100 characters long and can only contain alphanumeric characters and hyphens.", + /// "examples": [ + /// "e051beeb-7163-4527-a5b6-35e301529ff2" + /// ], + /// "type": "string", + /// "pattern": "^[a-zA-Z0-9-]{1,100}$" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct EndUser { + #[serde(rename = "authenticationMethods")] + pub authentication_methods: AuthenticationMethods, + ///The date and time when the end user was created, in ISO 8601 format. + #[serde(rename = "createdAt")] + pub created_at: ::chrono::DateTime<::chrono::offset::Utc>, + ///The list of EVM accounts associated with the end user. End users can have up to 10 EVM accounts. + #[serde(rename = "evmAccountObjects")] + pub evm_account_objects: ::std::vec::Vec, + ///**DEPRECATED**: Use `evmAccountObjects` instead for richer account information. The list of EVM account addresses associated with the end user. End users can have up to 10 EVM accounts. + #[serde(rename = "evmAccounts")] + pub evm_accounts: ::std::vec::Vec, + ///The list of EVM smart accounts associated with the end user. Each EVM EOA can own one smart account. + #[serde(rename = "evmSmartAccountObjects")] + pub evm_smart_account_objects: ::std::vec::Vec, + ///**DEPRECATED**: Use `evmSmartAccountObjects` instead for richer account information including owner relationships. The list of EVM smart account addresses associated with the end user. Each EVM EOA can own one smart account. + #[serde(rename = "evmSmartAccounts")] + pub evm_smart_accounts: ::std::vec::Vec, + #[serde( + rename = "mfaMethods", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub mfa_methods: ::std::option::Option, + ///The list of Solana accounts associated with the end user. End users can have up to 10 Solana accounts. + #[serde(rename = "solanaAccountObjects")] + pub solana_account_objects: ::std::vec::Vec, + ///**DEPRECATED**: Use `solanaAccountObjects` instead for richer account information. The list of Solana account addresses associated with the end user. End users can have up to 10 Solana accounts. + #[serde(rename = "solanaAccounts")] + pub solana_accounts: ::std::vec::Vec, + ///A stable, unique identifier for the end user. The `userId` must be unique across all end users in the developer's CDP Project. It must be between 1 and 100 characters long and can only contain alphanumeric characters and hyphens. + #[serde(rename = "userId")] + pub user_id: EndUserUserId, + } + impl ::std::convert::From<&EndUser> for EndUser { + fn from(value: &EndUser) -> Self { + value.clone() + } + } + impl EndUser { + pub fn builder() -> builder::EndUser { + Default::default() + } + } + ///Information about an EVM account associated with an end user. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "Information about an EVM account associated with an end user.", /// "type": "object", /// "required": [ /// "address", @@ -12237,12 +14231,12 @@ pub mod types { /// ], /// "properties": { /// "address": { - /// "description": "The base58 encoded address of the Solana account.", + /// "description": "The address of the EVM account.", /// "examples": [ - /// "HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT" + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" /// ], /// "type": "string", - /// "pattern": "^[1-9A-HJ-NP-Za-km-z]{32,44}$" + /// "pattern": "^0x[0-9a-fA-F]{40}$" /// }, /// "createdAt": { /// "description": "The date and time when the account was created, in ISO 8601 format.", @@ -12257,77 +14251,77 @@ pub mod types { /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct EndUserSolanaAccount { - ///The base58 encoded address of the Solana account. - pub address: EndUserSolanaAccountAddress, + pub struct EndUserEvmAccount { + ///The address of the EVM account. + pub address: EndUserEvmAccountAddress, ///The date and time when the account was created, in ISO 8601 format. #[serde(rename = "createdAt")] pub created_at: ::chrono::DateTime<::chrono::offset::Utc>, } - impl ::std::convert::From<&EndUserSolanaAccount> for EndUserSolanaAccount { - fn from(value: &EndUserSolanaAccount) -> Self { + impl ::std::convert::From<&EndUserEvmAccount> for EndUserEvmAccount { + fn from(value: &EndUserEvmAccount) -> Self { value.clone() } } - impl EndUserSolanaAccount { - pub fn builder() -> builder::EndUserSolanaAccount { + impl EndUserEvmAccount { + pub fn builder() -> builder::EndUserEvmAccount { Default::default() } } - ///The base58 encoded address of the Solana account. + ///The address of the EVM account. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The base58 encoded address of the Solana account.", + /// "description": "The address of the EVM account.", /// "examples": [ - /// "HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT" + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" /// ], /// "type": "string", - /// "pattern": "^[1-9A-HJ-NP-Za-km-z]{32,44}$" + /// "pattern": "^0x[0-9a-fA-F]{40}$" ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct EndUserSolanaAccountAddress(::std::string::String); - impl ::std::ops::Deref for EndUserSolanaAccountAddress { + pub struct EndUserEvmAccountAddress(::std::string::String); + impl ::std::ops::Deref for EndUserEvmAccountAddress { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: EndUserSolanaAccountAddress) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: EndUserEvmAccountAddress) -> Self { value.0 } } - impl ::std::convert::From<&EndUserSolanaAccountAddress> for EndUserSolanaAccountAddress { - fn from(value: &EndUserSolanaAccountAddress) -> Self { + impl ::std::convert::From<&EndUserEvmAccountAddress> for EndUserEvmAccountAddress { + fn from(value: &EndUserEvmAccountAddress) -> Self { value.clone() } } - impl ::std::str::FromStr for EndUserSolanaAccountAddress { + impl ::std::str::FromStr for EndUserEvmAccountAddress { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^[1-9A-HJ-NP-Za-km-z]{32,44}$").unwrap() + ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() }); if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^[1-9A-HJ-NP-Za-km-z]{32,44}$\"".into()); + return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for EndUserSolanaAccountAddress { + impl ::std::convert::TryFrom<&str> for EndUserEvmAccountAddress { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for EndUserSolanaAccountAddress { + impl ::std::convert::TryFrom<&::std::string::String> for EndUserEvmAccountAddress { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -12335,7 +14329,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for EndUserSolanaAccountAddress { + impl ::std::convert::TryFrom<::std::string::String> for EndUserEvmAccountAddress { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -12343,7 +14337,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for EndUserSolanaAccountAddress { + impl<'de> ::serde::Deserialize<'de> for EndUserEvmAccountAddress { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -12355,60 +14349,60 @@ pub mod types { }) } } - ///The base58 encoded address of the Solana account associated with the end user. + ///The address of the EVM account associated with the end user. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The base58 encoded address of the Solana account associated with the end user.", + /// "description": "The address of the EVM account associated with the end user.", /// "examples": [ - /// "HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT" + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" /// ], /// "type": "string", - /// "pattern": "^[1-9A-HJ-NP-Za-km-z]{32,44}$" + /// "pattern": "^0x[0-9a-fA-F]{40}$" ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct EndUserSolanaAccountsItem(::std::string::String); - impl ::std::ops::Deref for EndUserSolanaAccountsItem { + pub struct EndUserEvmAccountsItem(::std::string::String); + impl ::std::ops::Deref for EndUserEvmAccountsItem { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: EndUserSolanaAccountsItem) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: EndUserEvmAccountsItem) -> Self { value.0 } } - impl ::std::convert::From<&EndUserSolanaAccountsItem> for EndUserSolanaAccountsItem { - fn from(value: &EndUserSolanaAccountsItem) -> Self { + impl ::std::convert::From<&EndUserEvmAccountsItem> for EndUserEvmAccountsItem { + fn from(value: &EndUserEvmAccountsItem) -> Self { value.clone() } } - impl ::std::str::FromStr for EndUserSolanaAccountsItem { + impl ::std::str::FromStr for EndUserEvmAccountsItem { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^[1-9A-HJ-NP-Za-km-z]{32,44}$").unwrap() + ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() }); if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^[1-9A-HJ-NP-Za-km-z]{32,44}$\"".into()); + return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for EndUserSolanaAccountsItem { + impl ::std::convert::TryFrom<&str> for EndUserEvmAccountsItem { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for EndUserSolanaAccountsItem { + impl ::std::convert::TryFrom<&::std::string::String> for EndUserEvmAccountsItem { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -12416,7 +14410,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for EndUserSolanaAccountsItem { + impl ::std::convert::TryFrom<::std::string::String> for EndUserEvmAccountsItem { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -12424,7 +14418,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for EndUserSolanaAccountsItem { + impl<'de> ::serde::Deserialize<'de> for EndUserEvmAccountsItem { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -12436,60 +14430,133 @@ pub mod types { }) } } - ///A stable, unique identifier for the end user. The `userId` must be unique across all end users in the developer's CDP Project. It must be between 1 and 100 characters long and can only contain alphanumeric characters and hyphens. + ///Information about an EVM smart account associated with an end user. /// ///
JSON schema /// /// ```json ///{ - /// "description": "A stable, unique identifier for the end user. The `userId` must be unique across all end users in the developer's CDP Project. It must be between 1 and 100 characters long and can only contain alphanumeric characters and hyphens.", - /// "examples": [ - /// "e051beeb-7163-4527-a5b6-35e301529ff2" + /// "description": "Information about an EVM smart account associated with an end user.", + /// "type": "object", + /// "required": [ + /// "address", + /// "createdAt", + /// "ownerAddresses" /// ], - /// "type": "string", - /// "pattern": "^[a-zA-Z0-9-]{1,100}$" - ///} - /// ``` - ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct EndUserUserId(::std::string::String); - impl ::std::ops::Deref for EndUserUserId { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } - } - impl ::std::convert::From for ::std::string::String { - fn from(value: EndUserUserId) -> Self { + /// "properties": { + /// "address": { + /// "description": "The address of the EVM smart account.", + /// "examples": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// }, + /// "createdAt": { + /// "description": "The date and time when the account was created, in ISO 8601 format.", + /// "examples": [ + /// "2025-01-15T10:30:00Z" + /// ], + /// "type": "string", + /// "format": "date-time" + /// }, + /// "ownerAddresses": { + /// "description": "The addresses of the EVM EOA accounts that own this smart account. Smart accounts can have multiple owners, such as when spend permissions are enabled.", + /// "examples": [ + /// [ + /// "0x1234567890abcdef1234567890abcdef12345678", + /// "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd" + /// ] + /// ], + /// "type": "array", + /// "items": { + /// "description": "The address of an EVM EOA account that owns this smart account.", + /// "examples": [ + /// "0x1234567890abcdef1234567890abcdef12345678" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// } + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct EndUserEvmSmartAccount { + ///The address of the EVM smart account. + pub address: EndUserEvmSmartAccountAddress, + ///The date and time when the account was created, in ISO 8601 format. + #[serde(rename = "createdAt")] + pub created_at: ::chrono::DateTime<::chrono::offset::Utc>, + ///The addresses of the EVM EOA accounts that own this smart account. Smart accounts can have multiple owners, such as when spend permissions are enabled. + #[serde(rename = "ownerAddresses")] + pub owner_addresses: ::std::vec::Vec, + } + impl ::std::convert::From<&EndUserEvmSmartAccount> for EndUserEvmSmartAccount { + fn from(value: &EndUserEvmSmartAccount) -> Self { + value.clone() + } + } + impl EndUserEvmSmartAccount { + pub fn builder() -> builder::EndUserEvmSmartAccount { + Default::default() + } + } + ///The address of the EVM smart account. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The address of the EVM smart account.", + /// "examples": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{40}$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct EndUserEvmSmartAccountAddress(::std::string::String); + impl ::std::ops::Deref for EndUserEvmSmartAccountAddress { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: EndUserEvmSmartAccountAddress) -> Self { value.0 } } - impl ::std::convert::From<&EndUserUserId> for EndUserUserId { - fn from(value: &EndUserUserId) -> Self { + impl ::std::convert::From<&EndUserEvmSmartAccountAddress> for EndUserEvmSmartAccountAddress { + fn from(value: &EndUserEvmSmartAccountAddress) -> Self { value.clone() } } - impl ::std::str::FromStr for EndUserUserId { + impl ::std::str::FromStr for EndUserEvmSmartAccountAddress { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^[a-zA-Z0-9-]{1,100}$").unwrap() + ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() }); if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^[a-zA-Z0-9-]{1,100}$\"".into()); + return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for EndUserUserId { + impl ::std::convert::TryFrom<&str> for EndUserEvmSmartAccountAddress { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for EndUserUserId { + impl ::std::convert::TryFrom<&::std::string::String> for EndUserEvmSmartAccountAddress { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -12497,7 +14564,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for EndUserUserId { + impl ::std::convert::TryFrom<::std::string::String> for EndUserEvmSmartAccountAddress { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -12505,7 +14572,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for EndUserUserId { + impl<'de> ::serde::Deserialize<'de> for EndUserEvmSmartAccountAddress { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -12517,266 +14584,742 @@ pub mod types { }) } } - ///An error response including the code for the type of error and a human-readable message describing the error. + ///The address of an EVM EOA account that owns this smart account. /// ///
JSON schema /// /// ```json ///{ - /// "description": "An error response including the code for the type of error and a human-readable message describing the error.", + /// "description": "The address of an EVM EOA account that owns this smart account.", /// "examples": [ - /// { - /// "correlationId": "41deb8d59a9dc9a7-IAD", - /// "errorLink": "https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request", - /// "errorMessage": "Invalid request.", - /// "errorType": "invalid_request" - /// } + /// "0x1234567890abcdef1234567890abcdef12345678" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{40}$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct EndUserEvmSmartAccountOwnerAddressesItem(::std::string::String); + impl ::std::ops::Deref for EndUserEvmSmartAccountOwnerAddressesItem { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: EndUserEvmSmartAccountOwnerAddressesItem) -> Self { + value.0 + } + } + impl ::std::convert::From<&EndUserEvmSmartAccountOwnerAddressesItem> + for EndUserEvmSmartAccountOwnerAddressesItem + { + fn from(value: &EndUserEvmSmartAccountOwnerAddressesItem) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for EndUserEvmSmartAccountOwnerAddressesItem { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for EndUserEvmSmartAccountOwnerAddressesItem { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for EndUserEvmSmartAccountOwnerAddressesItem { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for EndUserEvmSmartAccountOwnerAddressesItem { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for EndUserEvmSmartAccountOwnerAddressesItem { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///The address of the EVM smart account associated with the end user. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The address of the EVM smart account associated with the end user.", + /// "examples": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{40}$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct EndUserEvmSmartAccountsItem(::std::string::String); + impl ::std::ops::Deref for EndUserEvmSmartAccountsItem { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: EndUserEvmSmartAccountsItem) -> Self { + value.0 + } + } + impl ::std::convert::From<&EndUserEvmSmartAccountsItem> for EndUserEvmSmartAccountsItem { + fn from(value: &EndUserEvmSmartAccountsItem) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for EndUserEvmSmartAccountsItem { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for EndUserEvmSmartAccountsItem { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for EndUserEvmSmartAccountsItem { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for EndUserEvmSmartAccountsItem { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for EndUserEvmSmartAccountsItem { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///Information about a Solana account associated with an end user. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "Information about a Solana account associated with an end user.", /// "type": "object", /// "required": [ - /// "errorMessage", - /// "errorType" + /// "address", + /// "createdAt" /// ], /// "properties": { - /// "correlationId": { - /// "description": "A unique identifier for the request that generated the error. This can be used to help debug issues with the API.", - /// "examples": [ - /// "41deb8d59a9dc9a7-IAD" - /// ], - /// "type": "string" - /// }, - /// "errorLink": { - /// "description": "A link to the corresponding error documentation.", + /// "address": { + /// "description": "The base58 encoded address of the Solana account.", /// "examples": [ - /// "https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request" + /// "HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT" /// ], - /// "allOf": [ - /// { - /// "$ref": "#/components/schemas/Url" - /// } - /// ] + /// "type": "string", + /// "pattern": "^[1-9A-HJ-NP-Za-km-z]{32,44}$" /// }, - /// "errorMessage": { - /// "description": "The error message.", + /// "createdAt": { + /// "description": "The date and time when the account was created, in ISO 8601 format.", /// "examples": [ - /// "Unable to create EVM account" + /// "2025-01-15T10:30:00Z" /// ], - /// "type": "string" - /// }, - /// "errorType": { - /// "$ref": "#/components/schemas/ErrorType" + /// "type": "string", + /// "format": "date-time" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct Error { - ///A unique identifier for the request that generated the error. This can be used to help debug issues with the API. - #[serde( - rename = "correlationId", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub correlation_id: ::std::option::Option<::std::string::String>, - ///A link to the corresponding error documentation. - #[serde( - rename = "errorLink", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub error_link: ::std::option::Option, - ///The error message. - #[serde(rename = "errorMessage")] - pub error_message: ::std::string::String, - #[serde(rename = "errorType")] - pub error_type: ErrorType, + pub struct EndUserSolanaAccount { + ///The base58 encoded address of the Solana account. + pub address: EndUserSolanaAccountAddress, + ///The date and time when the account was created, in ISO 8601 format. + #[serde(rename = "createdAt")] + pub created_at: ::chrono::DateTime<::chrono::offset::Utc>, } - impl ::std::convert::From<&Error> for Error { - fn from(value: &Error) -> Self { + impl ::std::convert::From<&EndUserSolanaAccount> for EndUserSolanaAccount { + fn from(value: &EndUserSolanaAccount) -> Self { value.clone() } } - impl Error { - pub fn builder() -> builder::Error { + impl EndUserSolanaAccount { + pub fn builder() -> builder::EndUserSolanaAccount { Default::default() } } - ///The code that indicates the type of error that occurred. These error codes can be used to determine how to handle the error. + ///The base58 encoded address of the Solana account. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The code that indicates the type of error that occurred. These error codes can be used to determine how to handle the error.", + /// "description": "The base58 encoded address of the Solana account.", /// "examples": [ - /// "invalid_request" + /// "HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT" /// ], /// "type": "string", - /// "enum": [ - /// "already_exists", - /// "authorization_expired", - /// "bad_gateway", - /// "capture_expired", - /// "client_closed_request", - /// "faucet_limit_exceeded", - /// "forbidden", - /// "idempotency_error", - /// "internal_server_error", - /// "invalid_request", - /// "invalid_sql_query", - /// "invalid_signature", - /// "malformed_transaction", - /// "not_found", - /// "payment_method_required", - /// "payment_required", - /// "settlement_failed", - /// "rate_limit_exceeded", - /// "request_canceled", - /// "service_unavailable", - /// "timed_out", - /// "unauthorized", - /// "policy_violation", - /// "policy_in_use", - /// "account_limit_exceeded", - /// "network_not_tradable", - /// "guest_permission_denied", - /// "guest_region_forbidden", - /// "guest_transaction_limit", - /// "guest_transaction_count", - /// "phone_number_verification_expired", - /// "document_verification_failed", - /// "recipient_allowlist_violation", - /// "recipient_allowlist_pending", - /// "refund_expired", - /// "travel_rules_recipient_violation", - /// "source_account_invalid", - /// "target_account_invalid", - /// "source_account_not_found", - /// "target_account_not_found", - /// "source_asset_not_supported", - /// "target_asset_not_supported", - /// "target_email_invalid", - /// "target_onchain_address_invalid", - /// "transfer_amount_invalid", - /// "transfer_asset_not_supported", - /// "insufficient_balance", - /// "metadata_too_many_entries", - /// "metadata_key_too_long", - /// "metadata_value_too_long", - /// "travel_rules_field_missing", - /// "asset_mismatch", - /// "mfa_already_enrolled", - /// "mfa_invalid_code", - /// "mfa_flow_expired", - /// "mfa_required", - /// "mfa_not_enrolled", - /// "order_quote_expired", - /// "order_already_filled", - /// "order_already_canceled", - /// "account_not_ready", - /// "insufficient_liquidity", - /// "insufficient_allowance", - /// "transaction_simulation_failed" - /// ], - /// "x-error-instructions": { - /// "account_not_ready": "This error occurs when an operation is attempted on an account that is still being provisioned.\n\n**Steps to resolve:**\n1. Wait a few moments and retry the request\n2. If the error persists, the account may still be completing setup — retry with exponential backoff", - /// "already_exists": "This error occurs when trying to create a resource that already exists.\n\n**Steps to resolve:**\n1. Check if the resource exists before creation\n2. Use GET endpoints to verify resource state\n3. Use unique identifiers/names for resources", - /// "asset_mismatch": "This error occurs when the assets specified in the transfer are incompatible or don't match expected values.\n\n**Steps to resolve:**\n1. Ensure the `asset` field matches either the source or target asset\n2. Verify that the source and target assets are compatible for conversion (if different)\n3. Check that the asset symbols are correctly specified\n\n**Common causes:**\n- Transfer asset doesn't match source or target\n- Attempting an unsupported asset conversion\n- Typo in asset symbols", - /// "authorization_expired": "Returned when an authorization attempt is made after the payment session's authorization deadline has passed. Create a new payment session with a later authorization deadline.", - /// "bad_gateway": "This error occurs when the CDP API is unable to connect to the backend service.\n\n**Steps to resolve:**\n1. Retry your request after a short delay\n2. If persistent, contact CDP support with:\n - The timestamp of the error\n - Request details\n3. Consider implementing retry logic with an exponential backoff\n\n**Note:** These errors are automatically logged and monitored by CDP.", - /// "capture_expired": "Returned when a capture attempt is made after the payment session's capture deadline has passed. The payment session can no longer be captured.", - /// "client_closed_request": "This error occurs when the client closes the connection before the server can send a response.\n\n**Common causes:**\n- The client timed out waiting for the server response\n- The client application was terminated during a pending request\n- Network interruption caused the client connection to drop\n\n**Steps to resolve:**\n1. Increase client-side timeout settings if applicable\n2. Implement retry logic with exponential backoff for long-running queries\n3. Consider optimizing the request to reduce server processing time", - /// "document_verification_failed": "This error occurs when the user has not verified their identity for their coinbase.com account.\n**Steps to resolve:**\n1. Verify your coinbase account identity with valid documents at https://www.coinbase.com/settings/account-levels.", - /// "faucet_limit_exceeded": "This error occurs when you've exceeded the faucet request limits.\n\n**Steps to resolve:**\n1. Wait for the time window to reset\n2. Use funds more efficiently in your testing\n\nFor more information on faucet limits, please visit the [EVM Faucet endpoint](https://docs.cdp.coinbase.com/api-reference/v2/rest-api/faucets/request-funds-on-evm-test-networks) or the [Solana Faucet endpoint](https://docs.cdp.coinbase.com/api-reference/v2/rest-api/faucets/request-funds-on-solana-devnet).", - /// "forbidden": "This error occurs when you don't have permission to access the resource.\n\n**Steps to resolve:**\n1. Verify your permissions to access the resource\n2. Ensure that you are the owner of the requested resource", - /// "guest_permission_denied": "This error occurs when the user is not allowed to complete onramp transactions as a guest.\n\n**Steps to resolve:**\n1. Redirect the user to create a Coinbase account to buy and send crypto.", - /// "guest_region_forbidden": "This error occurs when guest onramp transactions are not allowed in the user's region.\n\n**Steps to resolve:**\n1. Redirect the user to create a Coinbase account to buy and send crypto.", - /// "guest_transaction_count": "This error occurs when the user has reached the lifetime guest onramp transaction count limit.\n\n**Steps to resolve:**\n1. Redirect the user to create a Coinbase account to buy and send crypto.", - /// "guest_transaction_limit": "This error occurs when the user has reached the weekly guest onramp transaction limit.\n\n**Steps to resolve:**\n1. Inform the user they have reached their weekly limit and will have to wait until next week.", - /// "idempotency_error": "This error occurs when an idempotency key is reused with different parameters.\n\n**Steps to resolve:**\n1. Generate a new UUID v4 for each unique request\n2. Only reuse idempotency keys for exact request duplicates\n3. Track used keys within your application\n\n**Example idempotency key implementation:**\n```typescript lines wrap\nimport { v4 as uuidv4 } from 'uuid';\n\nfunction createIdempotencyKey() {\n return uuidv4();\n}\n```", - /// "insufficient_allowance": "This error occurs when the taker has not approved the Permit2 contract to spend the `fromToken`\non their behalf. ERC-20 swaps require a Permit2 allowance. Native ETH swaps do not.\n\n**Steps to resolve:**\n1. Submit an ERC-20 `approve` transaction on the `fromToken` contract, granting the Permit2\n contract (`0x000000000022D473030F116dDEE9F6B43aC78BA3`) an allowance of at least `fromAmount`\n2. Wait for the approval transaction to be confirmed on-chain\n3. Retry the swap\n\n**Example:**\n```typescript lines wrap\n// Approve Permit2 to spend fromToken\nawait walletClient.writeContract({\n address: fromToken,\n abi: erc20Abi,\n functionName: \"approve\",\n args: [\"0x000000000022D473030F116dDEE9F6B43aC78BA3\", fromAmount],\n});\n```", - /// "insufficient_balance": "This error occurs when the source account does not have enough funds to complete the transfer including fees.\n\n**Steps to resolve:**\n1. Check the source account balance\n2. Ensure the balance covers both the transfer amount and any fees\n3. Consider using `amountType: \"source\"` to transfer the maximum available amount minus fees\n4. Add funds to the source account if needed\n\n**Common causes:**\n- Transfer amount exceeds available balance\n- Not accounting for transfer fees\n- Pending transactions reducing available balance", - /// "insufficient_liquidity": "This error occurs when no swap route is available for the requested token pair or amount.\n\n**Steps to resolve:**\n1. Try a smaller `fromAmount` — large orders may exceed available liquidity\n2. Try a different token pair\n3. Retry after a short delay; liquidity conditions change with market activity", - /// "internal_server_error": "This indicates an unexpected error that occurred on the CDP servers.\n\n**Important**: If you encounter this error, please note that your operation's status should be treated as unknown by your application, as it could have been a success within the CDP back-end.\n\n**Steps to resolve:**\n1. Retry your request after a short delay\n2. If persistent, contact CDP support with:\n - Your correlation ID\n - Timestamp of the error\n - Request details\n3. Consider implementing retry logic with an exponential backoff\n\n**Note:** These errors are automatically logged and monitored by CDP.", - /// "invalid_request": "This error occurs when the request is malformed or contains invalid data, including issues with the request body, query parameters, path parameters, or headers.\n\n**Steps to resolve:**\n1. Check all required fields and parameters are present\n2. Ensure request body (if applicable) follows the correct schema\n3. Verify all parameter formats match the API specification:\n - Query parameters\n - Path parameters\n - Request headers\n4. Validate any addresses, IDs, or other formatted strings meet requirements\n\n**Common validation issues:**\n- Missing required parameters\n- Invalid parameter types or formats\n- Malformed JSON in request body\n- Invalid enum values\n\n#### Transfer-specific validation errors\n\nThe following transfer validation scenarios return `errorType: \"invalid_request\"`. Use the `errorMessage` field to identify the specific case.\n\n| Scenario | Example `errorMessage` |\n|----------|----------------------|\n| Source account ID is malformed | `\"source is invalid.\"` |\n| Target account ID is malformed | `\"target is invalid.\"` |\n| Source account does not exist | `\"source not found.\"` |\n| Target account does not exist | `\"target not found.\"` |\n| Asset not supported at source | `\"source is not supported.\"` |\n| Asset not supported at target | `\"target is not supported.\"` |\n| Target email address is malformed | `\"target has an invalid email format.\"` |\n| Target onchain address is invalid for network | `\"The recipient address is invalid for the selected network.\"` |\n| Asset not supported for this transfer route | `\"Transfer asset pair is not supported.\"` |\n| Insufficient balance | `\"Insufficient funds to complete this transfer.\"` |\n| Asset mismatch between request fields | `\"Currency mismatch in request.\"` |\n| Metadata has too many keys | `\"Metadata has too many keys. Up to 10 key/value pairs are permitted.\"` |\n| Metadata key exceeds length limit | `\"Metadata key is too long. Each key must be less than or equal to 40 characters.\"` |\n| Metadata value exceeds length limit | `\"Metadata value is too long. Each value must be less than or equal to 500 characters.\"` |\n| Travel rule fields missing | `\"Travel rule information is incomplete. Missing fields: ...\"` |\n| Recipient address not in account allowlist | `\"Your coinbase account allowlist does not include this address. Please update your allowlist at https://www.coinbase.com/settings/allowlist\"` |", - /// "invalid_signature": "This error occurs when the signature provided for the given user operation is invalid.\n\n**Steps to resolve:**\n1. Verify the signature was generated by the correct owner account\n2. Ensure the signature corresponds to the exact user operation hash\n3. Check that the signature format matches the expected format\n4. Confirm you're using the correct network for the Smart Account\n\n**Common causes:**\n- Using wrong owner account to sign\n- Signing modified/incorrect user operation data\n- Malformed signature encoding\n- Network mismatch between signature and broadcast", - /// "invalid_sql_query": "This error occurs when the SQL query is invalid or not allowed.\n\n**Common causes:**\n- Using non-SELECT SQL statements (INSERT, UPDATE, DELETE, etc.)\n- Invalid table or column names\n- Syntax errors in SQL query\n- Query exceeds character limit\n- Too many JOIN operations", - /// "malformed_transaction": "This error occurs when the transaction data provided is not properly formatted or is invalid.\n\n**Steps to resolve:**\n1. Verify transaction encoding:\n - **EVM networks**: Check RLP encoding is correct\n - **Solana**: Validate base64 encoding\n2. Ensure all required transaction fields are present\n3. Validate transaction parameters are within acceptable ranges\n4. Check that the transaction type is supported on the target network (see our [Supported Networks](https://docs.cdp.coinbase.com/get-started/supported-networks) page for more details)\n\n**Common causes:**\n- Invalid hex encoding for EVM transactions\n- Missing required transaction fields\n- Incorrect parameter formats\n- Unsupported transaction types\n- Network-specific transaction format mismatches", - /// "metadata_key_too_long": "This error occurs when a metadata key exceeds the maximum allowed length.\n\n**Steps to resolve:**\n1. Shorten the metadata key to 40 characters or less\n2. Use abbreviations or shorter naming conventions\n3. Consider using a key-value structure where the value contains the longer identifier\n\n**Limits:**\n- Maximum key length: 40 characters", - /// "metadata_too_many_entries": "This error occurs when the transfer metadata contains more entries than allowed.\n\n**Steps to resolve:**\n1. Reduce the number of metadata entries (maximum 10 allowed)\n2. Consolidate related data into fewer keys\n3. Store additional data externally and reference it with a single metadata entry\n\n**Limits:**\n- Maximum entries: 10", - /// "metadata_value_too_long": "This error occurs when a metadata value exceeds the maximum allowed length.\n\n**Steps to resolve:**\n1. Shorten the metadata value to 500 characters or less\n2. Store longer data externally and reference it with a shorter identifier\n3. Consider compressing or encoding the data if appropriate\n\n**Limits:**\n- Maximum value length: 500 characters", - /// "mfa_already_enrolled": "This error occurs when attempting to enroll in an MFA method that the user has already enrolled in.\n\n**Steps to resolve:**\n1. Check if the user is already enrolled in the MFA method before initiating enrollment\n2. To update or reset MFA, remove the existing enrollment first (if supported)\n3. Use a different MFA method if multiple options are available", - /// "mfa_flow_expired": "This error occurs when the MFA enrollment or verification session has expired.\n\n**Steps to resolve:**\n1. Restart the MFA enrollment or verification flow\n2. Complete the flow within the allowed time window (typically 5 minutes)\n3. Ensure the user doesn't leave the flow idle for extended periods\n\n**Note:** MFA sessions expire automatically for security purposes.", - /// "mfa_invalid_code": "This error occurs when the MFA code provided is incorrect or has already been used.\n\n**Steps to resolve:**\n1. Verify the user entered the correct code from their authenticator app\n2. Ensure the code is current (TOTP codes expire after 30 seconds)\n3. Check that the device time is synchronized correctly\n4. Ask the user to generate a new code and try again\n\n**Common causes:**\n- Typing errors in the 6-digit code\n- Using an expired TOTP code\n- Device clock drift on user's authenticator app\n- Attempting to reuse a previously submitted code", - /// "mfa_not_enrolled": "This error occurs when attempting to verify MFA for a user who has not enrolled in any MFA method.\n\n**Steps to resolve:**\n1. Check if the user has enrolled in MFA before attempting verification\n2. Guide the user through MFA enrollment first using the `/mfa/enroll/{mfaMethod}/init` endpoint\n3. Complete enrollment before requiring MFA verification", - /// "mfa_required": "This error occurs when attempting to perform a sensitive operation that requires MFA verification, but the user has not completed MFA verification.\n\n**Steps to resolve:**\n1. Initiate the MFA verification flow using the `/mfa/verify/{mfaMethod}/init` endpoint\n2. Prompt the user to enter their MFA code\n3. Submit the verification using the `/mfa/verify/{mfaMethod}/submit` endpoint\n4. Use the returned access token with MFA claim for the sensitive operation\n5. Retry the original request with the new MFA-verified token\n\n**Operations requiring MFA:**\n- Transactions Sign/Send\n- Key export\n- Account management actions (when configured)", - /// "network_not_tradable": "This error occurs when the selected asset cannot be purchased on the selected network in the user's location.\n\n**Steps to resolve:**\n1. Verify the asset is tradable on the selected network\n2. Check the user's location to ensure it is allowed to purchase the asset on the selected network\n\n**Common causes:**\n- Users in NY are not allowed to purchase USDC on any network other than Ethereum", - /// "not_found": "This error occurs when the resource specified in your request doesn't exist or you don't have access to it.\n\n**Steps to resolve:**\n1. Verify the resource ID/address/account exists\n2. Check your permissions to access the resource\n3. Ensure you're using the correct network/environment\n4. Confirm the resource hasn't been deleted\n\n**Common causes:**\n- Mistyped addresses\n- Accessing resources from the wrong CDP project\n- Resource was deleted or hasn't been created yet", - /// "order_already_canceled": "This error occurs when attempting to cancel or execute an order that has already been canceled.\n\n**Steps to resolve:**\n1. Check the current status of the order using `GET /v2/orders/{orderId}`.\n2. Create a new order if you still want to trade.", - /// "order_already_filled": "This error occurs when attempting to cancel or modify an order that has already been filled.\n\n**Steps to resolve:**\n1. Check the current status of the order using `GET /v2/orders/{orderId}`.\n2. A filled order cannot be canceled or re-executed.", - /// "order_quote_expired": "This error occurs when attempting to execute an order whose quote has expired.\n\n**Steps to resolve:**\n1. Create a new order with `execute: false` to get an updated quote.\n2. Execute the new order before the quote expires (check the `expiresAt` field).\n3. Alternatively, create a new order with `execute: true` to skip the quote step and execute immediately.", - /// "payment_method_required": "This error occurs when a payment method is required to complete the requested operation but none is configured or available.\n\n**Steps to resolve:**\n1. Add a valid payment method to your account using the [CDP Portal](https://portal.cdp.coinbase.com)\n2. Ensure your payment method is valid and not expired\n\n**Common causes:**\n- No payment method configured on the account\n- Payment method is expired", - /// "payment_required": "This error occurs when an x402 payment is required to access the requested resource.\n\n**Steps to resolve:**\n1. Include a valid x402 payment header in your request\n2. Ensure the payment meets the resource's pricing requirements", - /// "phone_number_verification_expired": "This error occurs when the user's phone number verification has expired. Use of guest Onramp requires the user's\nphone number to be verified every 60 days.\n\n**Steps to resolve:**\n1. Re-verify the user's phone number via OTP.\n2. Retry the request with the phoneNumberVerifiedAt field set to new verification timestamp.", - /// "policy_in_use": "This error occurs when trying to delete a Policy that is currently in use by at least one project or account.\n\n**Steps to resolve:**\n1. Update project or accounts to remove references to the Policy in question.\n2. Retry your delete request.", - /// "rate_limit_exceeded": "This error occurs when you've exceeded the API rate limits.\n\n**Steps to resolve:**\n1. Implement exponential backoff\n2. Cache responses where possible\n3. Wait for rate limit window to reset\n\n**Best practices:**\n```typescript lines wrap\nasync function withRetry(fn: () => Promise) {\n let delay = 1000;\n while (true) {\n try {\n return await fn();\n } catch (e) {\n if (e.errorType === \"rate_limit_exceeded\") {\n await sleep(delay);\n delay *= 2;\n continue;\n }\n throw e;\n }\n }\n}\n```", - /// "recipient_allowlist_pending": "This error occurs when the user is not allowed to receive funds at this address, because changes to their coinbase account allowlist are pending.\n**Steps to resolve:**\n1. Wait approximately 2 days for updates to take effect.", - /// "recipient_allowlist_violation": "This error occurs when the user is not allowed to receive funds at this address, according to their coinbase account allowlist.\n**Steps to resolve:**\n1. Either disable the allowlist or add the wallet address at https://www.coinbase.com/settings/allowlist\n2. Wait approximately 2 days for updates to take effect.", - /// "refund_expired": "Returned when a refund attempt is made after the payment session's refund deadline has passed. The payment session can no longer be refunded.", - /// "request_canceled": "This error occurs when the client cancels an in-progress request before it completes.\n\n**Steps to resolve:**\n1. Check client-side timeout configurations\n2. Review request cancellation logic in your code\n3. Consider increasing timeout thresholds for long-running operations\n4. Implement request tracking to identify premature cancellations\n\n**Best practices:**\n```typescript lines wrap\nasync function withTimeout(promise: Promise, timeoutMs: number): Promise {\n const timeout = new Promise((_, reject) => {\n setTimeout(() => {\n reject(new Error(\"Operation timed out\"));\n }, timeoutMs);\n });\n\n try {\n return await Promise.race([promise, timeout]);\n } catch (error) {\n // Handle timeout or cancellation\n throw error;\n }\n}\n```", - /// "service_unavailable": "This error occurs when the CDP API is temporarily unable to handle requests due to maintenance or high load.\n\n**Steps to resolve:**\n1. Retry your request after a short delay\n2. If persistent, contact CDP support with:\n - The timestamp of the error\n - Request details\n3. Consider implementing retry logic with an exponential backoff\n\n**Note:** These errors are automatically logged and monitored by CDP.", - /// "settlement_failed": "This error occurs when an x402 payment was verified but settlement on-chain failed.\n\n**Steps to resolve:**\n1. Retry the request with a new payment\n2. Ensure the payment asset has sufficient balance for settlement", - /// "source_account_invalid": "This error occurs when the source account specified in the transfer request is invalid or malformed.\n\n**Steps to resolve:**\n1. Verify the account ID format is correct (e.g., `account_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`)\n2. Ensure the account ID belongs to your CDP entity\n3. Verify the account ID exists by calling `GET /v2/accounts/{accountId}` or `GET /v2/accounts`\n\n**Common causes:**\n- Malformed account ID\n- Typo in the account ID", - /// "source_account_not_found": "This error occurs when the source account specified in the transfer does not exist.\n\n**Steps to resolve:**\n1. Verify the account ID exists by calling `GET /v2/accounts/{accountId}` or `GET /v2/accounts`", - /// "source_asset_not_supported": "This error occurs when the asset specified in the transfer source is not supported for this transfer type.\n\n**Steps to resolve:**\n1. Check the list of supported assets for the source account type\n2. Verify the asset symbol is correctly specified (e.g., `usdc`, `usdt`)\n\n**Common causes:**\n- Unsupported asset for the transfer route\n- Incorrect asset symbol", - /// "target_account_invalid": "This error occurs when the target account specified in the transfer request is invalid or malformed.\n\n**Steps to resolve:**\n1. Verify the account ID format is correct (e.g., `account_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`)\n2. Ensure the account exists and can receive funds\n3. Verify the account ID exists by calling `GET /v2/accounts/{accountId}` or `GET /v2/accounts`\n\n**Common causes:**\n- Malformed account ID\n- Typo in the account ID", - /// "target_account_not_found": "This error occurs when the target account specified in the transfer does not exist.\n\n**Steps to resolve:**\n1. Verify the account ID exists by calling `GET /v2/accounts/{accountId}` or `GET /v2/accounts`", - /// "target_asset_not_supported": "This error occurs when the asset specified in the transfer target is not supported for this transfer type.\n\n**Steps to resolve:**\n1. Check the list of supported assets for the target\n2. Verify the asset symbol is correctly specified (e.g., `usdc`, `usdt`)\n3. Ensure the target can receive this asset type\n\n**Common causes:**\n- Asset not supported by the target\n- Unsupported conversion between source and target assets", - /// "target_email_invalid": "This error occurs when the email address specified as the transfer target is invalid.\n\n**Steps to resolve:**\n1. Verify the email address format is valid (e.g., `user@example.com`)\n2. Check for typos in the email address\n3. Ensure the email domain is valid\n\n**Common causes:**\n- Invalid email format\n- Missing @ symbol or domain\n- Typo in the email address", - /// "target_onchain_address_invalid": "This error occurs when the onchain address specified as the transfer target is invalid for the specified network.\n\n**Steps to resolve:**\n1. Ensure the network is supported for the transfer type\n2. Verify the address format matches the target network\n3. Ensure you haven't mixed up addresses from different networks\n\n**Common causes:**\n- Network not supported for the transfer type\n- Address format doesn't match network\n- Address from a different blockchain network", - /// "timed_out": "This error occurs when a request exceeds the maximum allowed processing time.\n\n**Steps to resolve:**\n1. Break down large requests into smaller chunks (if applicable)\n2. Implement retry logic with exponential backoff\n3. Use streaming endpoints for large data sets\n\n**Example retry implementation:**\n```typescript lines wrap\nasync function withRetryAndTimeout(\n operation: () => Promise,\n maxRetries = 3,\n timeout = 30000,\n): Promise {\n let attempts = 0;\n while (attempts < maxRetries) {\n try {\n return await Promise.race([\n operation(),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error(\"Timeout\")), timeout)\n ),\n ]);\n } catch (error) {\n attempts++;\n if (attempts === maxRetries) throw error;\n // Exponential backoff\n await new Promise(resolve =>\n setTimeout(resolve, Math.pow(2, attempts) * 1000)\n );\n }\n }\n throw new Error(\"Max retries exceeded\");\n}\n```", - /// "transaction_simulation_failed": "This error occurs when the pre-broadcast simulation of the swap transaction predicted a revert.\nNo transaction was submitted and no gas was spent.\n\n**Common causes:**\n- The on-chain price moved past the `slippageBps` tolerance between the price estimate and execution\n- Taker balance changed between the price estimate and execution\n\n**Steps to resolve:**\n1. Retry immediately — prices change quickly and a new quote may succeed\n2. Increase `slippageBps` if retries continue to fail (e.g. from 100 to 200)\n3. For large swaps, consider splitting into smaller amounts to reduce price impact", - /// "transfer_amount_invalid": "This error occurs when the transfer amount is invalid.\n\n**Steps to resolve:**\n1. Ensure the amount is a positive number and greater than $1 USD equivalent amount\n2. Verify the amount format is a valid decimal string (e.g., `\"100.50\"`)\n3. Check the number of decimal places for the asset\n\n**Common causes:**\n- Zero or negative amount\n- Too many decimal places for the asset\n- Amount below minimum threshold ($1 USD equivalent amount)", - /// "transfer_asset_not_supported": "This error occurs when the asset specified for the transfer is not supported.\n\n**Steps to resolve:**\n1. Check the list of supported assets for transfers\n2. Verify the asset symbol is correctly specified\n3. Ensure the asset is supported for the transfer route (source → target)\n\n**Common causes:**\n- Asset not supported for transfers\n- Incorrect asset symbol", - /// "travel_rules_field_missing": "This error occurs when required travel rule fields are missing from the transfer request.\n\n**Steps to resolve:**\n1. Include the `travelRule` object in your transfer request\n2. Supply the required missing fields prompted by the error message\n3. Review the travel rule requirements for your jurisdiction\n\nNote: Required fields may vary by region.", - /// "travel_rules_recipient_violation": "This error occurs when the user is not allowed to receive funds at this address, because it violates travel rules.\n**Steps to resolve:**\n1. Ensure your desired transfer is not blocked by local travel regulations.", - /// "unauthorized": "This error occurs when authentication fails.\n\n**Steps to resolve:**\n1. Verify your CDP API credentials:\n - Check that your API key is valid\n - Check that your Wallet Secret is properly configured\n2. Validate JWT token:\n - Not expired\n - Properly signed\n - Contains required claims\n3. Check request headers:\n - Authorization header present\n - X-Wallet-Auth header included when required\n\n**Security note:** Never share your Wallet Secret or API keys." - /// } + /// "pattern": "^[1-9A-HJ-NP-Za-km-z]{32,44}$" ///} /// ``` ///
- #[derive( - ::serde::Deserialize, - ::serde::Serialize, - Clone, - Copy, - Debug, - Eq, - Hash, - Ord, - PartialEq, - PartialOrd, - )] - pub enum ErrorType { - #[serde(rename = "already_exists")] - AlreadyExists, - #[serde(rename = "authorization_expired")] - AuthorizationExpired, - #[serde(rename = "bad_gateway")] - BadGateway, - #[serde(rename = "capture_expired")] - CaptureExpired, - #[serde(rename = "client_closed_request")] - ClientClosedRequest, - #[serde(rename = "faucet_limit_exceeded")] - FaucetLimitExceeded, - #[serde(rename = "forbidden")] - Forbidden, - #[serde(rename = "idempotency_error")] - IdempotencyError, - #[serde(rename = "internal_server_error")] - InternalServerError, + #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct EndUserSolanaAccountAddress(::std::string::String); + impl ::std::ops::Deref for EndUserSolanaAccountAddress { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: EndUserSolanaAccountAddress) -> Self { + value.0 + } + } + impl ::std::convert::From<&EndUserSolanaAccountAddress> for EndUserSolanaAccountAddress { + fn from(value: &EndUserSolanaAccountAddress) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for EndUserSolanaAccountAddress { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^[1-9A-HJ-NP-Za-km-z]{32,44}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^[1-9A-HJ-NP-Za-km-z]{32,44}$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for EndUserSolanaAccountAddress { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for EndUserSolanaAccountAddress { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for EndUserSolanaAccountAddress { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for EndUserSolanaAccountAddress { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///The base58 encoded address of the Solana account associated with the end user. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The base58 encoded address of the Solana account associated with the end user.", + /// "examples": [ + /// "HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT" + /// ], + /// "type": "string", + /// "pattern": "^[1-9A-HJ-NP-Za-km-z]{32,44}$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct EndUserSolanaAccountsItem(::std::string::String); + impl ::std::ops::Deref for EndUserSolanaAccountsItem { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: EndUserSolanaAccountsItem) -> Self { + value.0 + } + } + impl ::std::convert::From<&EndUserSolanaAccountsItem> for EndUserSolanaAccountsItem { + fn from(value: &EndUserSolanaAccountsItem) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for EndUserSolanaAccountsItem { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^[1-9A-HJ-NP-Za-km-z]{32,44}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^[1-9A-HJ-NP-Za-km-z]{32,44}$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for EndUserSolanaAccountsItem { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for EndUserSolanaAccountsItem { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for EndUserSolanaAccountsItem { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for EndUserSolanaAccountsItem { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///A stable, unique identifier for the end user. The `userId` must be unique across all end users in the developer's CDP Project. It must be between 1 and 100 characters long and can only contain alphanumeric characters and hyphens. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "A stable, unique identifier for the end user. The `userId` must be unique across all end users in the developer's CDP Project. It must be between 1 and 100 characters long and can only contain alphanumeric characters and hyphens.", + /// "examples": [ + /// "e051beeb-7163-4527-a5b6-35e301529ff2" + /// ], + /// "type": "string", + /// "pattern": "^[a-zA-Z0-9-]{1,100}$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct EndUserUserId(::std::string::String); + impl ::std::ops::Deref for EndUserUserId { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: EndUserUserId) -> Self { + value.0 + } + } + impl ::std::convert::From<&EndUserUserId> for EndUserUserId { + fn from(value: &EndUserUserId) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for EndUserUserId { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^[a-zA-Z0-9-]{1,100}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^[a-zA-Z0-9-]{1,100}$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for EndUserUserId { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for EndUserUserId { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for EndUserUserId { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for EndUserUserId { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///An error response including the code for the type of error and a human-readable message describing the error. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "An error response including the code for the type of error and a human-readable message describing the error.", + /// "examples": [ + /// { + /// "correlationId": "41deb8d59a9dc9a7-IAD", + /// "errorLink": "https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request", + /// "errorMessage": "Invalid request.", + /// "errorType": "invalid_request" + /// } + /// ], + /// "type": "object", + /// "required": [ + /// "errorMessage", + /// "errorType" + /// ], + /// "properties": { + /// "correlationId": { + /// "description": "A unique identifier for the request that generated the error. This can be used to help debug issues with the API.", + /// "examples": [ + /// "41deb8d59a9dc9a7-IAD" + /// ], + /// "type": "string" + /// }, + /// "errorLink": { + /// "description": "A link to the corresponding error documentation.", + /// "examples": [ + /// "https://docs.cdp.coinbase.com/api-reference/v2/errors#invalid-request" + /// ], + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/Url" + /// } + /// ] + /// }, + /// "errorMessage": { + /// "description": "The error message.", + /// "examples": [ + /// "Unable to create EVM account" + /// ], + /// "type": "string" + /// }, + /// "errorType": { + /// "$ref": "#/components/schemas/ErrorType" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct Error { + ///A unique identifier for the request that generated the error. This can be used to help debug issues with the API. + #[serde( + rename = "correlationId", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub correlation_id: ::std::option::Option<::std::string::String>, + ///A link to the corresponding error documentation. + #[serde( + rename = "errorLink", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub error_link: ::std::option::Option, + ///The error message. + #[serde(rename = "errorMessage")] + pub error_message: ::std::string::String, + #[serde(rename = "errorType")] + pub error_type: ErrorType, + } + impl ::std::convert::From<&Error> for Error { + fn from(value: &Error) -> Self { + value.clone() + } + } + impl Error { + pub fn builder() -> builder::Error { + Default::default() + } + } + ///The code that indicates the type of error that occurred. These error codes can be used to determine how to handle the error. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The code that indicates the type of error that occurred. These error codes can be used to determine how to handle the error.", + /// "examples": [ + /// "invalid_request" + /// ], + /// "type": "string", + /// "enum": [ + /// "already_exists", + /// "authorization_expired", + /// "bad_gateway", + /// "capture_expired", + /// "client_closed_request", + /// "endpoint_unavailable", + /// "faucet_limit_exceeded", + /// "forbidden", + /// "idempotency_error", + /// "internal_server_error", + /// "invalid_request", + /// "invalid_sql_query", + /// "invalid_signature", + /// "malformed_transaction", + /// "not_found", + /// "payment_method_required", + /// "payment_required", + /// "settlement_failed", + /// "rate_limit_exceeded", + /// "request_canceled", + /// "service_unavailable", + /// "timed_out", + /// "unauthorized", + /// "unsupported_tos_language", + /// "policy_violation", + /// "policy_in_use", + /// "account_limit_exceeded", + /// "network_not_tradable", + /// "guest_permission_denied", + /// "guest_region_forbidden", + /// "guest_transaction_limit", + /// "guest_transaction_count", + /// "phone_number_verification_expired", + /// "document_verification_failed", + /// "recipient_allowlist_violation", + /// "recipient_allowlist_pending", + /// "refund_expired", + /// "travel_rules_recipient_violation", + /// "source_account_invalid", + /// "target_account_invalid", + /// "source_account_not_found", + /// "target_account_not_found", + /// "source_asset_not_supported", + /// "target_asset_not_supported", + /// "target_email_invalid", + /// "target_onchain_address_invalid", + /// "transfer_amount_invalid", + /// "transfer_asset_not_supported", + /// "transfer_quote_expired", + /// "insufficient_balance", + /// "metadata_too_many_entries", + /// "metadata_key_too_long", + /// "metadata_value_too_long", + /// "travel_rules_field_missing", + /// "asset_mismatch", + /// "mfa_already_enrolled", + /// "mfa_invalid_code", + /// "mfa_flow_expired", + /// "mfa_required", + /// "mfa_not_enrolled", + /// "order_quote_expired", + /// "order_already_filled", + /// "order_already_canceled", + /// "account_not_ready", + /// "insufficient_liquidity", + /// "insufficient_allowance", + /// "transaction_simulation_failed", + /// "delegation_not_found", + /// "delegation_expired", + /// "delegation_revoked", + /// "delegation_not_authorized", + /// "delegation_not_enabled" + /// ], + /// "x-error-instructions": { + /// "account_not_ready": "This error occurs when an operation is attempted on an account that is still being provisioned.\n\n**Steps to resolve:**\n1. Wait a few moments and retry the request\n2. If the error persists, the account may still be completing setup — retry with exponential backoff", + /// "already_exists": "This error occurs when trying to create a resource that already exists.\n\n**Steps to resolve:**\n1. Check if the resource exists before creation\n2. Use GET endpoints to verify resource state\n3. Use unique identifiers/names for resources", + /// "asset_mismatch": "This error occurs when the assets specified in the transfer are incompatible or don't match expected values.\n\n**Steps to resolve:**\n1. Ensure the `asset` field matches either the source or target asset\n2. Verify that the source and target assets are compatible for conversion (if different)\n3. Check that the asset symbols are correctly specified\n\n**Common causes:**\n- Transfer asset doesn't match source or target\n- Attempting an unsupported asset conversion\n- Typo in asset symbols", + /// "authorization_expired": "Returned when an authorization attempt is made after the payment session's authorization deadline has passed. Create a new payment session with a later authorization deadline.", + /// "bad_gateway": "This error occurs when the CDP API is unable to connect to the backend service.\n\n**Steps to resolve:**\n1. Retry your request after a short delay\n2. If persistent, contact CDP support with:\n - The timestamp of the error\n - Request details\n3. Consider implementing retry logic with an exponential backoff\n\n**Note:** These errors are automatically logged and monitored by CDP.", + /// "capture_expired": "Returned when a capture attempt is made after the payment session's capture deadline has passed. The payment session can no longer be captured.", + /// "client_closed_request": "This error occurs when the client closes the connection before the server can send a response.\n\n**Common causes:**\n- The client timed out waiting for the server response\n- The client application was terminated during a pending request\n- Network interruption caused the client connection to drop\n\n**Steps to resolve:**\n1. Increase client-side timeout settings if applicable\n2. Implement retry logic with exponential backoff for long-running queries\n3. Consider optimizing the request to reduce server processing time", + /// "delegation_expired": "This error occurs when the delegation grant used for signing has expired.\nDelegation grants have a limited lifetime set at creation.\n\n**Steps to resolve:**\n1. Create a new delegation grant using `createDelegationForEndUser` or\n `createDelegationForEndUserAccount`\n2. Retry the signing operation with the new grant active\n3. Consider creating grants with a longer TTL if expiry is frequent", + /// "delegation_not_authorized": "This error occurs when a delegation grant exists but does not authorize the\nrequested operation.\n\n**Steps to resolve:**\n1. For account-scoped grants, verify the signing address matches the address\n the grant was created for\n2. Check that the operation is permitted for delegated signing on your project\n3. Create a grant with the correct scope if needed", + /// "delegation_not_enabled": "This error occurs when delegated signing is attempted on a project that has\nnot enabled the feature.\n\n**Steps to resolve:**\n1. Enable delegated signing in your project configuration via the CDP Portal\n2. Contact support if you believe delegated signing should already be enabled\n for your project", + /// "delegation_not_found": "This error occurs when a delegated signing operation is attempted but no active\ndelegation grant exists for the end user (or account).\n\n**Steps to resolve:**\n1. Create a delegation grant using `createDelegationForEndUser` (user-scoped)\n or `createDelegationForEndUserAccount` (account-scoped) before calling\n the signing or sending operation\n2. If you previously created a grant, it may have expired or been revoked —\n in those cases you would receive a `delegation_expired` or\n `delegation_revoked` error instead\n3. For account-scoped grants, verify the address in the request matches the\n granted address (EVM addresses are compared case-insensitively;\n Solana addresses must match exactly)", + /// "delegation_revoked": "This error occurs when the delegation grant has been explicitly revoked.\n\n**Steps to resolve:**\n1. Create a new delegation grant using `createDelegationForEndUser` or\n `createDelegationForEndUserAccount`\n2. Confirm with the end user before recreating, since revocation is\n typically intentional", + /// "document_verification_failed": "This error occurs when the user has not verified their identity for their coinbase.com account.\n**Steps to resolve:**\n1. Verify your coinbase account identity with valid documents at https://www.coinbase.com/settings/account-levels.", + /// "endpoint_unavailable": "This error occurs when a specific endpoint has been temporarily disabled by an operator (e.g. a kill switch). The CDP API as a whole is still healthy; only this endpoint is unavailable. Distinct from `service_unavailable`, which indicates the API itself is down.\n\nRe-enabling is a manual operator action, so the endpoint may remain unavailable for an extended period.\n\n**Steps to resolve:**\n1. Check the [CDP status page](https://cdpstatus.coinbase.com/) for an active incident.\n2. If persistent, contact CDP support with:\n - The timestamp of the error\n - Request details", + /// "faucet_limit_exceeded": "This error occurs when you've exceeded the faucet request limits.\n\n**Steps to resolve:**\n1. Wait for the time window to reset\n2. Use funds more efficiently in your testing\n\nFor more information on faucet limits, please visit the [EVM Faucet endpoint](https://docs.cdp.coinbase.com/api-reference/v2/rest-api/faucets/request-funds-on-evm-test-networks) or the [Solana Faucet endpoint](https://docs.cdp.coinbase.com/api-reference/v2/rest-api/faucets/request-funds-on-solana-devnet).", + /// "forbidden": "This error occurs when you don't have permission to access the resource.\n\n**Steps to resolve:**\n1. Verify your permissions to access the resource\n2. Ensure that you are the owner of the requested resource", + /// "guest_permission_denied": "This error occurs when the user is not allowed to complete onramp transactions as a guest.\n\n**Steps to resolve:**\n1. Redirect the user to create a Coinbase account to buy and send crypto.", + /// "guest_region_forbidden": "This error occurs when guest onramp transactions are not allowed in the user's region.\n\n**Steps to resolve:**\n1. Redirect the user to create a Coinbase account to buy and send crypto.", + /// "guest_transaction_count": "This error occurs when the user has reached the lifetime guest onramp transaction count limit.\n\n**Steps to resolve:**\n1. Redirect the user to create a Coinbase account to buy and send crypto.", + /// "guest_transaction_limit": "This error occurs when the user has reached the weekly guest onramp transaction limit.\n\n**Steps to resolve:**\n1. Inform the user they have reached their weekly limit and will have to wait until next week.", + /// "idempotency_error": "This error occurs when an idempotency key is reused with different parameters.\n\n**Steps to resolve:**\n1. Generate a new UUID v4 for each unique request\n2. Only reuse idempotency keys for exact request duplicates\n3. Track used keys within your application\n\n**Example idempotency key implementation:**\n```typescript lines wrap\nimport { v4 as uuidv4 } from 'uuid';\n\nfunction createIdempotencyKey() {\n return uuidv4();\n}\n```", + /// "insufficient_allowance": "This error occurs when the taker has not approved the Permit2 contract to spend the `fromToken`\non their behalf. ERC-20 swaps require a Permit2 allowance. Native ETH swaps do not.\n\n**Steps to resolve:**\n1. Submit an ERC-20 `approve` transaction on the `fromToken` contract, granting the Permit2\n contract (`0x000000000022D473030F116dDEE9F6B43aC78BA3`) an allowance of at least `fromAmount`\n2. Wait for the approval transaction to be confirmed on-chain\n3. Retry the swap\n\n**Example:**\n```typescript lines wrap\n// Approve Permit2 to spend fromToken\nawait walletClient.writeContract({\n address: fromToken,\n abi: erc20Abi,\n functionName: \"approve\",\n args: [\"0x000000000022D473030F116dDEE9F6B43aC78BA3\", fromAmount],\n});\n```", + /// "insufficient_balance": "This error occurs when the source account does not have enough funds to complete the transfer including fees.\n\n**Steps to resolve:**\n1. Check the source account balance\n2. Ensure the balance covers both the transfer amount and any fees\n3. Consider using `amountType: \"source\"` to transfer the maximum available amount minus fees\n4. Add funds to the source account if needed\n\n**Common causes:**\n- Transfer amount exceeds available balance\n- Not accounting for transfer fees\n- Pending transactions reducing available balance", + /// "insufficient_liquidity": "This error occurs when no swap route is available for the requested token pair or amount.\n\n**Steps to resolve:**\n1. Try a smaller `fromAmount` — large orders may exceed available liquidity\n2. Try a different token pair\n3. Retry after a short delay; liquidity conditions change with market activity", + /// "internal_server_error": "This indicates an unexpected error that occurred on the CDP servers.\n\n**Important**: If you encounter this error, please note that your operation's status should be treated as unknown by your application, as it could have been a success within the CDP back-end.\n\n**Steps to resolve:**\n1. Retry your request after a short delay\n2. If persistent, contact CDP support with:\n - Your correlation ID\n - Timestamp of the error\n - Request details\n3. Consider implementing retry logic with an exponential backoff\n\n**Note:** These errors are automatically logged and monitored by CDP.", + /// "invalid_request": "This error occurs when the request is malformed or contains invalid data, including issues with the request body, query parameters, path parameters, or headers.\n\n**Steps to resolve:**\n1. Check all required fields and parameters are present\n2. Ensure request body (if applicable) follows the correct schema\n3. Verify all parameter formats match the API specification:\n - Query parameters\n - Path parameters\n - Request headers\n4. Validate any addresses, IDs, or other formatted strings meet requirements\n\n**Common validation issues:**\n- Missing required parameters\n- Invalid parameter types or formats\n- Malformed JSON in request body\n- Invalid enum values\n\n#### Transfer-specific validation errors\n\nThe following transfer validation scenarios return `errorType: \"invalid_request\"`. Use the `errorMessage` field to identify the specific case.\n\n| Scenario | Example `errorMessage` |\n|----------|----------------------|\n| Source account ID is malformed | `\"source is invalid.\"` |\n| Target account ID is malformed | `\"target is invalid.\"` |\n| Source account does not exist | `\"source not found.\"` |\n| Target account does not exist | `\"target not found.\"` |\n| Asset not supported at source | `\"source is not supported.\"` |\n| Asset not supported at target | `\"target is not supported.\"` |\n| Target email address is malformed | `\"target has an invalid email format.\"` |\n| Target onchain address is invalid for network | `\"The recipient address is invalid for the selected network.\"` |\n| Asset not supported for this transfer route | `\"Transfer asset pair is not supported.\"` |\n| Insufficient balance | `\"Insufficient funds to complete this transfer.\"` |\n| Asset mismatch between request fields | `\"Currency mismatch in request.\"` |\n| Metadata has too many keys | `\"Metadata has too many keys. Up to 10 key/value pairs are permitted.\"` |\n| Metadata key exceeds length limit | `\"Metadata key is too long. Each key must be less than or equal to 40 characters.\"` |\n| Metadata value exceeds length limit | `\"Metadata value is too long. Each value must be less than or equal to 500 characters.\"` |\n| Travel rule fields missing | `\"Travel rule information is incomplete. Missing fields: ...\"` |\n| Recipient address not in account allowlist | `\"Your coinbase account allowlist does not include this address. Please update your allowlist at https://www.coinbase.com/settings/allowlist\"` |", + /// "invalid_signature": "This error occurs when the signature provided for the given user operation is invalid.\n\n**Steps to resolve:**\n1. Verify the signature was generated by the correct owner account\n2. Ensure the signature corresponds to the exact user operation hash\n3. Check that the signature format matches the expected format\n4. Confirm you're using the correct network for the Smart Account\n\n**Common causes:**\n- Using wrong owner account to sign\n- Signing modified/incorrect user operation data\n- Malformed signature encoding\n- Network mismatch between signature and broadcast", + /// "invalid_sql_query": "This error occurs when the SQL query is invalid or not allowed.\n\n**Common causes:**\n- Using non-SELECT SQL statements (INSERT, UPDATE, DELETE, etc.)\n- Invalid table or column names\n- Syntax errors in SQL query\n- Query exceeds character limit\n- Too many JOIN operations", + /// "malformed_transaction": "This error occurs when the transaction data provided is not properly formatted or is invalid.\n\n**Steps to resolve:**\n1. Verify transaction encoding:\n - **EVM networks**: Check RLP encoding is correct\n - **Solana**: Validate base64 encoding\n2. Ensure all required transaction fields are present\n3. Validate transaction parameters are within acceptable ranges\n4. Check that the transaction type is supported on the target network (see our [Supported Networks](https://docs.cdp.coinbase.com/get-started/supported-networks) page for more details)\n\n**Common causes:**\n- Invalid hex encoding for EVM transactions\n- Missing required transaction fields\n- Incorrect parameter formats\n- Unsupported transaction types\n- Network-specific transaction format mismatches", + /// "metadata_key_too_long": "This error occurs when a metadata key exceeds the maximum allowed length.\n\n**Steps to resolve:**\n1. Shorten the metadata key to 40 characters or less\n2. Use abbreviations or shorter naming conventions\n3. Consider using a key-value structure where the value contains the longer identifier\n\n**Limits:**\n- Maximum key length: 40 characters", + /// "metadata_too_many_entries": "This error occurs when the transfer metadata contains more entries than allowed.\n\n**Steps to resolve:**\n1. Reduce the number of metadata entries (maximum 10 allowed)\n2. Consolidate related data into fewer keys\n3. Store additional data externally and reference it with a single metadata entry\n\n**Limits:**\n- Maximum entries: 10", + /// "metadata_value_too_long": "This error occurs when a metadata value exceeds the maximum allowed length.\n\n**Steps to resolve:**\n1. Shorten the metadata value to 500 characters or less\n2. Store longer data externally and reference it with a shorter identifier\n3. Consider compressing or encoding the data if appropriate\n\n**Limits:**\n- Maximum value length: 500 characters", + /// "mfa_already_enrolled": "This error occurs when attempting to enroll in an MFA method that the user has already enrolled in.\n\n**Steps to resolve:**\n1. Check if the user is already enrolled in the MFA method before initiating enrollment\n2. To update or reset MFA, remove the existing enrollment first (if supported)\n3. Use a different MFA method if multiple options are available", + /// "mfa_flow_expired": "This error occurs when the MFA enrollment or verification session has expired.\n\n**Steps to resolve:**\n1. Restart the MFA enrollment or verification flow\n2. Complete the flow within the allowed time window (typically 5 minutes)\n3. Ensure the user doesn't leave the flow idle for extended periods\n\n**Note:** MFA sessions expire automatically for security purposes.", + /// "mfa_invalid_code": "This error occurs when the MFA code provided is incorrect or has already been used.\n\n**Steps to resolve:**\n1. Verify the user entered the correct code from their authenticator app\n2. Ensure the code is current (TOTP codes expire after 30 seconds)\n3. Check that the device time is synchronized correctly\n4. Ask the user to generate a new code and try again\n\n**Common causes:**\n- Typing errors in the 6-digit code\n- Using an expired TOTP code\n- Device clock drift on user's authenticator app\n- Attempting to reuse a previously submitted code", + /// "mfa_not_enrolled": "This error occurs when attempting to verify MFA for a user who has not enrolled in any MFA method.\n\n**Steps to resolve:**\n1. Check if the user has enrolled in MFA before attempting verification\n2. Guide the user through MFA enrollment first using the `/mfa/enroll/{mfaMethod}/init` endpoint\n3. Complete enrollment before requiring MFA verification", + /// "mfa_required": "This error occurs when attempting to perform a sensitive operation that requires MFA verification, but the user has not completed MFA verification.\n\n**Steps to resolve:**\n1. Initiate the MFA verification flow using the `/mfa/verify/{mfaMethod}/init` endpoint\n2. Prompt the user to enter their MFA code\n3. Submit the verification using the `/mfa/verify/{mfaMethod}/submit` endpoint\n4. Use the returned access token with MFA claim for the sensitive operation\n5. Retry the original request with the new MFA-verified token\n\n**Operations requiring MFA:**\n- Transactions Sign/Send\n- Key export\n- Account management actions (when configured)", + /// "network_not_tradable": "This error occurs when the selected asset cannot be purchased on the selected network in the user's location.\n\n**Steps to resolve:**\n1. Verify the asset is tradable on the selected network\n2. Check the user's location to ensure it is allowed to purchase the asset on the selected network\n\n**Common causes:**\n- Users in NY are not allowed to purchase USDC on any network other than Ethereum", + /// "not_found": "This error occurs when the resource specified in your request doesn't exist or you don't have access to it.\n\n**Steps to resolve:**\n1. Verify the resource ID/address/account exists\n2. Check your permissions to access the resource\n3. Ensure you're using the correct network/environment\n4. Confirm the resource hasn't been deleted\n\n**Common causes:**\n- Mistyped addresses\n- Accessing resources from the wrong CDP project\n- Resource was deleted or hasn't been created yet", + /// "order_already_canceled": "This error occurs when attempting to cancel or execute an order that has already been canceled.\n\n**Steps to resolve:**\n1. Check the current status of the order using `GET /v2/orders/{orderId}`.\n2. Create a new order if you still want to trade.", + /// "order_already_filled": "This error occurs when attempting to cancel or modify an order that has already been filled.\n\n**Steps to resolve:**\n1. Check the current status of the order using `GET /v2/orders/{orderId}`.\n2. A filled order cannot be canceled or re-executed.", + /// "order_quote_expired": "This error occurs when attempting to execute an order whose quote has expired.\n\n**Steps to resolve:**\n1. Create a new order with `execute: false` to get an updated quote.\n2. Execute the new order before the quote expires (check the `expiresAt` field).\n3. Alternatively, create a new order with `execute: true` to skip the quote step and execute immediately.", + /// "payment_method_required": "This error occurs when a payment method is required to complete the requested operation but none is configured or available.\n\n**Steps to resolve:**\n1. Add a valid payment method to your account using the [CDP Portal](https://portal.cdp.coinbase.com)\n2. Ensure your payment method is valid and not expired\n\n**Common causes:**\n- No payment method configured on the account\n- Payment method is expired", + /// "payment_required": "This error occurs when an x402 payment is required to access the requested resource.\n\n**Steps to resolve:**\n1. Include a valid x402 payment header in your request\n2. Ensure the payment meets the resource's pricing requirements", + /// "phone_number_verification_expired": "This error occurs when the user's phone number verification has expired. Use of guest Onramp requires the user's\nphone number to be verified every 60 days.\n\n**Steps to resolve:**\n1. Re-verify the user's phone number via OTP.\n2. Retry the request with the phoneNumberVerifiedAt field set to new verification timestamp.", + /// "policy_in_use": "This error occurs when trying to delete a Policy that is currently in use by at least one project or account.\n\n**Steps to resolve:**\n1. Update project or accounts to remove references to the Policy in question.\n2. Retry your delete request.", + /// "rate_limit_exceeded": "This error occurs when you've exceeded the API rate limits.\n\n**Steps to resolve:**\n1. Implement exponential backoff\n2. Cache responses where possible\n3. Wait for rate limit window to reset\n\n**Best practices:**\n```typescript lines wrap\nasync function withRetry(fn: () => Promise) {\n let delay = 1000;\n while (true) {\n try {\n return await fn();\n } catch (e) {\n if (e.errorType === \"rate_limit_exceeded\") {\n await sleep(delay);\n delay *= 2;\n continue;\n }\n throw e;\n }\n }\n}\n```", + /// "recipient_allowlist_pending": "This error occurs when the user is not allowed to receive funds at this address, because changes to their coinbase account allowlist are pending.\n**Steps to resolve:**\n1. Wait approximately 2 days for updates to take effect.", + /// "recipient_allowlist_violation": "This error occurs when the user is not allowed to receive funds at this address, according to their coinbase account allowlist.\n**Steps to resolve:**\n1. Either disable the allowlist or add the wallet address at https://www.coinbase.com/settings/allowlist\n2. Wait approximately 2 days for updates to take effect.", + /// "refund_expired": "Returned when a refund attempt is made after the payment session's refund deadline has passed. The payment session can no longer be refunded.", + /// "request_canceled": "This error occurs when the client cancels an in-progress request before it completes.\n\n**Steps to resolve:**\n1. Check client-side timeout configurations\n2. Review request cancellation logic in your code\n3. Consider increasing timeout thresholds for long-running operations\n4. Implement request tracking to identify premature cancellations\n\n**Best practices:**\n```typescript lines wrap\nasync function withTimeout(promise: Promise, timeoutMs: number): Promise {\n const timeout = new Promise((_, reject) => {\n setTimeout(() => {\n reject(new Error(\"Operation timed out\"));\n }, timeoutMs);\n });\n\n try {\n return await Promise.race([promise, timeout]);\n } catch (error) {\n // Handle timeout or cancellation\n throw error;\n }\n}\n```", + /// "service_unavailable": "This error occurs when the CDP API is temporarily unable to handle requests due to maintenance or high load.\n\n**Steps to resolve:**\n1. Retry your request after a short delay\n2. If persistent, contact CDP support with:\n - The timestamp of the error\n - Request details\n3. Consider implementing retry logic with an exponential backoff\n\n**Note:** These errors are automatically logged and monitored by CDP.", + /// "settlement_failed": "This error occurs when an x402 payment was verified but settlement on-chain failed.\n\n**Steps to resolve:**\n1. Retry the request with a new payment\n2. Ensure the payment asset has sufficient balance for settlement", + /// "source_account_invalid": "This error occurs when the source account specified in the transfer request is invalid or malformed.\n\n**Steps to resolve:**\n1. Verify the account ID format is correct (e.g., `account_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`)\n2. Ensure the account ID belongs to your CDP entity\n3. Verify the account ID exists by calling `GET /v2/accounts/{accountId}` or `GET /v2/accounts`\n\n**Common causes:**\n- Malformed account ID\n- Typo in the account ID", + /// "source_account_not_found": "This error occurs when the source account specified in the transfer does not exist.\n\n**Steps to resolve:**\n1. Verify the account ID exists by calling `GET /v2/accounts/{accountId}` or `GET /v2/accounts`", + /// "source_asset_not_supported": "This error occurs when the asset specified in the transfer source is not supported for this transfer type.\n\n**Steps to resolve:**\n1. Check the list of supported assets for the source account type\n2. Verify the asset symbol is correctly specified (e.g., `usdc`, `usdt`)\n\n**Common causes:**\n- Unsupported asset for the transfer route\n- Incorrect asset symbol", + /// "target_account_invalid": "This error occurs when the target account specified in the transfer request is invalid or malformed.\n\n**Steps to resolve:**\n1. Verify the account ID format is correct (e.g., `account_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`)\n2. Ensure the account exists and can receive funds\n3. Verify the account ID exists by calling `GET /v2/accounts/{accountId}` or `GET /v2/accounts`\n\n**Common causes:**\n- Malformed account ID\n- Typo in the account ID", + /// "target_account_not_found": "This error occurs when the target account specified in the transfer does not exist.\n\n**Steps to resolve:**\n1. Verify the account ID exists by calling `GET /v2/accounts/{accountId}` or `GET /v2/accounts`", + /// "target_asset_not_supported": "This error occurs when the asset specified in the transfer target is not supported for this transfer type.\n\n**Steps to resolve:**\n1. Check the list of supported assets for the target\n2. Verify the asset symbol is correctly specified (e.g., `usdc`, `usdt`)\n3. Ensure the target can receive this asset type\n\n**Common causes:**\n- Asset not supported by the target\n- Unsupported conversion between source and target assets", + /// "target_email_invalid": "This error occurs when the email address specified as the transfer target is invalid.\n\n**Steps to resolve:**\n1. Verify the email address format is valid (e.g., `user@example.com`)\n2. Check for typos in the email address\n3. Ensure the email domain is valid\n\n**Common causes:**\n- Invalid email format\n- Missing @ symbol or domain\n- Typo in the email address", + /// "target_onchain_address_invalid": "This error occurs when the onchain address specified as the transfer target is invalid for the specified network.\n\n**Steps to resolve:**\n1. Ensure the network is supported for the transfer type\n2. Verify the address format matches the target network\n3. Ensure you haven't mixed up addresses from different networks\n\n**Common causes:**\n- Network not supported for the transfer type\n- Address format doesn't match network\n- Address from a different blockchain network", + /// "timed_out": "This error occurs when a request exceeds the maximum allowed processing time.\n\n**Steps to resolve:**\n1. Break down large requests into smaller chunks (if applicable)\n2. Implement retry logic with exponential backoff\n3. Use streaming endpoints for large data sets\n\n**Example retry implementation:**\n```typescript lines wrap\nasync function withRetryAndTimeout(\n operation: () => Promise,\n maxRetries = 3,\n timeout = 30000,\n): Promise {\n let attempts = 0;\n while (attempts < maxRetries) {\n try {\n return await Promise.race([\n operation(),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error(\"Timeout\")), timeout)\n ),\n ]);\n } catch (error) {\n attempts++;\n if (attempts === maxRetries) throw error;\n // Exponential backoff\n await new Promise(resolve =>\n setTimeout(resolve, Math.pow(2, attempts) * 1000)\n );\n }\n }\n throw new Error(\"Max retries exceeded\");\n}\n```", + /// "transaction_simulation_failed": "This error occurs when the pre-broadcast simulation of the swap transaction predicted a revert.\nNo transaction was submitted and no gas was spent.\n\n**Common causes:**\n- The on-chain price moved past the `slippageBps` tolerance between the price estimate and execution\n- Taker balance changed between the price estimate and execution\n\n**Steps to resolve:**\n1. Retry immediately — prices change quickly and a new quote may succeed\n2. Increase `slippageBps` if retries continue to fail (e.g. from 100 to 200)\n3. For large swaps, consider splitting into smaller amounts to reduce price impact", + /// "transfer_amount_invalid": "This error occurs when the transfer amount is invalid.\n\n**Steps to resolve:**\n1. Ensure the amount is a positive number and greater than $1 USD equivalent amount\n2. Verify the amount format is a valid decimal string (e.g., `\"100.50\"`)\n3. Check the number of decimal places for the asset\n\n**Common causes:**\n- Zero or negative amount\n- Too many decimal places for the asset\n- Amount below minimum threshold ($1 USD equivalent amount)", + /// "transfer_asset_not_supported": "This error occurs when the asset specified for the transfer is not supported.\n\n**Steps to resolve:**\n1. Check the list of supported assets for transfers\n2. Verify the asset symbol is correctly specified\n3. Ensure the asset is supported for the transfer route (source → target)\n\n**Common causes:**\n- Asset not supported for transfers\n- Incorrect asset symbol", + /// "transfer_quote_expired": "This error occurs when the transfer quote has expired. Quotes are valid for a limited time.\n\n**Steps to resolve:**\n1. Create a new transfer to obtain a fresh quote\n2. Execute the transfer promptly after creation\n\n**Common causes:**\n- Too much time elapsed between creating and executing the transfer", + /// "travel_rules_field_missing": "This error occurs when required travel rule fields are missing from the transfer request.\n\n**Steps to resolve:**\n1. Include the `travelRule` object in your transfer request\n2. Supply the required missing fields prompted by the error message\n3. Review the travel rule requirements for your jurisdiction\n\nNote: Required fields may vary by region.", + /// "travel_rules_recipient_violation": "This error occurs when the user is not allowed to receive funds at this address, because it violates travel rules.\n**Steps to resolve:**\n1. Ensure your desired transfer is not blocked by local travel regulations.", + /// "unauthorized": "This error occurs when authentication fails.\n\n**Steps to resolve:**\n1. Verify your CDP API credentials:\n - Check that your API key is valid\n - Check that your Wallet Secret is properly configured\n2. Validate JWT token:\n - Not expired\n - Properly signed\n - Contains required claims\n3. Check request headers:\n - Authorization header present\n - X-Wallet-Auth header included when required\n\n**Security note:** Never share your Wallet Secret or API keys.", + /// "unsupported_tos_language": "A submitted Terms of Service acceptance used a `language` that is not published for the referenced `versionId`.\n\n**Steps to resolve:**\n1. Read `Customer.requirements.tos.tosVersions[]` and find the entry whose `versionId` matches your acceptance.\n2. Choose a `language` from that entry's `languages` list (BCP 47 tags).\n3. Retry with `tosAcceptances[].language` set to a supported tag." + /// } + ///} + /// ``` + ///
+ #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum ErrorType { + #[serde(rename = "already_exists")] + AlreadyExists, + #[serde(rename = "authorization_expired")] + AuthorizationExpired, + #[serde(rename = "bad_gateway")] + BadGateway, + #[serde(rename = "capture_expired")] + CaptureExpired, + #[serde(rename = "client_closed_request")] + ClientClosedRequest, + #[serde(rename = "endpoint_unavailable")] + EndpointUnavailable, + #[serde(rename = "faucet_limit_exceeded")] + FaucetLimitExceeded, + #[serde(rename = "forbidden")] + Forbidden, + #[serde(rename = "idempotency_error")] + IdempotencyError, + #[serde(rename = "internal_server_error")] + InternalServerError, #[serde(rename = "invalid_request")] InvalidRequest, #[serde(rename = "invalid_sql_query")] @@ -12803,6 +15346,8 @@ pub mod types { TimedOut, #[serde(rename = "unauthorized")] Unauthorized, + #[serde(rename = "unsupported_tos_language")] + UnsupportedTosLanguage, #[serde(rename = "policy_violation")] PolicyViolation, #[serde(rename = "policy_in_use")] @@ -12851,6 +15396,8 @@ pub mod types { TransferAmountInvalid, #[serde(rename = "transfer_asset_not_supported")] TransferAssetNotSupported, + #[serde(rename = "transfer_quote_expired")] + TransferQuoteExpired, #[serde(rename = "insufficient_balance")] InsufficientBalance, #[serde(rename = "metadata_too_many_entries")] @@ -12887,6 +15434,16 @@ pub mod types { InsufficientAllowance, #[serde(rename = "transaction_simulation_failed")] TransactionSimulationFailed, + #[serde(rename = "delegation_not_found")] + DelegationNotFound, + #[serde(rename = "delegation_expired")] + DelegationExpired, + #[serde(rename = "delegation_revoked")] + DelegationRevoked, + #[serde(rename = "delegation_not_authorized")] + DelegationNotAuthorized, + #[serde(rename = "delegation_not_enabled")] + DelegationNotEnabled, } impl ::std::convert::From<&Self> for ErrorType { fn from(value: &ErrorType) -> Self { @@ -12901,6 +15458,7 @@ pub mod types { Self::BadGateway => f.write_str("bad_gateway"), Self::CaptureExpired => f.write_str("capture_expired"), Self::ClientClosedRequest => f.write_str("client_closed_request"), + Self::EndpointUnavailable => f.write_str("endpoint_unavailable"), Self::FaucetLimitExceeded => f.write_str("faucet_limit_exceeded"), Self::Forbidden => f.write_str("forbidden"), Self::IdempotencyError => f.write_str("idempotency_error"), @@ -12918,6 +15476,7 @@ pub mod types { Self::ServiceUnavailable => f.write_str("service_unavailable"), Self::TimedOut => f.write_str("timed_out"), Self::Unauthorized => f.write_str("unauthorized"), + Self::UnsupportedTosLanguage => f.write_str("unsupported_tos_language"), Self::PolicyViolation => f.write_str("policy_violation"), Self::PolicyInUse => f.write_str("policy_in_use"), Self::AccountLimitExceeded => f.write_str("account_limit_exceeded"), @@ -12946,6 +15505,7 @@ pub mod types { Self::TargetOnchainAddressInvalid => f.write_str("target_onchain_address_invalid"), Self::TransferAmountInvalid => f.write_str("transfer_amount_invalid"), Self::TransferAssetNotSupported => f.write_str("transfer_asset_not_supported"), + Self::TransferQuoteExpired => f.write_str("transfer_quote_expired"), Self::InsufficientBalance => f.write_str("insufficient_balance"), Self::MetadataTooManyEntries => f.write_str("metadata_too_many_entries"), Self::MetadataKeyTooLong => f.write_str("metadata_key_too_long"), @@ -12964,6 +15524,11 @@ pub mod types { Self::InsufficientLiquidity => f.write_str("insufficient_liquidity"), Self::InsufficientAllowance => f.write_str("insufficient_allowance"), Self::TransactionSimulationFailed => f.write_str("transaction_simulation_failed"), + Self::DelegationNotFound => f.write_str("delegation_not_found"), + Self::DelegationExpired => f.write_str("delegation_expired"), + Self::DelegationRevoked => f.write_str("delegation_revoked"), + Self::DelegationNotAuthorized => f.write_str("delegation_not_authorized"), + Self::DelegationNotEnabled => f.write_str("delegation_not_enabled"), } } } @@ -12976,6 +15541,7 @@ pub mod types { "bad_gateway" => Ok(Self::BadGateway), "capture_expired" => Ok(Self::CaptureExpired), "client_closed_request" => Ok(Self::ClientClosedRequest), + "endpoint_unavailable" => Ok(Self::EndpointUnavailable), "faucet_limit_exceeded" => Ok(Self::FaucetLimitExceeded), "forbidden" => Ok(Self::Forbidden), "idempotency_error" => Ok(Self::IdempotencyError), @@ -12993,6 +15559,7 @@ pub mod types { "service_unavailable" => Ok(Self::ServiceUnavailable), "timed_out" => Ok(Self::TimedOut), "unauthorized" => Ok(Self::Unauthorized), + "unsupported_tos_language" => Ok(Self::UnsupportedTosLanguage), "policy_violation" => Ok(Self::PolicyViolation), "policy_in_use" => Ok(Self::PolicyInUse), "account_limit_exceeded" => Ok(Self::AccountLimitExceeded), @@ -13017,6 +15584,7 @@ pub mod types { "target_onchain_address_invalid" => Ok(Self::TargetOnchainAddressInvalid), "transfer_amount_invalid" => Ok(Self::TransferAmountInvalid), "transfer_asset_not_supported" => Ok(Self::TransferAssetNotSupported), + "transfer_quote_expired" => Ok(Self::TransferQuoteExpired), "insufficient_balance" => Ok(Self::InsufficientBalance), "metadata_too_many_entries" => Ok(Self::MetadataTooManyEntries), "metadata_key_too_long" => Ok(Self::MetadataKeyTooLong), @@ -13035,6 +15603,11 @@ pub mod types { "insufficient_liquidity" => Ok(Self::InsufficientLiquidity), "insufficient_allowance" => Ok(Self::InsufficientAllowance), "transaction_simulation_failed" => Ok(Self::TransactionSimulationFailed), + "delegation_not_found" => Ok(Self::DelegationNotFound), + "delegation_expired" => Ok(Self::DelegationExpired), + "delegation_revoked" => Ok(Self::DelegationRevoked), + "delegation_not_authorized" => Ok(Self::DelegationNotAuthorized), + "delegation_not_enabled" => Ok(Self::DelegationNotEnabled), _ => Err("invalid value".into()), } } @@ -17484,6 +20057,162 @@ pub mod types { }) } } + ///`ExecuteFundTransferTransferId` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "type": "string", + /// "pattern": "^transfer_[a-f0-9\\-]{36}$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct ExecuteFundTransferTransferId(::std::string::String); + impl ::std::ops::Deref for ExecuteFundTransferTransferId { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: ExecuteFundTransferTransferId) -> Self { + value.0 + } + } + impl ::std::convert::From<&ExecuteFundTransferTransferId> for ExecuteFundTransferTransferId { + fn from(value: &ExecuteFundTransferTransferId) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for ExecuteFundTransferTransferId { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^transfer_[a-f0-9\\-]{36}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^transfer_[a-f0-9\\-]{36}$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for ExecuteFundTransferTransferId { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for ExecuteFundTransferTransferId { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for ExecuteFundTransferTransferId { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for ExecuteFundTransferTransferId { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///`ExecuteFundTransferXIdempotencyKey` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "type": "string", + /// "maxLength": 128, + /// "minLength": 1 + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct ExecuteFundTransferXIdempotencyKey(::std::string::String); + impl ::std::ops::Deref for ExecuteFundTransferXIdempotencyKey { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: ExecuteFundTransferXIdempotencyKey) -> Self { + value.0 + } + } + impl ::std::convert::From<&ExecuteFundTransferXIdempotencyKey> + for ExecuteFundTransferXIdempotencyKey + { + fn from(value: &ExecuteFundTransferXIdempotencyKey) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for ExecuteFundTransferXIdempotencyKey { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + if value.chars().count() > 128usize { + return Err("longer than 128 characters".into()); + } + if value.chars().count() < 1usize { + return Err("shorter than 1 characters".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for ExecuteFundTransferXIdempotencyKey { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for ExecuteFundTransferXIdempotencyKey { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for ExecuteFundTransferXIdempotencyKey { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for ExecuteFundTransferXIdempotencyKey { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } ///`ExportEvmAccountAddress` /// ///
JSON schema @@ -18258,6 +20987,408 @@ pub mod types { }) } } + ///Details specific to Fedwire (domestic USD wire) payment methods. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "Details specific to Fedwire (domestic USD wire) payment methods.", + /// "examples": [ + /// { + /// "accountLast4": "1234", + /// "asset": "usd", + /// "bankName": "ALLY BANK", + /// "routingNumber": "124003116" + /// } + /// ], + /// "type": "object", + /// "required": [ + /// "accountLast4", + /// "asset", + /// "bankName", + /// "routingNumber" + /// ], + /// "properties": { + /// "accountLast4": { + /// "description": "The last 4 digits of the bank account number.", + /// "examples": [ + /// "1234" + /// ], + /// "type": "string", + /// "pattern": "^[0-9]{4}$" + /// }, + /// "asset": { + /// "description": "The asset for this payment method. Always `usd` for Fedwire.", + /// "examples": [ + /// "usd" + /// ], + /// "type": "string" + /// }, + /// "bankName": { + /// "description": "The name of the bank.", + /// "examples": [ + /// "ALLY BANK" + /// ], + /// "type": "string" + /// }, + /// "routingNumber": { + /// "description": "The ABA routing number of the bank.", + /// "examples": [ + /// "124003116" + /// ], + /// "type": "string", + /// "pattern": "^[0-9]{9}$" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct FedwireDetails { + ///The last 4 digits of the bank account number. + #[serde(rename = "accountLast4")] + pub account_last4: FedwireDetailsAccountLast4, + ///The asset for this payment method. Always `usd` for Fedwire. + pub asset: ::std::string::String, + ///The name of the bank. + #[serde(rename = "bankName")] + pub bank_name: ::std::string::String, + ///The ABA routing number of the bank. + #[serde(rename = "routingNumber")] + pub routing_number: FedwireDetailsRoutingNumber, + } + impl ::std::convert::From<&FedwireDetails> for FedwireDetails { + fn from(value: &FedwireDetails) -> Self { + value.clone() + } + } + impl FedwireDetails { + pub fn builder() -> builder::FedwireDetails { + Default::default() + } + } + ///The last 4 digits of the bank account number. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The last 4 digits of the bank account number.", + /// "examples": [ + /// "1234" + /// ], + /// "type": "string", + /// "pattern": "^[0-9]{4}$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct FedwireDetailsAccountLast4(::std::string::String); + impl ::std::ops::Deref for FedwireDetailsAccountLast4 { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: FedwireDetailsAccountLast4) -> Self { + value.0 + } + } + impl ::std::convert::From<&FedwireDetailsAccountLast4> for FedwireDetailsAccountLast4 { + fn from(value: &FedwireDetailsAccountLast4) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for FedwireDetailsAccountLast4 { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| ::regress::Regex::new("^[0-9]{4}$").unwrap()); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^[0-9]{4}$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for FedwireDetailsAccountLast4 { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for FedwireDetailsAccountLast4 { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for FedwireDetailsAccountLast4 { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for FedwireDetailsAccountLast4 { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///The ABA routing number of the bank. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The ABA routing number of the bank.", + /// "examples": [ + /// "124003116" + /// ], + /// "type": "string", + /// "pattern": "^[0-9]{9}$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct FedwireDetailsRoutingNumber(::std::string::String); + impl ::std::ops::Deref for FedwireDetailsRoutingNumber { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: FedwireDetailsRoutingNumber) -> Self { + value.0 + } + } + impl ::std::convert::From<&FedwireDetailsRoutingNumber> for FedwireDetailsRoutingNumber { + fn from(value: &FedwireDetailsRoutingNumber) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for FedwireDetailsRoutingNumber { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| ::regress::Regex::new("^[0-9]{9}$").unwrap()); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^[0-9]{9}$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for FedwireDetailsRoutingNumber { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for FedwireDetailsRoutingNumber { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for FedwireDetailsRoutingNumber { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for FedwireDetailsRoutingNumber { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///A Fedwire (domestic USD wire) payment method linked to your entity. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "title": "FedwirePaymentMethod", + /// "description": "A Fedwire (domestic USD wire) payment method linked to your entity.", + /// "examples": [ + /// { + /// "active": true, + /// "createdAt": "2024-01-15T10:30:00Z", + /// "fedwire": { + /// "accountLast4": "1234", + /// "asset": "usd", + /// "bankName": "ALLY BANK", + /// "routingNumber": "124003116" + /// }, + /// "paymentMethodId": "paymentMethod_8e03978e-40d5-43e8-bc93-6894a57f9324", + /// "paymentRail": "fedwire", + /// "updatedAt": "2024-01-15T10:30:00Z" + /// } + /// ], + /// "type": "object", + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/PaymentMethodBase" + /// }, + /// { + /// "type": "object", + /// "required": [ + /// "fedwire", + /// "paymentRail" + /// ], + /// "properties": { + /// "fedwire": { + /// "description": "Fedwire (domestic USD wire) details.", + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/FedwireDetails" + /// } + /// ] + /// }, + /// "paymentRail": { + /// "description": "The payment rail for this payment method.", + /// "examples": [ + /// "fedwire" + /// ], + /// "type": "string", + /// "enum": [ + /// "fedwire" + /// ] + /// } + /// } + /// } + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct FedwirePaymentMethod { + ///Whether the payment method is active and can be used in transfers. A payment method may be inactive due to verification requirements or entity-level restrictions. + pub active: bool, + ///The timestamp when the payment method was created. + #[serde(rename = "createdAt")] + pub created_at: ::chrono::DateTime<::chrono::offset::Utc>, + ///Fedwire (domestic USD wire) details. + pub fedwire: FedwireDetails, + #[serde(rename = "paymentMethodId")] + pub payment_method_id: PaymentMethodId, + ///The payment rail for this payment method. + #[serde(rename = "paymentRail")] + pub payment_rail: FedwirePaymentMethodPaymentRail, + ///The timestamp when the payment method was last updated. + #[serde(rename = "updatedAt")] + pub updated_at: ::chrono::DateTime<::chrono::offset::Utc>, + } + impl ::std::convert::From<&FedwirePaymentMethod> for FedwirePaymentMethod { + fn from(value: &FedwirePaymentMethod) -> Self { + value.clone() + } + } + impl FedwirePaymentMethod { + pub fn builder() -> builder::FedwirePaymentMethod { + Default::default() + } + } + ///The payment rail for this payment method. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The payment rail for this payment method.", + /// "examples": [ + /// "fedwire" + /// ], + /// "type": "string", + /// "enum": [ + /// "fedwire" + /// ] + ///} + /// ``` + ///
+ #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum FedwirePaymentMethodPaymentRail { + #[serde(rename = "fedwire")] + Fedwire, + } + impl ::std::convert::From<&Self> for FedwirePaymentMethodPaymentRail { + fn from(value: &FedwirePaymentMethodPaymentRail) -> Self { + value.clone() + } + } + impl ::std::fmt::Display for FedwirePaymentMethodPaymentRail { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Fedwire => f.write_str("fedwire"), + } + } + } + impl ::std::str::FromStr for FedwirePaymentMethodPaymentRail { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "fedwire" => Ok(Self::Fedwire), + _ => Err("invalid value".into()), + } + } + } + impl ::std::convert::TryFrom<&str> for FedwirePaymentMethodPaymentRail { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for FedwirePaymentMethodPaymentRail { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for FedwirePaymentMethodPaymentRail { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } ///The amount of the `fromToken` to send in atomic units of the token. For example, `1000000000000000000` when sending ETH equates to 1 ETH, `1000000` when sending USDC equates to 1 USDC, etc. /// ///
JSON schema @@ -21028,6 +24159,86 @@ pub mod types { Self::SwapUnavailableResponse(value) } } + ///`GetTransferByIdTransferId` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "examples": [ + /// "transfer_af2937b0-9846-4fe7-bfe9-ccc22d935114" + /// ], + /// "type": "string", + /// "pattern": "^transfer_[a-f0-9\\-]{36}$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct GetTransferByIdTransferId(::std::string::String); + impl ::std::ops::Deref for GetTransferByIdTransferId { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: GetTransferByIdTransferId) -> Self { + value.0 + } + } + impl ::std::convert::From<&GetTransferByIdTransferId> for GetTransferByIdTransferId { + fn from(value: &GetTransferByIdTransferId) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for GetTransferByIdTransferId { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^transfer_[a-f0-9\\-]{36}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^transfer_[a-f0-9\\-]{36}$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for GetTransferByIdTransferId { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for GetTransferByIdTransferId { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for GetTransferByIdTransferId { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for GetTransferByIdTransferId { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } ///`GetUserOperationAddress` /// ///
JSON schema @@ -22751,6 +25962,45 @@ pub mod types { value.parse() } } + ///`ListBalancesResponse` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/Balances" + /// }, + /// { + /// "$ref": "#/components/schemas/ListResponse" + /// } + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct ListBalancesResponse { + ///The list of balances. + pub balances: ::std::vec::Vec, + ///The token for the next page of items, if any. + #[serde( + rename = "nextPageToken", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub next_page_token: ::std::option::Option<::std::string::String>, + } + impl ::std::convert::From<&ListBalancesResponse> for ListBalancesResponse { + fn from(value: &ListBalancesResponse) -> Self { + value.clone() + } + } + impl ListBalancesResponse { + pub fn builder() -> builder::ListBalancesResponse { + Default::default() + } + } ///`ListDataTokenBalancesAddress` /// ///
JSON schema @@ -22907,6 +26157,58 @@ pub mod types { Default::default() } } + ///`ListDepositDestinationsResponse` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "allOf": [ + /// { + /// "type": "object", + /// "required": [ + /// "depositDestinations" + /// ], + /// "properties": { + /// "depositDestinations": { + /// "description": "The list of deposit destinations.", + /// "type": "array", + /// "items": { + /// "$ref": "#/components/schemas/DepositDestination" + /// } + /// } + /// } + /// }, + /// { + /// "$ref": "#/components/schemas/ListResponse" + /// } + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct ListDepositDestinationsResponse { + ///The list of deposit destinations. + #[serde(rename = "depositDestinations")] + pub deposit_destinations: ::std::vec::Vec, + ///The token for the next page of items, if any. + #[serde( + rename = "nextPageToken", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub next_page_token: ::std::option::Option<::std::string::String>, + } + impl ::std::convert::From<&ListDepositDestinationsResponse> for ListDepositDestinationsResponse { + fn from(value: &ListDepositDestinationsResponse) -> Self { + value.clone() + } + } + impl ListDepositDestinationsResponse { + pub fn builder() -> builder::ListDepositDestinationsResponse { + Default::default() + } + } ///`ListEndUsersResponse` /// ///
JSON schema @@ -23380,6 +26682,109 @@ pub mod types { Default::default() } } + ///`ListFoundationAccountsResponse` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "allOf": [ + /// { + /// "type": "object", + /// "required": [ + /// "accounts" + /// ], + /// "properties": { + /// "accounts": { + /// "description": "The list of accounts.", + /// "type": "array", + /// "items": { + /// "$ref": "#/components/schemas/Account" + /// } + /// } + /// } + /// }, + /// { + /// "$ref": "#/components/schemas/ListResponse" + /// } + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct ListFoundationAccountsResponse { + ///The list of accounts. + pub accounts: ::std::vec::Vec, + ///The token for the next page of items, if any. + #[serde( + rename = "nextPageToken", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub next_page_token: ::std::option::Option<::std::string::String>, + } + impl ::std::convert::From<&ListFoundationAccountsResponse> for ListFoundationAccountsResponse { + fn from(value: &ListFoundationAccountsResponse) -> Self { + value.clone() + } + } + impl ListFoundationAccountsResponse { + pub fn builder() -> builder::ListFoundationAccountsResponse { + Default::default() + } + } + ///`ListPaymentMethodsResponse` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "allOf": [ + /// { + /// "type": "object", + /// "required": [ + /// "paymentMethods" + /// ], + /// "properties": { + /// "paymentMethods": { + /// "description": "The list of payment methods.", + /// "type": "array", + /// "items": { + /// "$ref": "#/components/schemas/payment-methods_PaymentMethod" + /// } + /// } + /// } + /// }, + /// { + /// "$ref": "#/components/schemas/ListResponse" + /// } + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct ListPaymentMethodsResponse { + ///The token for the next page of items, if any. + #[serde( + rename = "nextPageToken", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub next_page_token: ::std::option::Option<::std::string::String>, + ///The list of payment methods. + #[serde(rename = "paymentMethods")] + pub payment_methods: ::std::vec::Vec, + } + impl ::std::convert::From<&ListPaymentMethodsResponse> for ListPaymentMethodsResponse { + fn from(value: &ListPaymentMethodsResponse) -> Self { + value.clone() + } + } + impl ListPaymentMethodsResponse { + pub fn builder() -> builder::ListPaymentMethodsResponse { + Default::default() + } + } ///`ListPoliciesResponse` /// ///
JSON schema @@ -24123,6 +27528,134 @@ pub mod types { value.parse() } } + ///`ListTransfersResponse` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "allOf": [ + /// { + /// "type": "object", + /// "required": [ + /// "transfers" + /// ], + /// "properties": { + /// "transfers": { + /// "description": "The list of transfers.", + /// "type": "array", + /// "items": { + /// "$ref": "#/components/schemas/Transfer" + /// } + /// } + /// } + /// }, + /// { + /// "$ref": "#/components/schemas/ListResponse" + /// } + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct ListTransfersResponse { + ///The token for the next page of items, if any. + #[serde( + rename = "nextPageToken", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub next_page_token: ::std::option::Option<::std::string::String>, + ///The list of transfers. + pub transfers: ::std::vec::Vec, + } + impl ::std::convert::From<&ListTransfersResponse> for ListTransfersResponse { + fn from(value: &ListTransfersResponse) -> Self { + value.clone() + } + } + impl ListTransfersResponse { + pub fn builder() -> builder::ListTransfersResponse { + Default::default() + } + } + ///`ListTransfersTransferId` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "type": "string", + /// "pattern": "^transfer_[a-f0-9\\-]{36}$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct ListTransfersTransferId(::std::string::String); + impl ::std::ops::Deref for ListTransfersTransferId { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: ListTransfersTransferId) -> Self { + value.0 + } + } + impl ::std::convert::From<&ListTransfersTransferId> for ListTransfersTransferId { + fn from(value: &ListTransfersTransferId) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for ListTransfersTransferId { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^transfer_[a-f0-9\\-]{36}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^transfer_[a-f0-9\\-]{36}$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for ListTransfersTransferId { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for ListTransfersTransferId { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for ListTransfersTransferId { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for ListTransfersTransferId { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } ///`LookupEndUserPhoneNumber` /// ///
JSON schema @@ -25093,6 +28626,127 @@ pub mod types { value.parse() } } + ///The blockchain network for the payment. Supported networks depend on the account type. See [API and Network Support](https://docs.cdp.coinbase.com/api-reference/payment-apis/supported-networks-assets#by-asset-and-network) for more details. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The blockchain network for the payment. Supported networks depend on the account type. See [API and Network Support](https://docs.cdp.coinbase.com/api-reference/payment-apis/supported-networks-assets#by-asset-and-network) for more details.", + /// "examples": [ + /// "base" + /// ], + /// "type": "string", + /// "enum": [ + /// "base", + /// "ethereum", + /// "solana", + /// "aptos", + /// "arbitrum", + /// "arbitrum-sepolia", + /// "optimism", + /// "polygon", + /// "world", + /// "world-sepolia" + /// ] + ///} + /// ``` + ///
+ #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum Network { + #[serde(rename = "base")] + Base, + #[serde(rename = "ethereum")] + Ethereum, + #[serde(rename = "solana")] + Solana, + #[serde(rename = "aptos")] + Aptos, + #[serde(rename = "arbitrum")] + Arbitrum, + #[serde(rename = "arbitrum-sepolia")] + ArbitrumSepolia, + #[serde(rename = "optimism")] + Optimism, + #[serde(rename = "polygon")] + Polygon, + #[serde(rename = "world")] + World, + #[serde(rename = "world-sepolia")] + WorldSepolia, + } + impl ::std::convert::From<&Self> for Network { + fn from(value: &Network) -> Self { + value.clone() + } + } + impl ::std::fmt::Display for Network { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Base => f.write_str("base"), + Self::Ethereum => f.write_str("ethereum"), + Self::Solana => f.write_str("solana"), + Self::Aptos => f.write_str("aptos"), + Self::Arbitrum => f.write_str("arbitrum"), + Self::ArbitrumSepolia => f.write_str("arbitrum-sepolia"), + Self::Optimism => f.write_str("optimism"), + Self::Polygon => f.write_str("polygon"), + Self::World => f.write_str("world"), + Self::WorldSepolia => f.write_str("world-sepolia"), + } + } + } + impl ::std::str::FromStr for Network { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "base" => Ok(Self::Base), + "ethereum" => Ok(Self::Ethereum), + "solana" => Ok(Self::Solana), + "aptos" => Ok(Self::Aptos), + "arbitrum" => Ok(Self::Arbitrum), + "arbitrum-sepolia" => Ok(Self::ArbitrumSepolia), + "optimism" => Ok(Self::Optimism), + "polygon" => Ok(Self::Polygon), + "world" => Ok(Self::World), + "world-sepolia" => Ok(Self::WorldSepolia), + _ => Err("invalid value".into()), + } + } + } + impl ::std::convert::TryFrom<&str> for Network { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for Network { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for Network { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } ///Information about an end user who authenticates using a third-party provider. /// ///
JSON schema @@ -25264,6 +28918,98 @@ pub mod types { value.parse() } } + ///The target of the payment is an onchain address. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "title": "Onchain Address", + /// "description": "The target of the payment is an onchain address.", + /// "examples": [ + /// { + /// "address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + /// "asset": "usdc", + /// "network": "base" + /// } + /// ], + /// "type": "object", + /// "required": [ + /// "address", + /// "asset", + /// "network" + /// ], + /// "properties": { + /// "address": { + /// "description": "The onchain crypto address of the recipient.\n\nExamples:\n- EVM address: 0xabc1234567890abcdef1234567890abcdef123456\n- Solana address: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT\n- XRP address: rhccc5p23aKiCGFcEqqnjEfLRZ6xEvfy3s\n", + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/BlockchainAddress" + /// } + /// ] + /// }, + /// "asset": { + /// "description": "Asset symbol of the payment received by the recipient.", + /// "examples": [ + /// "btc" + /// ], + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/Asset" + /// } + /// ] + /// }, + /// "destinationTag": { + /// "description": "The destination tag of the onchain address. Destination tags are used by certain networks\n(primarily XRP/Ripple) to identify specific recipients when multiple users share a single address.\nThe tag ensures funds are credited to the correct account within the shared address.\n\nExamples by network:\n- XRP/Ripple: Numeric values like \"1234567890\" or \"123456\"\n- Stellar (XLM): Memos which can be text, ID, or hash format\n\nNote: Most networks (Ethereum, Bitcoin, Solana) do not use destination tags.\n", + /// "type": "string" + /// }, + /// "network": { + /// "$ref": "#/components/schemas/Network" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct OnchainAddress { + /**The onchain crypto address of the recipient. + + Examples: + - EVM address: 0xabc1234567890abcdef1234567890abcdef123456 + - Solana address: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + - XRP address: rhccc5p23aKiCGFcEqqnjEfLRZ6xEvfy3s + */ + pub address: BlockchainAddress, + ///Asset symbol of the payment received by the recipient. + pub asset: Asset, + /**The destination tag of the onchain address. Destination tags are used by certain networks + (primarily XRP/Ripple) to identify specific recipients when multiple users share a single address. + The tag ensures funds are credited to the correct account within the shared address. + + Examples by network: + - XRP/Ripple: Numeric values like "1234567890" or "123456" + - Stellar (XLM): Memos which can be text, ID, or hash format + + Note: Most networks (Ethereum, Bitcoin, Solana) do not use destination tags. + */ + #[serde( + rename = "destinationTag", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub destination_tag: ::std::option::Option<::std::string::String>, + pub network: Network, + } + impl ::std::convert::From<&OnchainAddress> for OnchainAddress { + fn from(value: &OnchainAddress) -> Self { + value.clone() + } + } + impl OnchainAddress { + pub fn builder() -> builder::OnchainAddress { + Default::default() + } + } ///Schema definition for a table column. /// ///
JSON schema @@ -27621,102 +31367,47 @@ pub mod types { Default::default() } } - ///`Policy` + ///The originating US bank account details for the transfer source. Present when funds were deposited from an external bank account into a deposit destination. Only the last 4 digits of the account number are exposed. /// ///
JSON schema /// /// ```json ///{ + /// "title": "Originating Bank Account (US)", + /// "description": "The originating US bank account details for the transfer source. Present when funds were deposited from an external bank account into a deposit destination. Only the last 4 digits of the account number are exposed.", + /// "examples": [ + /// { + /// "accountLast4": "6789", + /// "bankName": "Citibank, N.A.", + /// "currency": "usd" + /// } + /// ], /// "type": "object", /// "required": [ - /// "createdAt", - /// "id", - /// "rules", - /// "scope", - /// "updatedAt" + /// "accountLast4", + /// "bankName", + /// "currency" /// ], /// "properties": { - /// "createdAt": { - /// "description": "The ISO 8601 timestamp at which the Policy was created.", - /// "examples": [ - /// "2025-03-25T12:00:00Z" - /// ], - /// "type": "string" - /// }, - /// "description": { - /// "description": "An optional human-readable description of the policy.\nPolicy descriptions can consist of alphanumeric characters, spaces, commas, and periods, and be 50 characters or less.", - /// "examples": [ - /// "Default policy" - /// ], - /// "type": "string", - /// "pattern": "^[A-Za-z0-9 ,.]{1,50}$" - /// }, - /// "id": { - /// "description": "The unique identifier for the policy.", + /// "accountLast4": { + /// "description": "The last 4 digits of the originating bank account number.", /// "examples": [ - /// "123e4567-e89b-12d3-a456-426614174000" + /// "6789" /// ], /// "type": "string", - /// "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" - /// }, - /// "rules": { - /// "description": "A list of rules that comprise the policy.", - /// "examples": [ - /// [ - /// { - /// "action": "accept", - /// "criteria": [ - /// { - /// "ethValue": "1000000000000000000", - /// "operator": "<=", - /// "type": "ethValue" - /// }, - /// { - /// "addresses": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "0x1234567890123456789012345678901234567890" - /// ], - /// "operator": "in", - /// "type": "evmAddress" - /// } - /// ], - /// "operation": "signEvmTransaction" - /// }, - /// { - /// "action": "accept", - /// "criteria": [ - /// { - /// "addresses": [ - /// "HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT" - /// ], - /// "operator": "in", - /// "type": "solAddress" - /// } - /// ], - /// "operation": "signSolTransaction" - /// } - /// ] - /// ], - /// "type": "array", - /// "items": { - /// "$ref": "#/components/schemas/Rule" - /// } + /// "pattern": "^[0-9]{4}$" /// }, - /// "scope": { - /// "description": "The scope of the policy. Only one project-level policy can exist at any time.", + /// "bankName": { + /// "description": "The name of the bank that originated the deposit.", /// "examples": [ - /// "project" + /// "Citibank, N.A." /// ], - /// "type": "string", - /// "enum": [ - /// "project", - /// "account" - /// ] + /// "type": "string" /// }, - /// "updatedAt": { - /// "description": "The ISO 8601 timestamp at which the Policy was last updated.", + /// "currency": { + /// "description": "The fiat currency of the deposit (e.g., `usd`).", /// "examples": [ - /// "2025-03-26T12:00:00Z" + /// "usd" /// ], /// "type": "string" /// } @@ -27725,89 +31416,80 @@ pub mod types { /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct Policy { - ///The ISO 8601 timestamp at which the Policy was created. - #[serde(rename = "createdAt")] - pub created_at: ::std::string::String, - /**An optional human-readable description of the policy. - Policy descriptions can consist of alphanumeric characters, spaces, commas, and periods, and be 50 characters or less.*/ - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub description: ::std::option::Option, - ///The unique identifier for the policy. - pub id: PolicyId, - ///A list of rules that comprise the policy. - pub rules: ::std::vec::Vec, - ///The scope of the policy. Only one project-level policy can exist at any time. - pub scope: PolicyScope, - ///The ISO 8601 timestamp at which the Policy was last updated. - #[serde(rename = "updatedAt")] - pub updated_at: ::std::string::String, + pub struct OriginatingBankAccountUs { + ///The last 4 digits of the originating bank account number. + #[serde(rename = "accountLast4")] + pub account_last4: OriginatingBankAccountUsAccountLast4, + ///The name of the bank that originated the deposit. + #[serde(rename = "bankName")] + pub bank_name: ::std::string::String, + ///The fiat currency of the deposit (e.g., `usd`). + pub currency: ::std::string::String, } - impl ::std::convert::From<&Policy> for Policy { - fn from(value: &Policy) -> Self { + impl ::std::convert::From<&OriginatingBankAccountUs> for OriginatingBankAccountUs { + fn from(value: &OriginatingBankAccountUs) -> Self { value.clone() } } - impl Policy { - pub fn builder() -> builder::Policy { + impl OriginatingBankAccountUs { + pub fn builder() -> builder::OriginatingBankAccountUs { Default::default() } } - /**An optional human-readable description of the policy. - Policy descriptions can consist of alphanumeric characters, spaces, commas, and periods, and be 50 characters or less.*/ + ///The last 4 digits of the originating bank account number. /// ///
JSON schema /// /// ```json ///{ - /// "description": "An optional human-readable description of the policy.\nPolicy descriptions can consist of alphanumeric characters, spaces, commas, and periods, and be 50 characters or less.", + /// "description": "The last 4 digits of the originating bank account number.", /// "examples": [ - /// "Default policy" + /// "6789" /// ], /// "type": "string", - /// "pattern": "^[A-Za-z0-9 ,.]{1,50}$" + /// "pattern": "^[0-9]{4}$" ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct PolicyDescription(::std::string::String); - impl ::std::ops::Deref for PolicyDescription { + pub struct OriginatingBankAccountUsAccountLast4(::std::string::String); + impl ::std::ops::Deref for OriginatingBankAccountUsAccountLast4 { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: PolicyDescription) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: OriginatingBankAccountUsAccountLast4) -> Self { value.0 } } - impl ::std::convert::From<&PolicyDescription> for PolicyDescription { - fn from(value: &PolicyDescription) -> Self { + impl ::std::convert::From<&OriginatingBankAccountUsAccountLast4> + for OriginatingBankAccountUsAccountLast4 + { + fn from(value: &OriginatingBankAccountUsAccountLast4) -> Self { value.clone() } } - impl ::std::str::FromStr for PolicyDescription { + impl ::std::str::FromStr for OriginatingBankAccountUsAccountLast4 { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^[A-Za-z0-9 ,.]{1,50}$").unwrap() - }); + ::std::sync::LazyLock::new(|| ::regress::Regex::new("^[0-9]{4}$").unwrap()); if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^[A-Za-z0-9 ,.]{1,50}$\"".into()); + return Err("doesn't match pattern \"^[0-9]{4}$\"".into()); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for PolicyDescription { + impl ::std::convert::TryFrom<&str> for OriginatingBankAccountUsAccountLast4 { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for PolicyDescription { + impl ::std::convert::TryFrom<&::std::string::String> for OriginatingBankAccountUsAccountLast4 { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -27815,7 +31497,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for PolicyDescription { + impl ::std::convert::TryFrom<::std::string::String> for OriginatingBankAccountUsAccountLast4 { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -27823,7 +31505,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for PolicyDescription { + impl<'de> ::serde::Deserialize<'de> for OriginatingBankAccountUsAccountLast4 { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -27835,67 +31517,70 @@ pub mod types { }) } } - ///The unique identifier for the policy. + /**The Owner ID of the Account. + Owner IDs are UUIDs prefixed with the Owner Type as follows: + * **Entity**: `entity_` - If the Owner is your Entity, e.g. `entity_af2937b0-9846-4fe7-bfe9-ccc22d935114`. + Support for Customer-owned accounts (`customer_` prefix) is in development.*/ /// ///
JSON schema /// /// ```json ///{ - /// "description": "The unique identifier for the policy.", + /// "description": "The Owner ID of the Account.\nOwner IDs are UUIDs prefixed with the Owner Type as follows:\n* **Entity**: `entity_` - If the Owner is your Entity, e.g. `entity_af2937b0-9846-4fe7-bfe9-ccc22d935114`.\nSupport for Customer-owned accounts (`customer_` prefix) is in development.", /// "examples": [ - /// "123e4567-e89b-12d3-a456-426614174000" + /// "entity_af2937b0-9846-4fe7-bfe9-ccc22d935114" /// ], /// "type": "string", - /// "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" + /// "pattern": "^(entity|customer)_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct PolicyId(::std::string::String); - impl ::std::ops::Deref for PolicyId { + pub struct Owner(::std::string::String); + impl ::std::ops::Deref for Owner { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: PolicyId) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: Owner) -> Self { value.0 } } - impl ::std::convert::From<&PolicyId> for PolicyId { - fn from(value: &PolicyId) -> Self { + impl ::std::convert::From<&Owner> for Owner { + fn from(value: &Owner) -> Self { value.clone() } } - impl ::std::str::FromStr for PolicyId { + impl ::std::str::FromStr for Owner { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new( || { ::regress::Regex::new( - "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", + "^(entity|customer)_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", ) .unwrap() }, ); if PATTERN.find(value).is_none() { return Err( - "doesn't match pattern \"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$\"" + "doesn't match pattern \"^(entity|customer)_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$\"" .into(), ); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for PolicyId { + impl ::std::convert::TryFrom<&str> for Owner { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for PolicyId { + impl ::std::convert::TryFrom<&::std::string::String> for Owner { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -27903,7 +31588,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for PolicyId { + impl ::std::convert::TryFrom<::std::string::String> for Owner { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -27911,7 +31596,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for PolicyId { + impl<'de> ::serde::Deserialize<'de> for Owner { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -27923,139 +31608,176 @@ pub mod types { }) } } - ///The scope of the policy. Only one project-level policy can exist at any time. + ///The Payment Method specific details for the transfer. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The scope of the policy. Only one project-level policy can exist at any time.", + /// "title": "Payment Method", + /// "description": "The Payment Method specific details for the transfer.", /// "examples": [ - /// "project" + /// { + /// "asset": "usd", + /// "paymentMethodId": "pm_af2937b0-9846-4fe7-bfe9-ccc22d935114" + /// } /// ], - /// "type": "string", - /// "enum": [ - /// "project", - /// "account" - /// ] + /// "type": "object", + /// "required": [ + /// "asset", + /// "paymentMethodId" + /// ], + /// "properties": { + /// "asset": { + /// "$ref": "#/components/schemas/Asset" + /// }, + /// "paymentMethodId": { + /// "description": "The ID of the Payment Method.", + /// "type": "string" + /// } + /// } ///} /// ``` ///
- #[derive( - ::serde::Deserialize, - ::serde::Serialize, - Clone, - Copy, - Debug, - Eq, - Hash, - Ord, - PartialEq, - PartialOrd, - )] - pub enum PolicyScope { - #[serde(rename = "project")] - Project, - #[serde(rename = "account")] - Account, + #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct PaymentMethod { + pub asset: Asset, + ///The ID of the Payment Method. + #[serde(rename = "paymentMethodId")] + pub payment_method_id: ::std::string::String, } - impl ::std::convert::From<&Self> for PolicyScope { - fn from(value: &PolicyScope) -> Self { + impl ::std::convert::From<&PaymentMethod> for PaymentMethod { + fn from(value: &PaymentMethod) -> Self { value.clone() } } - impl ::std::fmt::Display for PolicyScope { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - match *self { - Self::Project => f.write_str("project"), - Self::Account => f.write_str("account"), - } - } - } - impl ::std::str::FromStr for PolicyScope { - type Err = self::error::ConversionError; - fn from_str(value: &str) -> ::std::result::Result { - match value { - "project" => Ok(Self::Project), - "account" => Ok(Self::Account), - _ => Err("invalid value".into()), - } + impl PaymentMethod { + pub fn builder() -> builder::PaymentMethod { + Default::default() } } - impl ::std::convert::TryFrom<&str> for PolicyScope { - type Error = self::error::ConversionError; - fn try_from(value: &str) -> ::std::result::Result { - value.parse() - } + ///Common properties shared by all payment method types. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "Common properties shared by all payment method types.", + /// "type": "object", + /// "required": [ + /// "active", + /// "createdAt", + /// "paymentMethodId", + /// "updatedAt" + /// ], + /// "properties": { + /// "active": { + /// "description": "Whether the payment method is active and can be used in transfers. A payment method may be inactive due to verification requirements or entity-level restrictions.", + /// "examples": [ + /// true + /// ], + /// "type": "boolean" + /// }, + /// "createdAt": { + /// "description": "The timestamp when the payment method was created.", + /// "examples": [ + /// "2024-01-15T10:30:00Z" + /// ], + /// "type": "string", + /// "format": "date-time" + /// }, + /// "paymentMethodId": { + /// "$ref": "#/components/schemas/PaymentMethodId" + /// }, + /// "updatedAt": { + /// "description": "The timestamp when the payment method was last updated.", + /// "examples": [ + /// "2024-01-15T10:30:00Z" + /// ], + /// "type": "string", + /// "format": "date-time" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct PaymentMethodBase { + ///Whether the payment method is active and can be used in transfers. A payment method may be inactive due to verification requirements or entity-level restrictions. + pub active: bool, + ///The timestamp when the payment method was created. + #[serde(rename = "createdAt")] + pub created_at: ::chrono::DateTime<::chrono::offset::Utc>, + #[serde(rename = "paymentMethodId")] + pub payment_method_id: PaymentMethodId, + ///The timestamp when the payment method was last updated. + #[serde(rename = "updatedAt")] + pub updated_at: ::chrono::DateTime<::chrono::offset::Utc>, } - impl ::std::convert::TryFrom<&::std::string::String> for PolicyScope { - type Error = self::error::ConversionError; - fn try_from( - value: &::std::string::String, - ) -> ::std::result::Result { - value.parse() + impl ::std::convert::From<&PaymentMethodBase> for PaymentMethodBase { + fn from(value: &PaymentMethodBase) -> Self { + value.clone() } } - impl ::std::convert::TryFrom<::std::string::String> for PolicyScope { - type Error = self::error::ConversionError; - fn try_from( - value: ::std::string::String, - ) -> ::std::result::Result { - value.parse() + impl PaymentMethodBase { + pub fn builder() -> builder::PaymentMethodBase { + Default::default() } } - ///`PrepareAndSendUserOperationAddress` + ///The ID of the Payment Method, which is a UUID prefixed by the string `paymentMethod_`. /// ///
JSON schema /// /// ```json ///{ + /// "description": "The ID of the Payment Method, which is a UUID prefixed by the string `paymentMethod_`.", + /// "examples": [ + /// "paymentMethod_8e03978e-40d5-43e8-bc93-6894a57f9324" + /// ], /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// "pattern": "^paymentMethod_[a-f0-9\\-]{36}$" ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct PrepareAndSendUserOperationAddress(::std::string::String); - impl ::std::ops::Deref for PrepareAndSendUserOperationAddress { + pub struct PaymentMethodId(::std::string::String); + impl ::std::ops::Deref for PaymentMethodId { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: PrepareAndSendUserOperationAddress) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: PaymentMethodId) -> Self { value.0 } } - impl ::std::convert::From<&PrepareAndSendUserOperationAddress> - for PrepareAndSendUserOperationAddress - { - fn from(value: &PrepareAndSendUserOperationAddress) -> Self { + impl ::std::convert::From<&PaymentMethodId> for PaymentMethodId { + fn from(value: &PaymentMethodId) -> Self { value.clone() } } - impl ::std::str::FromStr for PrepareAndSendUserOperationAddress { + impl ::std::str::FromStr for PaymentMethodId { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() + ::regress::Regex::new("^paymentMethod_[a-f0-9\\-]{36}$").unwrap() }); if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); + return Err("doesn't match pattern \"^paymentMethod_[a-f0-9\\-]{36}$\"".into()); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for PrepareAndSendUserOperationAddress { + impl ::std::convert::TryFrom<&str> for PaymentMethodId { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for PrepareAndSendUserOperationAddress { + impl ::std::convert::TryFrom<&::std::string::String> for PaymentMethodId { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -28063,7 +31785,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for PrepareAndSendUserOperationAddress { + impl ::std::convert::TryFrom<::std::string::String> for PaymentMethodId { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -28071,7 +31793,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for PrepareAndSendUserOperationAddress { + impl<'de> ::serde::Deserialize<'de> for PaymentMethodId { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -28083,197 +31805,218 @@ pub mod types { }) } } - ///`PrepareAndSendUserOperationBody` + /**A payment method linked to your entity. Payment methods represent external financial instruments that can be used as a target for transfers. + + The `paymentRail` field indicates which type-specific details object is present. Type-specific fields are nested under a key matching the rail name (e.g., `fedwire`, `swift`).*/ /// ///
JSON schema /// /// ```json ///{ - /// "type": "object", - /// "required": [ - /// "calls", - /// "network" - /// ], - /// "properties": { - /// "calls": { - /// "description": "The list of calls to make from the Smart Account.", - /// "type": "array", - /// "items": { - /// "$ref": "#/components/schemas/EvmCall" - /// } + /// "description": "A payment method linked to your entity. Payment methods represent external financial instruments that can be used as a target for transfers.\n\nThe `paymentRail` field indicates which type-specific details object is present. Type-specific fields are nested under a key matching the rail name (e.g., `fedwire`, `swift`).", + /// "oneOf": [ + /// { + /// "$ref": "#/components/schemas/FedwirePaymentMethod" /// }, - /// "network": { - /// "$ref": "#/components/schemas/EvmUserOperationNetwork" + /// { + /// "$ref": "#/components/schemas/SwiftPaymentMethod" /// }, - /// "paymasterUrl": { - /// "description": "The URL of the paymaster to use for the user operation.", - /// "examples": [ - /// "https://api.developer.coinbase.com/rpc/v1/base/" - /// ], - /// "allOf": [ - /// { - /// "$ref": "#/components/schemas/Url" - /// } - /// ] + /// { + /// "$ref": "#/components/schemas/SepaPaymentMethod" /// } - /// } + /// ] ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct PrepareAndSendUserOperationBody { - ///The list of calls to make from the Smart Account. - pub calls: ::std::vec::Vec, - pub network: EvmUserOperationNetwork, - ///The URL of the paymaster to use for the user operation. - #[serde( - rename = "paymasterUrl", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub paymaster_url: ::std::option::Option, + #[serde(untagged)] + pub enum PaymentMethodsPaymentMethod { + FedwirePaymentMethod(FedwirePaymentMethod), + SwiftPaymentMethod(SwiftPaymentMethod), + SepaPaymentMethod(SepaPaymentMethod), } - impl ::std::convert::From<&PrepareAndSendUserOperationBody> for PrepareAndSendUserOperationBody { - fn from(value: &PrepareAndSendUserOperationBody) -> Self { + impl ::std::convert::From<&Self> for PaymentMethodsPaymentMethod { + fn from(value: &PaymentMethodsPaymentMethod) -> Self { value.clone() } } - impl PrepareAndSendUserOperationBody { - pub fn builder() -> builder::PrepareAndSendUserOperationBody { - Default::default() + impl ::std::convert::From for PaymentMethodsPaymentMethod { + fn from(value: FedwirePaymentMethod) -> Self { + Self::FedwirePaymentMethod(value) } } - ///`PrepareAndSendUserOperationXIdempotencyKey` + impl ::std::convert::From for PaymentMethodsPaymentMethod { + fn from(value: SwiftPaymentMethod) -> Self { + Self::SwiftPaymentMethod(value) + } + } + impl ::std::convert::From for PaymentMethodsPaymentMethod { + fn from(value: SepaPaymentMethod) -> Self { + Self::SepaPaymentMethod(value) + } + } + ///A physical address with standard address components including street, city, state/province, postal code, and country. /// ///
JSON schema /// /// ```json ///{ - /// "type": "string", - /// "maxLength": 128, - /// "minLength": 1 - ///} - /// ``` - ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct PrepareAndSendUserOperationXIdempotencyKey(::std::string::String); - impl ::std::ops::Deref for PrepareAndSendUserOperationXIdempotencyKey { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } - } - impl ::std::convert::From for ::std::string::String { - fn from(value: PrepareAndSendUserOperationXIdempotencyKey) -> Self { - value.0 - } + /// "description": "A physical address with standard address components including street, city, state/province, postal code, and country.", + /// "type": "object", + /// "properties": { + /// "city": { + /// "description": "City or locality.", + /// "examples": [ + /// "San Francisco" + /// ], + /// "type": "string" + /// }, + /// "countryCode": { + /// "description": "ISO 3166-1 alpha-2 country code (2 characters). See https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes.", + /// "examples": [ + /// "US" + /// ], + /// "type": "string", + /// "maxLength": 2, + /// "minLength": 2 + /// }, + /// "line1": { + /// "description": "Primary street address.", + /// "examples": [ + /// "123 Market St" + /// ], + /// "type": "string" + /// }, + /// "line2": { + /// "description": "Secondary address information.", + /// "examples": [ + /// "Suite 400" + /// ], + /// "type": "string" + /// }, + /// "postCode": { + /// "description": "Postal or ZIP code.", + /// "examples": [ + /// "94105" + /// ], + /// "type": "string" + /// }, + /// "state": { + /// "description": "State, province, or region.", + /// "examples": [ + /// "CA" + /// ], + /// "type": "string" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct PhysicalAddress { + ///City or locality. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub city: ::std::option::Option<::std::string::String>, + ///ISO 3166-1 alpha-2 country code (2 characters). See https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes. + #[serde( + rename = "countryCode", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub country_code: ::std::option::Option, + ///Primary street address. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub line1: ::std::option::Option<::std::string::String>, + ///Secondary address information. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub line2: ::std::option::Option<::std::string::String>, + ///Postal or ZIP code. + #[serde( + rename = "postCode", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub post_code: ::std::option::Option<::std::string::String>, + ///State, province, or region. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub state: ::std::option::Option<::std::string::String>, } - impl ::std::convert::From<&PrepareAndSendUserOperationXIdempotencyKey> - for PrepareAndSendUserOperationXIdempotencyKey - { - fn from(value: &PrepareAndSendUserOperationXIdempotencyKey) -> Self { + impl ::std::convert::From<&PhysicalAddress> for PhysicalAddress { + fn from(value: &PhysicalAddress) -> Self { value.clone() } } - impl ::std::str::FromStr for PrepareAndSendUserOperationXIdempotencyKey { - type Err = self::error::ConversionError; - fn from_str(value: &str) -> ::std::result::Result { - if value.chars().count() > 128usize { - return Err("longer than 128 characters".into()); - } - if value.chars().count() < 1usize { - return Err("shorter than 1 characters".into()); + impl ::std::default::Default for PhysicalAddress { + fn default() -> Self { + Self { + city: Default::default(), + country_code: Default::default(), + line1: Default::default(), + line2: Default::default(), + post_code: Default::default(), + state: Default::default(), } - Ok(Self(value.to_string())) - } - } - impl ::std::convert::TryFrom<&str> for PrepareAndSendUserOperationXIdempotencyKey { - type Error = self::error::ConversionError; - fn try_from(value: &str) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<&::std::string::String> - for PrepareAndSendUserOperationXIdempotencyKey - { - type Error = self::error::ConversionError; - fn try_from( - value: &::std::string::String, - ) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<::std::string::String> for PrepareAndSendUserOperationXIdempotencyKey { - type Error = self::error::ConversionError; - fn try_from( - value: ::std::string::String, - ) -> ::std::result::Result { - value.parse() } } - impl<'de> ::serde::Deserialize<'de> for PrepareAndSendUserOperationXIdempotencyKey { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) + impl PhysicalAddress { + pub fn builder() -> builder::PhysicalAddress { + Default::default() } } - ///`PrepareUserOperationAddress` + ///ISO 3166-1 alpha-2 country code (2 characters). See https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes. /// ///
JSON schema /// /// ```json ///{ + /// "description": "ISO 3166-1 alpha-2 country code (2 characters). See https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes.", + /// "examples": [ + /// "US" + /// ], /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// "maxLength": 2, + /// "minLength": 2 ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct PrepareUserOperationAddress(::std::string::String); - impl ::std::ops::Deref for PrepareUserOperationAddress { + pub struct PhysicalAddressCountryCode(::std::string::String); + impl ::std::ops::Deref for PhysicalAddressCountryCode { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: PrepareUserOperationAddress) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: PhysicalAddressCountryCode) -> Self { value.0 } } - impl ::std::convert::From<&PrepareUserOperationAddress> for PrepareUserOperationAddress { - fn from(value: &PrepareUserOperationAddress) -> Self { + impl ::std::convert::From<&PhysicalAddressCountryCode> for PhysicalAddressCountryCode { + fn from(value: &PhysicalAddressCountryCode) -> Self { value.clone() } } - impl ::std::str::FromStr for PrepareUserOperationAddress { + impl ::std::str::FromStr for PhysicalAddressCountryCode { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() - }); - if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); + if value.chars().count() > 2usize { + return Err("longer than 2 characters".into()); + } + if value.chars().count() < 2usize { + return Err("shorter than 2 characters".into()); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for PrepareUserOperationAddress { + impl ::std::convert::TryFrom<&str> for PhysicalAddressCountryCode { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for PrepareUserOperationAddress { + impl ::std::convert::TryFrom<&::std::string::String> for PhysicalAddressCountryCode { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -28281,7 +32024,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for PrepareUserOperationAddress { + impl ::std::convert::TryFrom<::std::string::String> for PhysicalAddressCountryCode { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -28289,7 +32032,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for PrepareUserOperationAddress { + impl<'de> ::serde::Deserialize<'de> for PhysicalAddressCountryCode { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -28301,7 +32044,7 @@ pub mod types { }) } } - ///`PrepareUserOperationBody` + ///`Policy` /// ///
JSON schema /// @@ -28309,127 +32052,185 @@ pub mod types { ///{ /// "type": "object", /// "required": [ - /// "calls", - /// "network" + /// "createdAt", + /// "id", + /// "rules", + /// "scope", + /// "updatedAt" /// ], /// "properties": { - /// "calls": { - /// "description": "The list of calls to make from the Smart Account.", + /// "createdAt": { + /// "description": "The ISO 8601 timestamp at which the Policy was created.", + /// "examples": [ + /// "2025-03-25T12:00:00Z" + /// ], + /// "type": "string" + /// }, + /// "description": { + /// "description": "An optional human-readable description of the policy.\nPolicy descriptions can consist of alphanumeric characters, spaces, commas, and periods, and be 50 characters or less.", + /// "examples": [ + /// "Default policy" + /// ], + /// "type": "string", + /// "pattern": "^[A-Za-z0-9 ,.]{1,50}$" + /// }, + /// "id": { + /// "description": "The unique identifier for the policy.", + /// "examples": [ + /// "123e4567-e89b-12d3-a456-426614174000" + /// ], + /// "type": "string", + /// "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" + /// }, + /// "rules": { + /// "description": "A list of rules that comprise the policy.", + /// "examples": [ + /// [ + /// { + /// "action": "accept", + /// "criteria": [ + /// { + /// "ethValue": "1000000000000000000", + /// "operator": "<=", + /// "type": "ethValue" + /// }, + /// { + /// "addresses": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "0x1234567890123456789012345678901234567890" + /// ], + /// "operator": "in", + /// "type": "evmAddress" + /// } + /// ], + /// "operation": "signEvmTransaction" + /// }, + /// { + /// "action": "accept", + /// "criteria": [ + /// { + /// "addresses": [ + /// "HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT" + /// ], + /// "operator": "in", + /// "type": "solAddress" + /// } + /// ], + /// "operation": "signSolTransaction" + /// } + /// ] + /// ], /// "type": "array", /// "items": { - /// "$ref": "#/components/schemas/EvmCall" + /// "$ref": "#/components/schemas/Rule" /// } /// }, - /// "dataSuffix": { - /// "description": "The EIP-8021 data suffix (hex-encoded) that enables transaction attribution for the user operation.", + /// "scope": { + /// "description": "The scope of the policy. Only one project-level policy can exist at any time.", /// "examples": [ - /// "0xdddddddd62617365617070070080218021802180218021802180218021" + /// "project" /// ], /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]+$" - /// }, - /// "network": { - /// "$ref": "#/components/schemas/EvmUserOperationNetwork" + /// "enum": [ + /// "project", + /// "account" + /// ] /// }, - /// "paymasterUrl": { - /// "description": "The URL of the paymaster to use for the user operation.", + /// "updatedAt": { + /// "description": "The ISO 8601 timestamp at which the Policy was last updated.", /// "examples": [ - /// "https://api.developer.coinbase.com/rpc/v1/base/" + /// "2025-03-26T12:00:00Z" /// ], - /// "allOf": [ - /// { - /// "$ref": "#/components/schemas/Url" - /// } - /// ] + /// "type": "string" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct PrepareUserOperationBody { - ///The list of calls to make from the Smart Account. - pub calls: ::std::vec::Vec, - ///The EIP-8021 data suffix (hex-encoded) that enables transaction attribution for the user operation. - #[serde( - rename = "dataSuffix", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub data_suffix: ::std::option::Option, - pub network: EvmUserOperationNetwork, - ///The URL of the paymaster to use for the user operation. - #[serde( - rename = "paymasterUrl", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub paymaster_url: ::std::option::Option, + pub struct Policy { + ///The ISO 8601 timestamp at which the Policy was created. + #[serde(rename = "createdAt")] + pub created_at: ::std::string::String, + /**An optional human-readable description of the policy. + Policy descriptions can consist of alphanumeric characters, spaces, commas, and periods, and be 50 characters or less.*/ + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub description: ::std::option::Option, + ///The unique identifier for the policy. + pub id: PolicyId, + ///A list of rules that comprise the policy. + pub rules: ::std::vec::Vec, + ///The scope of the policy. Only one project-level policy can exist at any time. + pub scope: PolicyScope, + ///The ISO 8601 timestamp at which the Policy was last updated. + #[serde(rename = "updatedAt")] + pub updated_at: ::std::string::String, } - impl ::std::convert::From<&PrepareUserOperationBody> for PrepareUserOperationBody { - fn from(value: &PrepareUserOperationBody) -> Self { + impl ::std::convert::From<&Policy> for Policy { + fn from(value: &Policy) -> Self { value.clone() } } - impl PrepareUserOperationBody { - pub fn builder() -> builder::PrepareUserOperationBody { + impl Policy { + pub fn builder() -> builder::Policy { Default::default() } } - ///The EIP-8021 data suffix (hex-encoded) that enables transaction attribution for the user operation. + /**An optional human-readable description of the policy. + Policy descriptions can consist of alphanumeric characters, spaces, commas, and periods, and be 50 characters or less.*/ /// ///
JSON schema /// /// ```json ///{ - /// "description": "The EIP-8021 data suffix (hex-encoded) that enables transaction attribution for the user operation.", + /// "description": "An optional human-readable description of the policy.\nPolicy descriptions can consist of alphanumeric characters, spaces, commas, and periods, and be 50 characters or less.", /// "examples": [ - /// "0xdddddddd62617365617070070080218021802180218021802180218021" + /// "Default policy" /// ], /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]+$" + /// "pattern": "^[A-Za-z0-9 ,.]{1,50}$" ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct PrepareUserOperationBodyDataSuffix(::std::string::String); - impl ::std::ops::Deref for PrepareUserOperationBodyDataSuffix { + pub struct PolicyDescription(::std::string::String); + impl ::std::ops::Deref for PolicyDescription { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: PrepareUserOperationBodyDataSuffix) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: PolicyDescription) -> Self { value.0 } } - impl ::std::convert::From<&PrepareUserOperationBodyDataSuffix> - for PrepareUserOperationBodyDataSuffix - { - fn from(value: &PrepareUserOperationBodyDataSuffix) -> Self { + impl ::std::convert::From<&PolicyDescription> for PolicyDescription { + fn from(value: &PolicyDescription) -> Self { value.clone() } } - impl ::std::str::FromStr for PrepareUserOperationBodyDataSuffix { + impl ::std::str::FromStr for PolicyDescription { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| ::regress::Regex::new("^0x[0-9a-fA-F]+$").unwrap()); + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^[A-Za-z0-9 ,.]{1,50}$").unwrap() + }); if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]+$\"".into()); + return Err("doesn't match pattern \"^[A-Za-z0-9 ,.]{1,50}$\"".into()); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for PrepareUserOperationBodyDataSuffix { + impl ::std::convert::TryFrom<&str> for PolicyDescription { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for PrepareUserOperationBodyDataSuffix { + impl ::std::convert::TryFrom<&::std::string::String> for PolicyDescription { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -28437,7 +32238,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for PrepareUserOperationBodyDataSuffix { + impl ::std::convert::TryFrom<::std::string::String> for PolicyDescription { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -28445,7 +32246,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for PrepareUserOperationBodyDataSuffix { + impl<'de> ::serde::Deserialize<'de> for PolicyDescription { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -28457,272 +32258,160 @@ pub mod types { }) } } - ///A schema for specifying criteria for the PrepareUserOperation operation. + ///The unique identifier for the policy. /// ///
JSON schema /// /// ```json ///{ - /// "description": "A schema for specifying criteria for the PrepareUserOperation operation.", + /// "description": "The unique identifier for the policy.", /// "examples": [ - /// [ - /// { - /// "ethValue": "1000000", - /// "operator": ">=", - /// "type": "ethValue" - /// }, - /// { - /// "addresses": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" - /// ], - /// "operator": "in", - /// "type": "evmAddress" - /// } - /// ] + /// "123e4567-e89b-12d3-a456-426614174000" /// ], - /// "type": "array", - /// "items": { - /// "oneOf": [ - /// { - /// "$ref": "#/components/schemas/EthValueCriterion" - /// }, - /// { - /// "$ref": "#/components/schemas/EvmAddressCriterion" - /// }, - /// { - /// "$ref": "#/components/schemas/EvmNetworkCriterion" - /// }, - /// { - /// "$ref": "#/components/schemas/EvmDataCriterion" - /// }, - /// { - /// "$ref": "#/components/schemas/NetUSDChangeCriterion" - /// } - /// ] - /// }, - /// "x-audience": "public" + /// "type": "string", + /// "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" ///} /// ``` ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct PrepareUserOperationCriteria(pub ::std::vec::Vec); - impl ::std::ops::Deref for PrepareUserOperationCriteria { - type Target = ::std::vec::Vec; - fn deref(&self) -> &::std::vec::Vec { + pub struct PolicyId(::std::string::String); + impl ::std::ops::Deref for PolicyId { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From - for ::std::vec::Vec - { - fn from(value: PrepareUserOperationCriteria) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: PolicyId) -> Self { value.0 } } - impl ::std::convert::From<&PrepareUserOperationCriteria> for PrepareUserOperationCriteria { - fn from(value: &PrepareUserOperationCriteria) -> Self { + impl ::std::convert::From<&PolicyId> for PolicyId { + fn from(value: &PolicyId) -> Self { value.clone() } } - impl ::std::convert::From<::std::vec::Vec> - for PrepareUserOperationCriteria - { - fn from(value: ::std::vec::Vec) -> Self { - Self(value) + impl ::std::str::FromStr for PolicyId { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new( + || { + ::regress::Regex::new( + "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", + ) + .unwrap() + }, + ); + if PATTERN.find(value).is_none() { + return Err( + "doesn't match pattern \"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$\"" + .into(), + ); + } + Ok(Self(value.to_string())) } } - ///`PrepareUserOperationCriteriaItem` + impl ::std::convert::TryFrom<&str> for PolicyId { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for PolicyId { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for PolicyId { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for PolicyId { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///The scope of the policy. Only one project-level policy can exist at any time. /// ///
JSON schema /// /// ```json ///{ - /// "oneOf": [ - /// { - /// "$ref": "#/components/schemas/EthValueCriterion" - /// }, - /// { - /// "$ref": "#/components/schemas/EvmAddressCriterion" - /// }, - /// { - /// "$ref": "#/components/schemas/EvmNetworkCriterion" - /// }, - /// { - /// "$ref": "#/components/schemas/EvmDataCriterion" - /// }, - /// { - /// "$ref": "#/components/schemas/NetUSDChangeCriterion" - /// } + /// "description": "The scope of the policy. Only one project-level policy can exist at any time.", + /// "examples": [ + /// "project" + /// ], + /// "type": "string", + /// "enum": [ + /// "project", + /// "account" /// ] ///} /// ``` ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - #[serde(untagged)] - pub enum PrepareUserOperationCriteriaItem { - EthValueCriterion(EthValueCriterion), - EvmAddressCriterion(EvmAddressCriterion), - EvmNetworkCriterion(EvmNetworkCriterion), - EvmDataCriterion(EvmDataCriterion), - NetUsdChangeCriterion(NetUsdChangeCriterion), + #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum PolicyScope { + #[serde(rename = "project")] + Project, + #[serde(rename = "account")] + Account, } - impl ::std::convert::From<&Self> for PrepareUserOperationCriteriaItem { - fn from(value: &PrepareUserOperationCriteriaItem) -> Self { + impl ::std::convert::From<&Self> for PolicyScope { + fn from(value: &PolicyScope) -> Self { value.clone() } } - impl ::std::convert::From for PrepareUserOperationCriteriaItem { - fn from(value: EthValueCriterion) -> Self { - Self::EthValueCriterion(value) + impl ::std::fmt::Display for PolicyScope { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Project => f.write_str("project"), + Self::Account => f.write_str("account"), + } } } - impl ::std::convert::From for PrepareUserOperationCriteriaItem { - fn from(value: EvmAddressCriterion) -> Self { - Self::EvmAddressCriterion(value) + impl ::std::str::FromStr for PolicyScope { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "project" => Ok(Self::Project), + "account" => Ok(Self::Account), + _ => Err("invalid value".into()), + } } } - impl ::std::convert::From for PrepareUserOperationCriteriaItem { - fn from(value: EvmNetworkCriterion) -> Self { - Self::EvmNetworkCriterion(value) + impl ::std::convert::TryFrom<&str> for PolicyScope { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() } } - impl ::std::convert::From for PrepareUserOperationCriteriaItem { - fn from(value: EvmDataCriterion) -> Self { - Self::EvmDataCriterion(value) - } - } - impl ::std::convert::From for PrepareUserOperationCriteriaItem { - fn from(value: NetUsdChangeCriterion) -> Self { - Self::NetUsdChangeCriterion(value) - } - } - ///`PrepareUserOperationRule` - /// - ///
JSON schema - /// - /// ```json - ///{ - /// "title": "PrepareUserOperationRule", - /// "required": [ - /// "action", - /// "criteria", - /// "operation" - /// ], - /// "properties": { - /// "action": { - /// "description": "Whether matching the rule will cause the request to be rejected or accepted.", - /// "examples": [ - /// "accept" - /// ], - /// "type": "string", - /// "enum": [ - /// "reject", - /// "accept" - /// ] - /// }, - /// "criteria": { - /// "$ref": "#/components/schemas/PrepareUserOperationCriteria" - /// }, - /// "operation": { - /// "description": "The operation to which the rule applies. Every element of the `criteria` array must match the specified operation.", - /// "examples": [ - /// "prepareUserOperation" - /// ], - /// "type": "string", - /// "enum": [ - /// "prepareUserOperation" - /// ] - /// } - /// }, - /// "x-audience": "public" - ///} - /// ``` - ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct PrepareUserOperationRule { - ///Whether matching the rule will cause the request to be rejected or accepted. - pub action: PrepareUserOperationRuleAction, - pub criteria: PrepareUserOperationCriteria, - ///The operation to which the rule applies. Every element of the `criteria` array must match the specified operation. - pub operation: PrepareUserOperationRuleOperation, - } - impl ::std::convert::From<&PrepareUserOperationRule> for PrepareUserOperationRule { - fn from(value: &PrepareUserOperationRule) -> Self { - value.clone() - } - } - impl PrepareUserOperationRule { - pub fn builder() -> builder::PrepareUserOperationRule { - Default::default() - } - } - ///Whether matching the rule will cause the request to be rejected or accepted. - /// - ///
JSON schema - /// - /// ```json - ///{ - /// "description": "Whether matching the rule will cause the request to be rejected or accepted.", - /// "examples": [ - /// "accept" - /// ], - /// "type": "string", - /// "enum": [ - /// "reject", - /// "accept" - /// ] - ///} - /// ``` - ///
- #[derive( - ::serde::Deserialize, - ::serde::Serialize, - Clone, - Copy, - Debug, - Eq, - Hash, - Ord, - PartialEq, - PartialOrd, - )] - pub enum PrepareUserOperationRuleAction { - #[serde(rename = "reject")] - Reject, - #[serde(rename = "accept")] - Accept, - } - impl ::std::convert::From<&Self> for PrepareUserOperationRuleAction { - fn from(value: &PrepareUserOperationRuleAction) -> Self { - value.clone() - } - } - impl ::std::fmt::Display for PrepareUserOperationRuleAction { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - match *self { - Self::Reject => f.write_str("reject"), - Self::Accept => f.write_str("accept"), - } - } - } - impl ::std::str::FromStr for PrepareUserOperationRuleAction { - type Err = self::error::ConversionError; - fn from_str(value: &str) -> ::std::result::Result { - match value { - "reject" => Ok(Self::Reject), - "accept" => Ok(Self::Accept), - _ => Err("invalid value".into()), - } - } - } - impl ::std::convert::TryFrom<&str> for PrepareUserOperationRuleAction { - type Error = self::error::ConversionError; - fn try_from(value: &str) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<&::std::string::String> for PrepareUserOperationRuleAction { + impl ::std::convert::TryFrom<&::std::string::String> for PolicyScope { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -28730,7 +32419,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for PrepareUserOperationRuleAction { + impl ::std::convert::TryFrom<::std::string::String> for PolicyScope { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -28738,67 +32427,58 @@ pub mod types { value.parse() } } - ///The operation to which the rule applies. Every element of the `criteria` array must match the specified operation. + ///`PrepareAndSendUserOperationAddress` /// ///
JSON schema /// /// ```json ///{ - /// "description": "The operation to which the rule applies. Every element of the `criteria` array must match the specified operation.", - /// "examples": [ - /// "prepareUserOperation" - /// ], /// "type": "string", - /// "enum": [ - /// "prepareUserOperation" - /// ] + /// "pattern": "^0x[0-9a-fA-F]{40}$" ///} /// ``` ///
- #[derive( - ::serde::Deserialize, - ::serde::Serialize, - Clone, - Copy, - Debug, - Eq, - Hash, - Ord, - PartialEq, - PartialOrd, - )] - pub enum PrepareUserOperationRuleOperation { - #[serde(rename = "prepareUserOperation")] - PrepareUserOperation, + #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct PrepareAndSendUserOperationAddress(::std::string::String); + impl ::std::ops::Deref for PrepareAndSendUserOperationAddress { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } } - impl ::std::convert::From<&Self> for PrepareUserOperationRuleOperation { - fn from(value: &PrepareUserOperationRuleOperation) -> Self { - value.clone() + impl ::std::convert::From for ::std::string::String { + fn from(value: PrepareAndSendUserOperationAddress) -> Self { + value.0 } } - impl ::std::fmt::Display for PrepareUserOperationRuleOperation { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - match *self { - Self::PrepareUserOperation => f.write_str("prepareUserOperation"), - } + impl ::std::convert::From<&PrepareAndSendUserOperationAddress> + for PrepareAndSendUserOperationAddress + { + fn from(value: &PrepareAndSendUserOperationAddress) -> Self { + value.clone() } } - impl ::std::str::FromStr for PrepareUserOperationRuleOperation { + impl ::std::str::FromStr for PrepareAndSendUserOperationAddress { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - match value { - "prepareUserOperation" => Ok(Self::PrepareUserOperation), - _ => Err("invalid value".into()), + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); } + Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for PrepareUserOperationRuleOperation { + impl ::std::convert::TryFrom<&str> for PrepareAndSendUserOperationAddress { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for PrepareUserOperationRuleOperation { + impl ::std::convert::TryFrom<&::std::string::String> for PrepareAndSendUserOperationAddress { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -28806,7 +32486,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for PrepareUserOperationRuleOperation { + impl ::std::convert::TryFrom<::std::string::String> for PrepareAndSendUserOperationAddress { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -28814,149 +32494,132 @@ pub mod types { value.parse() } } - ///The criterion for the program IDs of a Solana transaction's instructions. + impl<'de> ::serde::Deserialize<'de> for PrepareAndSendUserOperationAddress { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///`PrepareAndSendUserOperationBody` /// ///
JSON schema /// /// ```json ///{ - /// "title": "ProgramIdCriterion", - /// "description": "The criterion for the program IDs of a Solana transaction's instructions.", /// "type": "object", /// "required": [ - /// "operator", - /// "programIds", - /// "type" + /// "calls", + /// "network" /// ], /// "properties": { - /// "operator": { - /// "description": "The operator to use for the comparison. Each of the program IDs in the transaction's instructions will be on the left-hand side of the operator, and the `programIds` field will be on the right-hand side.", - /// "examples": [ - /// "in" - /// ], - /// "type": "string", - /// "enum": [ - /// "in", - /// "not in" - /// ] - /// }, - /// "programIds": { - /// "description": "The Solana program IDs that are compared to the list of program IDs in the transaction's instructions.", - /// "examples": [ - /// [ - /// "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", - /// "11111111111111111111111111111112" - /// ] - /// ], + /// "calls": { + /// "description": "The list of calls to make from the Smart Account.", /// "type": "array", /// "items": { - /// "description": "The Solana program ID that is compared to the list of program IDs in the transaction's instructions.", - /// "type": "string", - /// "pattern": "^[1-9A-HJ-NP-Za-km-z]{32,44}$" + /// "$ref": "#/components/schemas/EvmCall" /// } /// }, - /// "type": { - /// "description": "The type of criterion to use. This should be `programId`.", + /// "network": { + /// "$ref": "#/components/schemas/EvmUserOperationNetwork" + /// }, + /// "paymasterUrl": { + /// "description": "The URL of the paymaster to use for the user operation.", /// "examples": [ - /// "programId" + /// "https://api.developer.coinbase.com/rpc/v1/base/" /// ], - /// "type": "string", - /// "enum": [ - /// "programId" + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/Url" + /// } /// ] /// } - /// }, - /// "x-audience": "public" + /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct ProgramIdCriterion { - ///The operator to use for the comparison. Each of the program IDs in the transaction's instructions will be on the left-hand side of the operator, and the `programIds` field will be on the right-hand side. - pub operator: ProgramIdCriterionOperator, - ///The Solana program IDs that are compared to the list of program IDs in the transaction's instructions. - #[serde(rename = "programIds")] - pub program_ids: ::std::vec::Vec, - ///The type of criterion to use. This should be `programId`. - #[serde(rename = "type")] - pub type_: ProgramIdCriterionType, + pub struct PrepareAndSendUserOperationBody { + ///The list of calls to make from the Smart Account. + pub calls: ::std::vec::Vec, + pub network: EvmUserOperationNetwork, + ///The URL of the paymaster to use for the user operation. + #[serde( + rename = "paymasterUrl", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub paymaster_url: ::std::option::Option, } - impl ::std::convert::From<&ProgramIdCriterion> for ProgramIdCriterion { - fn from(value: &ProgramIdCriterion) -> Self { + impl ::std::convert::From<&PrepareAndSendUserOperationBody> for PrepareAndSendUserOperationBody { + fn from(value: &PrepareAndSendUserOperationBody) -> Self { value.clone() } } - impl ProgramIdCriterion { - pub fn builder() -> builder::ProgramIdCriterion { + impl PrepareAndSendUserOperationBody { + pub fn builder() -> builder::PrepareAndSendUserOperationBody { Default::default() } } - ///The operator to use for the comparison. Each of the program IDs in the transaction's instructions will be on the left-hand side of the operator, and the `programIds` field will be on the right-hand side. + ///`PrepareAndSendUserOperationXIdempotencyKey` /// ///
JSON schema /// /// ```json ///{ - /// "description": "The operator to use for the comparison. Each of the program IDs in the transaction's instructions will be on the left-hand side of the operator, and the `programIds` field will be on the right-hand side.", - /// "examples": [ - /// "in" - /// ], /// "type": "string", - /// "enum": [ - /// "in", - /// "not in" - /// ] + /// "maxLength": 128, + /// "minLength": 1 ///} /// ``` ///
- #[derive( - ::serde::Deserialize, - ::serde::Serialize, - Clone, - Copy, - Debug, - Eq, - Hash, - Ord, - PartialEq, - PartialOrd, - )] - pub enum ProgramIdCriterionOperator { - #[serde(rename = "in")] - In, - #[serde(rename = "not in")] - NotIn, + #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct PrepareAndSendUserOperationXIdempotencyKey(::std::string::String); + impl ::std::ops::Deref for PrepareAndSendUserOperationXIdempotencyKey { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } } - impl ::std::convert::From<&Self> for ProgramIdCriterionOperator { - fn from(value: &ProgramIdCriterionOperator) -> Self { - value.clone() + impl ::std::convert::From for ::std::string::String { + fn from(value: PrepareAndSendUserOperationXIdempotencyKey) -> Self { + value.0 } } - impl ::std::fmt::Display for ProgramIdCriterionOperator { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - match *self { - Self::In => f.write_str("in"), - Self::NotIn => f.write_str("not in"), - } + impl ::std::convert::From<&PrepareAndSendUserOperationXIdempotencyKey> + for PrepareAndSendUserOperationXIdempotencyKey + { + fn from(value: &PrepareAndSendUserOperationXIdempotencyKey) -> Self { + value.clone() } } - impl ::std::str::FromStr for ProgramIdCriterionOperator { + impl ::std::str::FromStr for PrepareAndSendUserOperationXIdempotencyKey { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - match value { - "in" => Ok(Self::In), - "not in" => Ok(Self::NotIn), - _ => Err("invalid value".into()), + if value.chars().count() > 128usize { + return Err("longer than 128 characters".into()); + } + if value.chars().count() < 1usize { + return Err("shorter than 1 characters".into()); } + Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for ProgramIdCriterionOperator { + impl ::std::convert::TryFrom<&str> for PrepareAndSendUserOperationXIdempotencyKey { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for ProgramIdCriterionOperator { + impl ::std::convert::TryFrom<&::std::string::String> + for PrepareAndSendUserOperationXIdempotencyKey + { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -28964,7 +32627,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for ProgramIdCriterionOperator { + impl ::std::convert::TryFrom<::std::string::String> for PrepareAndSendUserOperationXIdempotencyKey { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -28972,57 +32635,68 @@ pub mod types { value.parse() } } - ///The Solana program ID that is compared to the list of program IDs in the transaction's instructions. + impl<'de> ::serde::Deserialize<'de> for PrepareAndSendUserOperationXIdempotencyKey { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///`PrepareUserOperationAddress` /// ///
JSON schema /// /// ```json ///{ - /// "description": "The Solana program ID that is compared to the list of program IDs in the transaction's instructions.", /// "type": "string", - /// "pattern": "^[1-9A-HJ-NP-Za-km-z]{32,44}$" + /// "pattern": "^0x[0-9a-fA-F]{40}$" ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct ProgramIdCriterionProgramIdsItem(::std::string::String); - impl ::std::ops::Deref for ProgramIdCriterionProgramIdsItem { + pub struct PrepareUserOperationAddress(::std::string::String); + impl ::std::ops::Deref for PrepareUserOperationAddress { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: ProgramIdCriterionProgramIdsItem) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: PrepareUserOperationAddress) -> Self { value.0 } } - impl ::std::convert::From<&ProgramIdCriterionProgramIdsItem> for ProgramIdCriterionProgramIdsItem { - fn from(value: &ProgramIdCriterionProgramIdsItem) -> Self { + impl ::std::convert::From<&PrepareUserOperationAddress> for PrepareUserOperationAddress { + fn from(value: &PrepareUserOperationAddress) -> Self { value.clone() } } - impl ::std::str::FromStr for ProgramIdCriterionProgramIdsItem { + impl ::std::str::FromStr for PrepareUserOperationAddress { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^[1-9A-HJ-NP-Za-km-z]{32,44}$").unwrap() + ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() }); if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^[1-9A-HJ-NP-Za-km-z]{32,44}$\"".into()); + return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for ProgramIdCriterionProgramIdsItem { + impl ::std::convert::TryFrom<&str> for PrepareUserOperationAddress { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for ProgramIdCriterionProgramIdsItem { + impl ::std::convert::TryFrom<&::std::string::String> for PrepareUserOperationAddress { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -29030,7 +32704,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for ProgramIdCriterionProgramIdsItem { + impl ::std::convert::TryFrom<::std::string::String> for PrepareUserOperationAddress { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -29038,7 +32712,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for ProgramIdCriterionProgramIdsItem { + impl<'de> ::serde::Deserialize<'de> for PrepareUserOperationAddress { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -29050,67 +32724,135 @@ pub mod types { }) } } - ///The type of criterion to use. This should be `programId`. + ///`PrepareUserOperationBody` /// ///
JSON schema /// /// ```json ///{ - /// "description": "The type of criterion to use. This should be `programId`.", - /// "examples": [ - /// "programId" + /// "type": "object", + /// "required": [ + /// "calls", + /// "network" /// ], - /// "type": "string", - /// "enum": [ - /// "programId" - /// ] + /// "properties": { + /// "calls": { + /// "description": "The list of calls to make from the Smart Account.", + /// "type": "array", + /// "items": { + /// "$ref": "#/components/schemas/EvmCall" + /// } + /// }, + /// "dataSuffix": { + /// "description": "The EIP-8021 data suffix (hex-encoded) that enables transaction attribution for the user operation.", + /// "examples": [ + /// "0xdddddddd62617365617070070080218021802180218021802180218021" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]+$" + /// }, + /// "network": { + /// "$ref": "#/components/schemas/EvmUserOperationNetwork" + /// }, + /// "paymasterUrl": { + /// "description": "The URL of the paymaster to use for the user operation.", + /// "examples": [ + /// "https://api.developer.coinbase.com/rpc/v1/base/" + /// ], + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/Url" + /// } + /// ] + /// } + /// } ///} /// ``` ///
- #[derive( - ::serde::Deserialize, - ::serde::Serialize, - Clone, - Copy, - Debug, - Eq, - Hash, - Ord, - PartialEq, - PartialOrd, - )] - pub enum ProgramIdCriterionType { - #[serde(rename = "programId")] - ProgramId, + #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct PrepareUserOperationBody { + ///The list of calls to make from the Smart Account. + pub calls: ::std::vec::Vec, + ///The EIP-8021 data suffix (hex-encoded) that enables transaction attribution for the user operation. + #[serde( + rename = "dataSuffix", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub data_suffix: ::std::option::Option, + pub network: EvmUserOperationNetwork, + ///The URL of the paymaster to use for the user operation. + #[serde( + rename = "paymasterUrl", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub paymaster_url: ::std::option::Option, } - impl ::std::convert::From<&Self> for ProgramIdCriterionType { - fn from(value: &ProgramIdCriterionType) -> Self { + impl ::std::convert::From<&PrepareUserOperationBody> for PrepareUserOperationBody { + fn from(value: &PrepareUserOperationBody) -> Self { value.clone() } } - impl ::std::fmt::Display for ProgramIdCriterionType { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - match *self { - Self::ProgramId => f.write_str("programId"), - } + impl PrepareUserOperationBody { + pub fn builder() -> builder::PrepareUserOperationBody { + Default::default() } } - impl ::std::str::FromStr for ProgramIdCriterionType { - type Err = self::error::ConversionError; - fn from_str(value: &str) -> ::std::result::Result { - match value { - "programId" => Ok(Self::ProgramId), - _ => Err("invalid value".into()), + ///The EIP-8021 data suffix (hex-encoded) that enables transaction attribution for the user operation. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The EIP-8021 data suffix (hex-encoded) that enables transaction attribution for the user operation.", + /// "examples": [ + /// "0xdddddddd62617365617070070080218021802180218021802180218021" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]+$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct PrepareUserOperationBodyDataSuffix(::std::string::String); + impl ::std::ops::Deref for PrepareUserOperationBodyDataSuffix { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: PrepareUserOperationBodyDataSuffix) -> Self { + value.0 + } + } + impl ::std::convert::From<&PrepareUserOperationBodyDataSuffix> + for PrepareUserOperationBodyDataSuffix + { + fn from(value: &PrepareUserOperationBodyDataSuffix) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for PrepareUserOperationBodyDataSuffix { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| ::regress::Regex::new("^0x[0-9a-fA-F]+$").unwrap()); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^0x[0-9a-fA-F]+$\"".into()); } + Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for ProgramIdCriterionType { + impl ::std::convert::TryFrom<&str> for PrepareUserOperationBodyDataSuffix { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for ProgramIdCriterionType { + impl ::std::convert::TryFrom<&::std::string::String> for PrepareUserOperationBodyDataSuffix { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -29118,7 +32860,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for ProgramIdCriterionType { + impl ::std::convert::TryFrom<::std::string::String> for PrepareUserOperationBodyDataSuffix { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -29126,226 +32868,232 @@ pub mod types { value.parse() } } - /**Enables control over how often queries need to be fully re-executed on the backing store. - This can be useful in scenarios where API calls might be made frequently, API latency is critical, and some freshness lag (ex: 750ms, 2s, 5s) is tolerable. - By default, each query result is returned from cache so long as the result is from an identical query and less than 500ms old. This freshness tolerance can be modified upwards, to a maximum of 900000ms (i.e. 900s, 15m). - */ + impl<'de> ::serde::Deserialize<'de> for PrepareUserOperationBodyDataSuffix { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///A schema for specifying criteria for the PrepareUserOperation operation. /// ///
JSON schema /// /// ```json ///{ - /// "title": "Query result cache configuration", - /// "description": "Enables control over how often queries need to be fully re-executed on the backing store.\nThis can be useful in scenarios where API calls might be made frequently, API latency is critical, and some freshness lag (ex: 750ms, 2s, 5s) is tolerable.\nBy default, each query result is returned from cache so long as the result is from an identical query and less than 500ms old. This freshness tolerance can be modified upwards, to a maximum of 900000ms (i.e. 900s, 15m).\n", + /// "description": "A schema for specifying criteria for the PrepareUserOperation operation.", /// "examples": [ - /// { - /// "maxAgeMs": 1000 - /// } + /// [ + /// { + /// "ethValue": "1000000", + /// "operator": ">=", + /// "type": "ethValue" + /// }, + /// { + /// "addresses": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ], + /// "operator": "in", + /// "type": "evmAddress" + /// } + /// ] /// ], - /// "type": "object", - /// "properties": { - /// "maxAgeMs": { - /// "description": "The maximum tolerable staleness of the query result cache in milliseconds. If a previous execution result of an identical query is older than this age, the query will be re-executed. If the data is less than this age, the result will be returned from cache.", - /// "default": 500, - /// "examples": [ - /// 1000 - /// ], - /// "type": "integer", - /// "maximum": 900000.0, - /// "minimum": 500.0 - /// } - /// } + /// "type": "array", + /// "items": { + /// "oneOf": [ + /// { + /// "$ref": "#/components/schemas/EthValueCriterion" + /// }, + /// { + /// "$ref": "#/components/schemas/EvmAddressCriterion" + /// }, + /// { + /// "$ref": "#/components/schemas/EvmNetworkCriterion" + /// }, + /// { + /// "$ref": "#/components/schemas/EvmDataCriterion" + /// }, + /// { + /// "$ref": "#/components/schemas/NetUSDChangeCriterion" + /// } + /// ] + /// }, + /// "x-audience": "public" ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct QueryResultCacheConfiguration { - ///The maximum tolerable staleness of the query result cache in milliseconds. If a previous execution result of an identical query is older than this age, the query will be re-executed. If the data is less than this age, the result will be returned from cache. - #[serde(rename = "maxAgeMs", default = "defaults::default_u64::")] - pub max_age_ms: i64, + #[serde(transparent)] + pub struct PrepareUserOperationCriteria(pub ::std::vec::Vec); + impl ::std::ops::Deref for PrepareUserOperationCriteria { + type Target = ::std::vec::Vec; + fn deref(&self) -> &::std::vec::Vec { + &self.0 + } } - impl ::std::convert::From<&QueryResultCacheConfiguration> for QueryResultCacheConfiguration { - fn from(value: &QueryResultCacheConfiguration) -> Self { - value.clone() + impl ::std::convert::From + for ::std::vec::Vec + { + fn from(value: PrepareUserOperationCriteria) -> Self { + value.0 } } - impl ::std::default::Default for QueryResultCacheConfiguration { - fn default() -> Self { - Self { - max_age_ms: defaults::default_u64::(), - } + impl ::std::convert::From<&PrepareUserOperationCriteria> for PrepareUserOperationCriteria { + fn from(value: &PrepareUserOperationCriteria) -> Self { + value.clone() } } - impl QueryResultCacheConfiguration { - pub fn builder() -> builder::QueryResultCacheConfiguration { - Default::default() + impl ::std::convert::From<::std::vec::Vec> + for PrepareUserOperationCriteria + { + fn from(value: ::std::vec::Vec) -> Self { + Self(value) } } - ///`RequestEvmFaucetBody` + ///`PrepareUserOperationCriteriaItem` /// ///
JSON schema /// /// ```json ///{ - /// "type": "object", - /// "required": [ - /// "address", - /// "network", - /// "token" - /// ], - /// "properties": { - /// "address": { - /// "description": "The address to request funds to, which is a 0x-prefixed hexadecimal string.", - /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// "oneOf": [ + /// { + /// "$ref": "#/components/schemas/EthValueCriterion" /// }, - /// "network": { - /// "description": "The network to request funds from.", - /// "examples": [ - /// "base-sepolia" - /// ], - /// "type": "string", - /// "enum": [ - /// "base-sepolia", - /// "ethereum-sepolia", - /// "ethereum-hoodi" - /// ] + /// { + /// "$ref": "#/components/schemas/EvmAddressCriterion" /// }, - /// "token": { - /// "description": "The token to request funds for.", - /// "examples": [ - /// "eth" - /// ], - /// "type": "string", - /// "enum": [ - /// "eth", - /// "usdc", - /// "eurc", - /// "cbbtc" - /// ] + /// { + /// "$ref": "#/components/schemas/EvmNetworkCriterion" + /// }, + /// { + /// "$ref": "#/components/schemas/EvmDataCriterion" + /// }, + /// { + /// "$ref": "#/components/schemas/NetUSDChangeCriterion" /// } - /// } + /// ] ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct RequestEvmFaucetBody { - ///The address to request funds to, which is a 0x-prefixed hexadecimal string. - pub address: RequestEvmFaucetBodyAddress, - ///The network to request funds from. - pub network: RequestEvmFaucetBodyNetwork, - ///The token to request funds for. - pub token: RequestEvmFaucetBodyToken, + #[serde(untagged)] + pub enum PrepareUserOperationCriteriaItem { + EthValueCriterion(EthValueCriterion), + EvmAddressCriterion(EvmAddressCriterion), + EvmNetworkCriterion(EvmNetworkCriterion), + EvmDataCriterion(EvmDataCriterion), + NetUsdChangeCriterion(NetUsdChangeCriterion), } - impl ::std::convert::From<&RequestEvmFaucetBody> for RequestEvmFaucetBody { - fn from(value: &RequestEvmFaucetBody) -> Self { + impl ::std::convert::From<&Self> for PrepareUserOperationCriteriaItem { + fn from(value: &PrepareUserOperationCriteriaItem) -> Self { value.clone() } } - impl RequestEvmFaucetBody { - pub fn builder() -> builder::RequestEvmFaucetBody { - Default::default() + impl ::std::convert::From for PrepareUserOperationCriteriaItem { + fn from(value: EthValueCriterion) -> Self { + Self::EthValueCriterion(value) } } - ///The address to request funds to, which is a 0x-prefixed hexadecimal string. + impl ::std::convert::From for PrepareUserOperationCriteriaItem { + fn from(value: EvmAddressCriterion) -> Self { + Self::EvmAddressCriterion(value) + } + } + impl ::std::convert::From for PrepareUserOperationCriteriaItem { + fn from(value: EvmNetworkCriterion) -> Self { + Self::EvmNetworkCriterion(value) + } + } + impl ::std::convert::From for PrepareUserOperationCriteriaItem { + fn from(value: EvmDataCriterion) -> Self { + Self::EvmDataCriterion(value) + } + } + impl ::std::convert::From for PrepareUserOperationCriteriaItem { + fn from(value: NetUsdChangeCriterion) -> Self { + Self::NetUsdChangeCriterion(value) + } + } + ///`PrepareUserOperationRule` /// ///
JSON schema /// /// ```json ///{ - /// "description": "The address to request funds to, which is a 0x-prefixed hexadecimal string.", - /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// "title": "PrepareUserOperationRule", + /// "required": [ + /// "action", + /// "criteria", + /// "operation" /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// "properties": { + /// "action": { + /// "description": "Whether matching the rule will cause the request to be rejected or accepted.", + /// "examples": [ + /// "accept" + /// ], + /// "type": "string", + /// "enum": [ + /// "reject", + /// "accept" + /// ] + /// }, + /// "criteria": { + /// "$ref": "#/components/schemas/PrepareUserOperationCriteria" + /// }, + /// "operation": { + /// "description": "The operation to which the rule applies. Every element of the `criteria` array must match the specified operation.", + /// "examples": [ + /// "prepareUserOperation" + /// ], + /// "type": "string", + /// "enum": [ + /// "prepareUserOperation" + /// ] + /// } + /// }, + /// "x-audience": "public" ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct RequestEvmFaucetBodyAddress(::std::string::String); - impl ::std::ops::Deref for RequestEvmFaucetBodyAddress { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } - } - impl ::std::convert::From for ::std::string::String { - fn from(value: RequestEvmFaucetBodyAddress) -> Self { - value.0 - } + #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct PrepareUserOperationRule { + ///Whether matching the rule will cause the request to be rejected or accepted. + pub action: PrepareUserOperationRuleAction, + pub criteria: PrepareUserOperationCriteria, + ///The operation to which the rule applies. Every element of the `criteria` array must match the specified operation. + pub operation: PrepareUserOperationRuleOperation, } - impl ::std::convert::From<&RequestEvmFaucetBodyAddress> for RequestEvmFaucetBodyAddress { - fn from(value: &RequestEvmFaucetBodyAddress) -> Self { + impl ::std::convert::From<&PrepareUserOperationRule> for PrepareUserOperationRule { + fn from(value: &PrepareUserOperationRule) -> Self { value.clone() } } - impl ::std::str::FromStr for RequestEvmFaucetBodyAddress { - type Err = self::error::ConversionError; - fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() - }); - if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); - } - Ok(Self(value.to_string())) - } - } - impl ::std::convert::TryFrom<&str> for RequestEvmFaucetBodyAddress { - type Error = self::error::ConversionError; - fn try_from(value: &str) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<&::std::string::String> for RequestEvmFaucetBodyAddress { - type Error = self::error::ConversionError; - fn try_from( - value: &::std::string::String, - ) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<::std::string::String> for RequestEvmFaucetBodyAddress { - type Error = self::error::ConversionError; - fn try_from( - value: ::std::string::String, - ) -> ::std::result::Result { - value.parse() - } - } - impl<'de> ::serde::Deserialize<'de> for RequestEvmFaucetBodyAddress { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) + impl PrepareUserOperationRule { + pub fn builder() -> builder::PrepareUserOperationRule { + Default::default() } } - ///The network to request funds from. + ///Whether matching the rule will cause the request to be rejected or accepted. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The network to request funds from.", + /// "description": "Whether matching the rule will cause the request to be rejected or accepted.", /// "examples": [ - /// "base-sepolia" + /// "accept" /// ], /// "type": "string", /// "enum": [ - /// "base-sepolia", - /// "ethereum-sepolia", - /// "ethereum-hoodi" + /// "reject", + /// "accept" /// ] ///} /// ``` @@ -29362,46 +33110,42 @@ pub mod types { PartialEq, PartialOrd, )] - pub enum RequestEvmFaucetBodyNetwork { - #[serde(rename = "base-sepolia")] - BaseSepolia, - #[serde(rename = "ethereum-sepolia")] - EthereumSepolia, - #[serde(rename = "ethereum-hoodi")] - EthereumHoodi, + pub enum PrepareUserOperationRuleAction { + #[serde(rename = "reject")] + Reject, + #[serde(rename = "accept")] + Accept, } - impl ::std::convert::From<&Self> for RequestEvmFaucetBodyNetwork { - fn from(value: &RequestEvmFaucetBodyNetwork) -> Self { + impl ::std::convert::From<&Self> for PrepareUserOperationRuleAction { + fn from(value: &PrepareUserOperationRuleAction) -> Self { value.clone() } } - impl ::std::fmt::Display for RequestEvmFaucetBodyNetwork { + impl ::std::fmt::Display for PrepareUserOperationRuleAction { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match *self { - Self::BaseSepolia => f.write_str("base-sepolia"), - Self::EthereumSepolia => f.write_str("ethereum-sepolia"), - Self::EthereumHoodi => f.write_str("ethereum-hoodi"), + Self::Reject => f.write_str("reject"), + Self::Accept => f.write_str("accept"), } } } - impl ::std::str::FromStr for RequestEvmFaucetBodyNetwork { + impl ::std::str::FromStr for PrepareUserOperationRuleAction { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { match value { - "base-sepolia" => Ok(Self::BaseSepolia), - "ethereum-sepolia" => Ok(Self::EthereumSepolia), - "ethereum-hoodi" => Ok(Self::EthereumHoodi), + "reject" => Ok(Self::Reject), + "accept" => Ok(Self::Accept), _ => Err("invalid value".into()), } } } - impl ::std::convert::TryFrom<&str> for RequestEvmFaucetBodyNetwork { + impl ::std::convert::TryFrom<&str> for PrepareUserOperationRuleAction { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for RequestEvmFaucetBodyNetwork { + impl ::std::convert::TryFrom<&::std::string::String> for PrepareUserOperationRuleAction { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -29409,7 +33153,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for RequestEvmFaucetBodyNetwork { + impl ::std::convert::TryFrom<::std::string::String> for PrepareUserOperationRuleAction { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -29417,22 +33161,19 @@ pub mod types { value.parse() } } - ///The token to request funds for. + ///The operation to which the rule applies. Every element of the `criteria` array must match the specified operation. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The token to request funds for.", + /// "description": "The operation to which the rule applies. Every element of the `criteria` array must match the specified operation.", /// "examples": [ - /// "eth" + /// "prepareUserOperation" /// ], /// "type": "string", /// "enum": [ - /// "eth", - /// "usdc", - /// "eurc", - /// "cbbtc" + /// "prepareUserOperation" /// ] ///} /// ``` @@ -29449,50 +33190,38 @@ pub mod types { PartialEq, PartialOrd, )] - pub enum RequestEvmFaucetBodyToken { - #[serde(rename = "eth")] - Eth, - #[serde(rename = "usdc")] - Usdc, - #[serde(rename = "eurc")] - Eurc, - #[serde(rename = "cbbtc")] - Cbbtc, + pub enum PrepareUserOperationRuleOperation { + #[serde(rename = "prepareUserOperation")] + PrepareUserOperation, } - impl ::std::convert::From<&Self> for RequestEvmFaucetBodyToken { - fn from(value: &RequestEvmFaucetBodyToken) -> Self { + impl ::std::convert::From<&Self> for PrepareUserOperationRuleOperation { + fn from(value: &PrepareUserOperationRuleOperation) -> Self { value.clone() } } - impl ::std::fmt::Display for RequestEvmFaucetBodyToken { + impl ::std::fmt::Display for PrepareUserOperationRuleOperation { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match *self { - Self::Eth => f.write_str("eth"), - Self::Usdc => f.write_str("usdc"), - Self::Eurc => f.write_str("eurc"), - Self::Cbbtc => f.write_str("cbbtc"), + Self::PrepareUserOperation => f.write_str("prepareUserOperation"), } } } - impl ::std::str::FromStr for RequestEvmFaucetBodyToken { + impl ::std::str::FromStr for PrepareUserOperationRuleOperation { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { match value { - "eth" => Ok(Self::Eth), - "usdc" => Ok(Self::Usdc), - "eurc" => Ok(Self::Eurc), - "cbbtc" => Ok(Self::Cbbtc), + "prepareUserOperation" => Ok(Self::PrepareUserOperation), _ => Err("invalid value".into()), } } } - impl ::std::convert::TryFrom<&str> for RequestEvmFaucetBodyToken { + impl ::std::convert::TryFrom<&str> for PrepareUserOperationRuleOperation { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for RequestEvmFaucetBodyToken { + impl ::std::convert::TryFrom<&::std::string::String> for PrepareUserOperationRuleOperation { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -29500,7 +33229,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for RequestEvmFaucetBodyToken { + impl ::std::convert::TryFrom<::std::string::String> for PrepareUserOperationRuleOperation { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -29508,108 +33237,171 @@ pub mod types { value.parse() } } - ///`RequestEvmFaucetResponse` + ///The criterion for the program IDs of a Solana transaction's instructions. /// ///
JSON schema /// /// ```json ///{ + /// "title": "ProgramIdCriterion", + /// "description": "The criterion for the program IDs of a Solana transaction's instructions.", /// "type": "object", /// "required": [ - /// "transactionHash" + /// "operator", + /// "programIds", + /// "type" /// ], /// "properties": { - /// "transactionHash": { - /// "description": "The hash of the transaction that requested the funds.\n**Note:** In rare cases, when gas conditions are unusually high, the transaction may not confirm, and the system may issue a replacement transaction to complete the faucet request. In these rare cases, the `transactionHash` will be out of sync with the actual faucet transaction that was confirmed onchain.", + /// "operator": { + /// "description": "The operator to use for the comparison. Each of the program IDs in the transaction's instructions will be on the left-hand side of the operator, and the `programIds` field will be on the right-hand side.", /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// "in" /// ], - /// "type": "string" + /// "type": "string", + /// "enum": [ + /// "in", + /// "not in" + /// ] + /// }, + /// "programIds": { + /// "description": "The Solana program IDs that are compared to the list of program IDs in the transaction's instructions.", + /// "examples": [ + /// [ + /// "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", + /// "11111111111111111111111111111112" + /// ] + /// ], + /// "type": "array", + /// "items": { + /// "description": "The Solana program ID that is compared to the list of program IDs in the transaction's instructions.", + /// "type": "string", + /// "pattern": "^[1-9A-HJ-NP-Za-km-z]{32,44}$" + /// } + /// }, + /// "type": { + /// "description": "The type of criterion to use. This should be `programId`.", + /// "examples": [ + /// "programId" + /// ], + /// "type": "string", + /// "enum": [ + /// "programId" + /// ] /// } - /// } + /// }, + /// "x-audience": "public" ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct RequestEvmFaucetResponse { - /**The hash of the transaction that requested the funds. - **Note:** In rare cases, when gas conditions are unusually high, the transaction may not confirm, and the system may issue a replacement transaction to complete the faucet request. In these rare cases, the `transactionHash` will be out of sync with the actual faucet transaction that was confirmed onchain.*/ - #[serde(rename = "transactionHash")] - pub transaction_hash: ::std::string::String, + pub struct ProgramIdCriterion { + ///The operator to use for the comparison. Each of the program IDs in the transaction's instructions will be on the left-hand side of the operator, and the `programIds` field will be on the right-hand side. + pub operator: ProgramIdCriterionOperator, + ///The Solana program IDs that are compared to the list of program IDs in the transaction's instructions. + #[serde(rename = "programIds")] + pub program_ids: ::std::vec::Vec, + ///The type of criterion to use. This should be `programId`. + #[serde(rename = "type")] + pub type_: ProgramIdCriterionType, } - impl ::std::convert::From<&RequestEvmFaucetResponse> for RequestEvmFaucetResponse { - fn from(value: &RequestEvmFaucetResponse) -> Self { + impl ::std::convert::From<&ProgramIdCriterion> for ProgramIdCriterion { + fn from(value: &ProgramIdCriterion) -> Self { value.clone() } } - impl RequestEvmFaucetResponse { - pub fn builder() -> builder::RequestEvmFaucetResponse { + impl ProgramIdCriterion { + pub fn builder() -> builder::ProgramIdCriterion { Default::default() } } - ///`RequestSolanaFaucetBody` + ///The operator to use for the comparison. Each of the program IDs in the transaction's instructions will be on the left-hand side of the operator, and the `programIds` field will be on the right-hand side. /// ///
JSON schema /// /// ```json ///{ - /// "type": "object", - /// "required": [ - /// "address", - /// "token" + /// "description": "The operator to use for the comparison. Each of the program IDs in the transaction's instructions will be on the left-hand side of the operator, and the `programIds` field will be on the right-hand side.", + /// "examples": [ + /// "in" /// ], - /// "properties": { - /// "address": { - /// "description": "The address to request funds to, which is a base58-encoded string.", - /// "examples": [ - /// "HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT" - /// ], - /// "type": "string", - /// "pattern": "^[1-9A-HJ-NP-Za-km-z]{32,44}$" - /// }, - /// "token": { - /// "description": "The token to request funds for.", - /// "examples": [ - /// "sol" - /// ], - /// "type": "string", - /// "enum": [ - /// "sol", - /// "usdc", - /// "cbtusd" - /// ] - /// } - /// } + /// "type": "string", + /// "enum": [ + /// "in", + /// "not in" + /// ] ///} /// ``` ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct RequestSolanaFaucetBody { - ///The address to request funds to, which is a base58-encoded string. - pub address: RequestSolanaFaucetBodyAddress, - ///The token to request funds for. - pub token: RequestSolanaFaucetBodyToken, + #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum ProgramIdCriterionOperator { + #[serde(rename = "in")] + In, + #[serde(rename = "not in")] + NotIn, } - impl ::std::convert::From<&RequestSolanaFaucetBody> for RequestSolanaFaucetBody { - fn from(value: &RequestSolanaFaucetBody) -> Self { + impl ::std::convert::From<&Self> for ProgramIdCriterionOperator { + fn from(value: &ProgramIdCriterionOperator) -> Self { value.clone() } } - impl RequestSolanaFaucetBody { - pub fn builder() -> builder::RequestSolanaFaucetBody { - Default::default() + impl ::std::fmt::Display for ProgramIdCriterionOperator { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::In => f.write_str("in"), + Self::NotIn => f.write_str("not in"), + } } } - ///The address to request funds to, which is a base58-encoded string. + impl ::std::str::FromStr for ProgramIdCriterionOperator { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "in" => Ok(Self::In), + "not in" => Ok(Self::NotIn), + _ => Err("invalid value".into()), + } + } + } + impl ::std::convert::TryFrom<&str> for ProgramIdCriterionOperator { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for ProgramIdCriterionOperator { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for ProgramIdCriterionOperator { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + ///The Solana program ID that is compared to the list of program IDs in the transaction's instructions. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The address to request funds to, which is a base58-encoded string.", - /// "examples": [ - /// "HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT" - /// ], + /// "description": "The Solana program ID that is compared to the list of program IDs in the transaction's instructions.", /// "type": "string", /// "pattern": "^[1-9A-HJ-NP-Za-km-z]{32,44}$" ///} @@ -29617,24 +33409,24 @@ pub mod types { ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct RequestSolanaFaucetBodyAddress(::std::string::String); - impl ::std::ops::Deref for RequestSolanaFaucetBodyAddress { + pub struct ProgramIdCriterionProgramIdsItem(::std::string::String); + impl ::std::ops::Deref for ProgramIdCriterionProgramIdsItem { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: RequestSolanaFaucetBodyAddress) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: ProgramIdCriterionProgramIdsItem) -> Self { value.0 } } - impl ::std::convert::From<&RequestSolanaFaucetBodyAddress> for RequestSolanaFaucetBodyAddress { - fn from(value: &RequestSolanaFaucetBodyAddress) -> Self { + impl ::std::convert::From<&ProgramIdCriterionProgramIdsItem> for ProgramIdCriterionProgramIdsItem { + fn from(value: &ProgramIdCriterionProgramIdsItem) -> Self { value.clone() } } - impl ::std::str::FromStr for RequestSolanaFaucetBodyAddress { + impl ::std::str::FromStr for ProgramIdCriterionProgramIdsItem { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = @@ -29647,13 +33439,13 @@ pub mod types { Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for RequestSolanaFaucetBodyAddress { + impl ::std::convert::TryFrom<&str> for ProgramIdCriterionProgramIdsItem { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for RequestSolanaFaucetBodyAddress { + impl ::std::convert::TryFrom<&::std::string::String> for ProgramIdCriterionProgramIdsItem { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -29661,7 +33453,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for RequestSolanaFaucetBodyAddress { + impl ::std::convert::TryFrom<::std::string::String> for ProgramIdCriterionProgramIdsItem { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -29669,7 +33461,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for RequestSolanaFaucetBodyAddress { + impl<'de> ::serde::Deserialize<'de> for ProgramIdCriterionProgramIdsItem { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -29681,21 +33473,19 @@ pub mod types { }) } } - ///The token to request funds for. + ///The type of criterion to use. This should be `programId`. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The token to request funds for.", + /// "description": "The type of criterion to use. This should be `programId`.", /// "examples": [ - /// "sol" + /// "programId" /// ], /// "type": "string", /// "enum": [ - /// "sol", - /// "usdc", - /// "cbtusd" + /// "programId" /// ] ///} /// ``` @@ -29712,46 +33502,38 @@ pub mod types { PartialEq, PartialOrd, )] - pub enum RequestSolanaFaucetBodyToken { - #[serde(rename = "sol")] - Sol, - #[serde(rename = "usdc")] - Usdc, - #[serde(rename = "cbtusd")] - Cbtusd, + pub enum ProgramIdCriterionType { + #[serde(rename = "programId")] + ProgramId, } - impl ::std::convert::From<&Self> for RequestSolanaFaucetBodyToken { - fn from(value: &RequestSolanaFaucetBodyToken) -> Self { + impl ::std::convert::From<&Self> for ProgramIdCriterionType { + fn from(value: &ProgramIdCriterionType) -> Self { value.clone() } } - impl ::std::fmt::Display for RequestSolanaFaucetBodyToken { + impl ::std::fmt::Display for ProgramIdCriterionType { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match *self { - Self::Sol => f.write_str("sol"), - Self::Usdc => f.write_str("usdc"), - Self::Cbtusd => f.write_str("cbtusd"), + Self::ProgramId => f.write_str("programId"), } } } - impl ::std::str::FromStr for RequestSolanaFaucetBodyToken { + impl ::std::str::FromStr for ProgramIdCriterionType { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { match value { - "sol" => Ok(Self::Sol), - "usdc" => Ok(Self::Usdc), - "cbtusd" => Ok(Self::Cbtusd), + "programId" => Ok(Self::ProgramId), _ => Err("invalid value".into()), } } } - impl ::std::convert::TryFrom<&str> for RequestSolanaFaucetBodyToken { + impl ::std::convert::TryFrom<&str> for ProgramIdCriterionType { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for RequestSolanaFaucetBodyToken { + impl ::std::convert::TryFrom<&::std::string::String> for ProgramIdCriterionType { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -29759,7 +33541,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for RequestSolanaFaucetBodyToken { + impl ::std::convert::TryFrom<::std::string::String> for ProgramIdCriterionType { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -29767,154 +33549,184 @@ pub mod types { value.parse() } } - ///`RequestSolanaFaucetResponse` + /**Enables control over how often queries need to be fully re-executed on the backing store. + This can be useful in scenarios where API calls might be made frequently, API latency is critical, and some freshness lag (ex: 750ms, 2s, 5s) is tolerable. + By default, each query result is returned from cache so long as the result is from an identical query and less than 500ms old. This freshness tolerance can be modified upwards, to a maximum of 900000ms (i.e. 900s, 15m). + */ /// ///
JSON schema /// /// ```json ///{ - /// "type": "object", - /// "required": [ - /// "transactionSignature" + /// "title": "Query result cache configuration", + /// "description": "Enables control over how often queries need to be fully re-executed on the backing store.\nThis can be useful in scenarios where API calls might be made frequently, API latency is critical, and some freshness lag (ex: 750ms, 2s, 5s) is tolerable.\nBy default, each query result is returned from cache so long as the result is from an identical query and less than 500ms old. This freshness tolerance can be modified upwards, to a maximum of 900000ms (i.e. 900s, 15m).\n", + /// "examples": [ + /// { + /// "maxAgeMs": 1000 + /// } /// ], + /// "type": "object", /// "properties": { - /// "transactionSignature": { - /// "description": "The signature identifying the transaction that requested the funds.", + /// "maxAgeMs": { + /// "description": "The maximum tolerable staleness of the query result cache in milliseconds. If a previous execution result of an identical query is older than this age, the query will be re-executed. If the data is less than this age, the result will be returned from cache.", + /// "default": 500, /// "examples": [ - /// "4dje1d24iG2FfxwxTJJt8VSTtYXNc6AAuJwngtL97TJSqqPD3pgRZ7uh4szoU6WDrKyFTBgaswkDrCr7BqWjQqqK" + /// 1000 /// ], - /// "type": "string" + /// "type": "integer", + /// "maximum": 900000.0, + /// "minimum": 500.0 /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct RequestSolanaFaucetResponse { - ///The signature identifying the transaction that requested the funds. - #[serde(rename = "transactionSignature")] - pub transaction_signature: ::std::string::String, + pub struct QueryResultCacheConfiguration { + ///The maximum tolerable staleness of the query result cache in milliseconds. If a previous execution result of an identical query is older than this age, the query will be re-executed. If the data is less than this age, the result will be returned from cache. + #[serde(rename = "maxAgeMs", default = "defaults::default_u64::")] + pub max_age_ms: i64, } - impl ::std::convert::From<&RequestSolanaFaucetResponse> for RequestSolanaFaucetResponse { - fn from(value: &RequestSolanaFaucetResponse) -> Self { + impl ::std::convert::From<&QueryResultCacheConfiguration> for QueryResultCacheConfiguration { + fn from(value: &QueryResultCacheConfiguration) -> Self { value.clone() } } - impl RequestSolanaFaucetResponse { - pub fn builder() -> builder::RequestSolanaFaucetResponse { + impl ::std::default::Default for QueryResultCacheConfiguration { + fn default() -> Self { + Self { + max_age_ms: defaults::default_u64::(), + } + } + } + impl QueryResultCacheConfiguration { + pub fn builder() -> builder::QueryResultCacheConfiguration { Default::default() } } - ///`RevokeDelegationForEndUserAccountBody` + ///`RequestEvmFaucetBody` /// ///
JSON schema /// /// ```json ///{ /// "type": "object", + /// "required": [ + /// "address", + /// "network", + /// "token" + /// ], /// "properties": { - /// "walletSecretId": { - /// "description": "When revoking with a wallet authentication scheme, the ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header.", + /// "address": { + /// "description": "The address to request funds to, which is a 0x-prefixed hexadecimal string.", /// "examples": [ - /// "e051beeb-7163-4527-a5b6-35e301529ff2" + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" /// ], /// "type": "string", - /// "pattern": "^[a-zA-Z0-9-]{1,100}$" + /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// }, + /// "network": { + /// "description": "The network to request funds from.", + /// "examples": [ + /// "base-sepolia" + /// ], + /// "type": "string", + /// "enum": [ + /// "base-sepolia", + /// "ethereum-sepolia", + /// "ethereum-hoodi" + /// ] + /// }, + /// "token": { + /// "description": "The token to request funds for.", + /// "examples": [ + /// "eth" + /// ], + /// "type": "string", + /// "enum": [ + /// "eth", + /// "usdc", + /// "eurc", + /// "cbbtc" + /// ] /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct RevokeDelegationForEndUserAccountBody { - ///When revoking with a wallet authentication scheme, the ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. - #[serde( - rename = "walletSecretId", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub wallet_secret_id: - ::std::option::Option, + pub struct RequestEvmFaucetBody { + ///The address to request funds to, which is a 0x-prefixed hexadecimal string. + pub address: RequestEvmFaucetBodyAddress, + ///The network to request funds from. + pub network: RequestEvmFaucetBodyNetwork, + ///The token to request funds for. + pub token: RequestEvmFaucetBodyToken, } - impl ::std::convert::From<&RevokeDelegationForEndUserAccountBody> - for RevokeDelegationForEndUserAccountBody - { - fn from(value: &RevokeDelegationForEndUserAccountBody) -> Self { + impl ::std::convert::From<&RequestEvmFaucetBody> for RequestEvmFaucetBody { + fn from(value: &RequestEvmFaucetBody) -> Self { value.clone() } } - impl ::std::default::Default for RevokeDelegationForEndUserAccountBody { - fn default() -> Self { - Self { - wallet_secret_id: Default::default(), - } - } - } - impl RevokeDelegationForEndUserAccountBody { - pub fn builder() -> builder::RevokeDelegationForEndUserAccountBody { + impl RequestEvmFaucetBody { + pub fn builder() -> builder::RequestEvmFaucetBody { Default::default() } } - ///When revoking with a wallet authentication scheme, the ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. + ///The address to request funds to, which is a 0x-prefixed hexadecimal string. /// ///
JSON schema /// /// ```json ///{ - /// "description": "When revoking with a wallet authentication scheme, the ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header.", + /// "description": "The address to request funds to, which is a 0x-prefixed hexadecimal string.", /// "examples": [ - /// "e051beeb-7163-4527-a5b6-35e301529ff2" + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" /// ], /// "type": "string", - /// "pattern": "^[a-zA-Z0-9-]{1,100}$" + /// "pattern": "^0x[0-9a-fA-F]{40}$" ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct RevokeDelegationForEndUserAccountBodyWalletSecretId(::std::string::String); - impl ::std::ops::Deref for RevokeDelegationForEndUserAccountBodyWalletSecretId { + pub struct RequestEvmFaucetBodyAddress(::std::string::String); + impl ::std::ops::Deref for RequestEvmFaucetBodyAddress { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From - for ::std::string::String - { - fn from(value: RevokeDelegationForEndUserAccountBodyWalletSecretId) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: RequestEvmFaucetBodyAddress) -> Self { value.0 } } - impl ::std::convert::From<&RevokeDelegationForEndUserAccountBodyWalletSecretId> - for RevokeDelegationForEndUserAccountBodyWalletSecretId - { - fn from(value: &RevokeDelegationForEndUserAccountBodyWalletSecretId) -> Self { + impl ::std::convert::From<&RequestEvmFaucetBodyAddress> for RequestEvmFaucetBodyAddress { + fn from(value: &RequestEvmFaucetBodyAddress) -> Self { value.clone() } } - impl ::std::str::FromStr for RevokeDelegationForEndUserAccountBodyWalletSecretId { + impl ::std::str::FromStr for RequestEvmFaucetBodyAddress { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^[a-zA-Z0-9-]{1,100}$").unwrap() + ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() }); if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^[a-zA-Z0-9-]{1,100}$\"".into()); + return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for RevokeDelegationForEndUserAccountBodyWalletSecretId { + impl ::std::convert::TryFrom<&str> for RequestEvmFaucetBodyAddress { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> - for RevokeDelegationForEndUserAccountBodyWalletSecretId - { + impl ::std::convert::TryFrom<&::std::string::String> for RequestEvmFaucetBodyAddress { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -29922,9 +33734,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> - for RevokeDelegationForEndUserAccountBodyWalletSecretId - { + impl ::std::convert::TryFrom<::std::string::String> for RequestEvmFaucetBodyAddress { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -29932,7 +33742,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for RevokeDelegationForEndUserAccountBodyWalletSecretId { + impl<'de> ::serde::Deserialize<'de> for RequestEvmFaucetBodyAddress { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -29944,69 +33754,77 @@ pub mod types { }) } } - ///`RevokeDelegationForEndUserAccountProjectId` + ///The network to request funds from. /// ///
JSON schema /// /// ```json ///{ + /// "description": "The network to request funds from.", /// "examples": [ - /// "8e03978e-40d5-43e8-bc93-6894a57f9324" + /// "base-sepolia" /// ], /// "type": "string", - /// "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" + /// "enum": [ + /// "base-sepolia", + /// "ethereum-sepolia", + /// "ethereum-hoodi" + /// ] ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct RevokeDelegationForEndUserAccountProjectId(::std::string::String); - impl ::std::ops::Deref for RevokeDelegationForEndUserAccountProjectId { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } + #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum RequestEvmFaucetBodyNetwork { + #[serde(rename = "base-sepolia")] + BaseSepolia, + #[serde(rename = "ethereum-sepolia")] + EthereumSepolia, + #[serde(rename = "ethereum-hoodi")] + EthereumHoodi, } - impl ::std::convert::From for ::std::string::String { - fn from(value: RevokeDelegationForEndUserAccountProjectId) -> Self { - value.0 + impl ::std::convert::From<&Self> for RequestEvmFaucetBodyNetwork { + fn from(value: &RequestEvmFaucetBodyNetwork) -> Self { + value.clone() } } - impl ::std::convert::From<&RevokeDelegationForEndUserAccountProjectId> - for RevokeDelegationForEndUserAccountProjectId - { - fn from(value: &RevokeDelegationForEndUserAccountProjectId) -> Self { - value.clone() + impl ::std::fmt::Display for RequestEvmFaucetBodyNetwork { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::BaseSepolia => f.write_str("base-sepolia"), + Self::EthereumSepolia => f.write_str("ethereum-sepolia"), + Self::EthereumHoodi => f.write_str("ethereum-hoodi"), + } } } - impl ::std::str::FromStr for RevokeDelegationForEndUserAccountProjectId { + impl ::std::str::FromStr for RequestEvmFaucetBodyNetwork { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new( - "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", - ) - .unwrap() - }); - if PATTERN.find(value).is_none() { - return Err( - "doesn't match pattern \"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$\"" - .into(), - ); + match value { + "base-sepolia" => Ok(Self::BaseSepolia), + "ethereum-sepolia" => Ok(Self::EthereumSepolia), + "ethereum-hoodi" => Ok(Self::EthereumHoodi), + _ => Err("invalid value".into()), } - Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for RevokeDelegationForEndUserAccountProjectId { + impl ::std::convert::TryFrom<&str> for RequestEvmFaucetBodyNetwork { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> - for RevokeDelegationForEndUserAccountProjectId - { + impl ::std::convert::TryFrom<&::std::string::String> for RequestEvmFaucetBodyNetwork { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -30014,7 +33832,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for RevokeDelegationForEndUserAccountProjectId { + impl ::std::convert::TryFrom<::std::string::String> for RequestEvmFaucetBodyNetwork { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -30022,73 +33840,82 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for RevokeDelegationForEndUserAccountProjectId { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) - } - } - ///`RevokeDelegationForEndUserAccountUserId` + ///The token to request funds for. /// ///
JSON schema /// /// ```json ///{ + /// "description": "The token to request funds for.", /// "examples": [ - /// "e051beeb-7163-4527-a5b6-35e301529ff2" + /// "eth" /// ], /// "type": "string", - /// "pattern": "^[a-zA-Z0-9-]{1,100}$" + /// "enum": [ + /// "eth", + /// "usdc", + /// "eurc", + /// "cbbtc" + /// ] ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct RevokeDelegationForEndUserAccountUserId(::std::string::String); - impl ::std::ops::Deref for RevokeDelegationForEndUserAccountUserId { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } + #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum RequestEvmFaucetBodyToken { + #[serde(rename = "eth")] + Eth, + #[serde(rename = "usdc")] + Usdc, + #[serde(rename = "eurc")] + Eurc, + #[serde(rename = "cbbtc")] + Cbbtc, } - impl ::std::convert::From for ::std::string::String { - fn from(value: RevokeDelegationForEndUserAccountUserId) -> Self { - value.0 + impl ::std::convert::From<&Self> for RequestEvmFaucetBodyToken { + fn from(value: &RequestEvmFaucetBodyToken) -> Self { + value.clone() } } - impl ::std::convert::From<&RevokeDelegationForEndUserAccountUserId> - for RevokeDelegationForEndUserAccountUserId - { - fn from(value: &RevokeDelegationForEndUserAccountUserId) -> Self { - value.clone() + impl ::std::fmt::Display for RequestEvmFaucetBodyToken { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Eth => f.write_str("eth"), + Self::Usdc => f.write_str("usdc"), + Self::Eurc => f.write_str("eurc"), + Self::Cbbtc => f.write_str("cbbtc"), + } } } - impl ::std::str::FromStr for RevokeDelegationForEndUserAccountUserId { + impl ::std::str::FromStr for RequestEvmFaucetBodyToken { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^[a-zA-Z0-9-]{1,100}$").unwrap() - }); - if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^[a-zA-Z0-9-]{1,100}$\"".into()); + match value { + "eth" => Ok(Self::Eth), + "usdc" => Ok(Self::Usdc), + "eurc" => Ok(Self::Eurc), + "cbbtc" => Ok(Self::Cbbtc), + _ => Err("invalid value".into()), } - Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for RevokeDelegationForEndUserAccountUserId { + impl ::std::convert::TryFrom<&str> for RequestEvmFaucetBodyToken { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for RevokeDelegationForEndUserAccountUserId { + impl ::std::convert::TryFrom<&::std::string::String> for RequestEvmFaucetBodyToken { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -30096,7 +33923,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for RevokeDelegationForEndUserAccountUserId { + impl ::std::convert::TryFrom<::std::string::String> for RequestEvmFaucetBodyToken { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -30104,74 +33931,152 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for RevokeDelegationForEndUserAccountUserId { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) + ///`RequestEvmFaucetResponse` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "type": "object", + /// "required": [ + /// "transactionHash" + /// ], + /// "properties": { + /// "transactionHash": { + /// "description": "The hash of the transaction that requested the funds.\n**Note:** In rare cases, when gas conditions are unusually high, the transaction may not confirm, and the system may issue a replacement transaction to complete the faucet request. In these rare cases, the `transactionHash` will be out of sync with the actual faucet transaction that was confirmed onchain.", + /// "examples": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ], + /// "type": "string" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct RequestEvmFaucetResponse { + /**The hash of the transaction that requested the funds. + **Note:** In rare cases, when gas conditions are unusually high, the transaction may not confirm, and the system may issue a replacement transaction to complete the faucet request. In these rare cases, the `transactionHash` will be out of sync with the actual faucet transaction that was confirmed onchain.*/ + #[serde(rename = "transactionHash")] + pub transaction_hash: ::std::string::String, + } + impl ::std::convert::From<&RequestEvmFaucetResponse> for RequestEvmFaucetResponse { + fn from(value: &RequestEvmFaucetResponse) -> Self { + value.clone() } } - ///`RevokeDelegationForEndUserAccountXIdempotencyKey` + impl RequestEvmFaucetResponse { + pub fn builder() -> builder::RequestEvmFaucetResponse { + Default::default() + } + } + ///`RequestSolanaFaucetBody` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "type": "object", + /// "required": [ + /// "address", + /// "token" + /// ], + /// "properties": { + /// "address": { + /// "description": "The address to request funds to, which is a base58-encoded string.", + /// "examples": [ + /// "HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT" + /// ], + /// "type": "string", + /// "pattern": "^[1-9A-HJ-NP-Za-km-z]{32,44}$" + /// }, + /// "token": { + /// "description": "The token to request funds for.", + /// "examples": [ + /// "sol" + /// ], + /// "type": "string", + /// "enum": [ + /// "sol", + /// "usdc", + /// "cbtusd" + /// ] + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct RequestSolanaFaucetBody { + ///The address to request funds to, which is a base58-encoded string. + pub address: RequestSolanaFaucetBodyAddress, + ///The token to request funds for. + pub token: RequestSolanaFaucetBodyToken, + } + impl ::std::convert::From<&RequestSolanaFaucetBody> for RequestSolanaFaucetBody { + fn from(value: &RequestSolanaFaucetBody) -> Self { + value.clone() + } + } + impl RequestSolanaFaucetBody { + pub fn builder() -> builder::RequestSolanaFaucetBody { + Default::default() + } + } + ///The address to request funds to, which is a base58-encoded string. /// ///
JSON schema /// /// ```json ///{ + /// "description": "The address to request funds to, which is a base58-encoded string.", + /// "examples": [ + /// "HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT" + /// ], /// "type": "string", - /// "maxLength": 128, - /// "minLength": 1 + /// "pattern": "^[1-9A-HJ-NP-Za-km-z]{32,44}$" ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct RevokeDelegationForEndUserAccountXIdempotencyKey(::std::string::String); - impl ::std::ops::Deref for RevokeDelegationForEndUserAccountXIdempotencyKey { + pub struct RequestSolanaFaucetBodyAddress(::std::string::String); + impl ::std::ops::Deref for RequestSolanaFaucetBodyAddress { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From - for ::std::string::String - { - fn from(value: RevokeDelegationForEndUserAccountXIdempotencyKey) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: RequestSolanaFaucetBodyAddress) -> Self { value.0 } } - impl ::std::convert::From<&RevokeDelegationForEndUserAccountXIdempotencyKey> - for RevokeDelegationForEndUserAccountXIdempotencyKey - { - fn from(value: &RevokeDelegationForEndUserAccountXIdempotencyKey) -> Self { + impl ::std::convert::From<&RequestSolanaFaucetBodyAddress> for RequestSolanaFaucetBodyAddress { + fn from(value: &RequestSolanaFaucetBodyAddress) -> Self { value.clone() } } - impl ::std::str::FromStr for RevokeDelegationForEndUserAccountXIdempotencyKey { + impl ::std::str::FromStr for RequestSolanaFaucetBodyAddress { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - if value.chars().count() > 128usize { - return Err("longer than 128 characters".into()); - } - if value.chars().count() < 1usize { - return Err("shorter than 1 characters".into()); + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^[1-9A-HJ-NP-Za-km-z]{32,44}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^[1-9A-HJ-NP-Za-km-z]{32,44}$\"".into()); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for RevokeDelegationForEndUserAccountXIdempotencyKey { + impl ::std::convert::TryFrom<&str> for RequestSolanaFaucetBodyAddress { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> - for RevokeDelegationForEndUserAccountXIdempotencyKey - { + impl ::std::convert::TryFrom<&::std::string::String> for RequestSolanaFaucetBodyAddress { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -30179,9 +34084,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> - for RevokeDelegationForEndUserAccountXIdempotencyKey - { + impl ::std::convert::TryFrom<::std::string::String> for RequestSolanaFaucetBodyAddress { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -30189,7 +34092,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for RevokeDelegationForEndUserAccountXIdempotencyKey { + impl<'de> ::serde::Deserialize<'de> for RequestSolanaFaucetBodyAddress { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -30201,7 +34104,131 @@ pub mod types { }) } } - ///`RevokeDelegationForEndUserBody` + ///The token to request funds for. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The token to request funds for.", + /// "examples": [ + /// "sol" + /// ], + /// "type": "string", + /// "enum": [ + /// "sol", + /// "usdc", + /// "cbtusd" + /// ] + ///} + /// ``` + ///
+ #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum RequestSolanaFaucetBodyToken { + #[serde(rename = "sol")] + Sol, + #[serde(rename = "usdc")] + Usdc, + #[serde(rename = "cbtusd")] + Cbtusd, + } + impl ::std::convert::From<&Self> for RequestSolanaFaucetBodyToken { + fn from(value: &RequestSolanaFaucetBodyToken) -> Self { + value.clone() + } + } + impl ::std::fmt::Display for RequestSolanaFaucetBodyToken { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Sol => f.write_str("sol"), + Self::Usdc => f.write_str("usdc"), + Self::Cbtusd => f.write_str("cbtusd"), + } + } + } + impl ::std::str::FromStr for RequestSolanaFaucetBodyToken { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "sol" => Ok(Self::Sol), + "usdc" => Ok(Self::Usdc), + "cbtusd" => Ok(Self::Cbtusd), + _ => Err("invalid value".into()), + } + } + } + impl ::std::convert::TryFrom<&str> for RequestSolanaFaucetBodyToken { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for RequestSolanaFaucetBodyToken { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for RequestSolanaFaucetBodyToken { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + ///`RequestSolanaFaucetResponse` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "type": "object", + /// "required": [ + /// "transactionSignature" + /// ], + /// "properties": { + /// "transactionSignature": { + /// "description": "The signature identifying the transaction that requested the funds.", + /// "examples": [ + /// "4dje1d24iG2FfxwxTJJt8VSTtYXNc6AAuJwngtL97TJSqqPD3pgRZ7uh4szoU6WDrKyFTBgaswkDrCr7BqWjQqqK" + /// ], + /// "type": "string" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct RequestSolanaFaucetResponse { + ///The signature identifying the transaction that requested the funds. + #[serde(rename = "transactionSignature")] + pub transaction_signature: ::std::string::String, + } + impl ::std::convert::From<&RequestSolanaFaucetResponse> for RequestSolanaFaucetResponse { + fn from(value: &RequestSolanaFaucetResponse) -> Self { + value.clone() + } + } + impl RequestSolanaFaucetResponse { + pub fn builder() -> builder::RequestSolanaFaucetResponse { + Default::default() + } + } + ///`RevokeDelegationForEndUserAccountBody` /// ///
JSON schema /// @@ -30222,29 +34249,32 @@ pub mod types { /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct RevokeDelegationForEndUserBody { + pub struct RevokeDelegationForEndUserAccountBody { ///When revoking with a wallet authentication scheme, the ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. #[serde( rename = "walletSecretId", default, skip_serializing_if = "::std::option::Option::is_none" )] - pub wallet_secret_id: ::std::option::Option, + pub wallet_secret_id: + ::std::option::Option, } - impl ::std::convert::From<&RevokeDelegationForEndUserBody> for RevokeDelegationForEndUserBody { - fn from(value: &RevokeDelegationForEndUserBody) -> Self { + impl ::std::convert::From<&RevokeDelegationForEndUserAccountBody> + for RevokeDelegationForEndUserAccountBody + { + fn from(value: &RevokeDelegationForEndUserAccountBody) -> Self { value.clone() } } - impl ::std::default::Default for RevokeDelegationForEndUserBody { + impl ::std::default::Default for RevokeDelegationForEndUserAccountBody { fn default() -> Self { Self { wallet_secret_id: Default::default(), } } } - impl RevokeDelegationForEndUserBody { - pub fn builder() -> builder::RevokeDelegationForEndUserBody { + impl RevokeDelegationForEndUserAccountBody { + pub fn builder() -> builder::RevokeDelegationForEndUserAccountBody { Default::default() } } @@ -30265,26 +34295,28 @@ pub mod types { ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct RevokeDelegationForEndUserBodyWalletSecretId(::std::string::String); - impl ::std::ops::Deref for RevokeDelegationForEndUserBodyWalletSecretId { + pub struct RevokeDelegationForEndUserAccountBodyWalletSecretId(::std::string::String); + impl ::std::ops::Deref for RevokeDelegationForEndUserAccountBodyWalletSecretId { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: RevokeDelegationForEndUserBodyWalletSecretId) -> Self { + impl ::std::convert::From + for ::std::string::String + { + fn from(value: RevokeDelegationForEndUserAccountBodyWalletSecretId) -> Self { value.0 } } - impl ::std::convert::From<&RevokeDelegationForEndUserBodyWalletSecretId> - for RevokeDelegationForEndUserBodyWalletSecretId + impl ::std::convert::From<&RevokeDelegationForEndUserAccountBodyWalletSecretId> + for RevokeDelegationForEndUserAccountBodyWalletSecretId { - fn from(value: &RevokeDelegationForEndUserBodyWalletSecretId) -> Self { + fn from(value: &RevokeDelegationForEndUserAccountBodyWalletSecretId) -> Self { value.clone() } } - impl ::std::str::FromStr for RevokeDelegationForEndUserBodyWalletSecretId { + impl ::std::str::FromStr for RevokeDelegationForEndUserAccountBodyWalletSecretId { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = @@ -30297,14 +34329,14 @@ pub mod types { Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for RevokeDelegationForEndUserBodyWalletSecretId { + impl ::std::convert::TryFrom<&str> for RevokeDelegationForEndUserAccountBodyWalletSecretId { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } impl ::std::convert::TryFrom<&::std::string::String> - for RevokeDelegationForEndUserBodyWalletSecretId + for RevokeDelegationForEndUserAccountBodyWalletSecretId { type Error = self::error::ConversionError; fn try_from( @@ -30314,7 +34346,7 @@ pub mod types { } } impl ::std::convert::TryFrom<::std::string::String> - for RevokeDelegationForEndUserBodyWalletSecretId + for RevokeDelegationForEndUserAccountBodyWalletSecretId { type Error = self::error::ConversionError; fn try_from( @@ -30323,7 +34355,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for RevokeDelegationForEndUserBodyWalletSecretId { + impl<'de> ::serde::Deserialize<'de> for RevokeDelegationForEndUserAccountBodyWalletSecretId { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -30335,7 +34367,7 @@ pub mod types { }) } } - ///`RevokeDelegationForEndUserProjectId` + ///`RevokeDelegationForEndUserAccountProjectId` /// ///
JSON schema /// @@ -30351,26 +34383,26 @@ pub mod types { ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct RevokeDelegationForEndUserProjectId(::std::string::String); - impl ::std::ops::Deref for RevokeDelegationForEndUserProjectId { + pub struct RevokeDelegationForEndUserAccountProjectId(::std::string::String); + impl ::std::ops::Deref for RevokeDelegationForEndUserAccountProjectId { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: RevokeDelegationForEndUserProjectId) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: RevokeDelegationForEndUserAccountProjectId) -> Self { value.0 } } - impl ::std::convert::From<&RevokeDelegationForEndUserProjectId> - for RevokeDelegationForEndUserProjectId + impl ::std::convert::From<&RevokeDelegationForEndUserAccountProjectId> + for RevokeDelegationForEndUserAccountProjectId { - fn from(value: &RevokeDelegationForEndUserProjectId) -> Self { + fn from(value: &RevokeDelegationForEndUserAccountProjectId) -> Self { value.clone() } } - impl ::std::str::FromStr for RevokeDelegationForEndUserProjectId { + impl ::std::str::FromStr for RevokeDelegationForEndUserAccountProjectId { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = @@ -30389,13 +34421,15 @@ pub mod types { Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for RevokeDelegationForEndUserProjectId { + impl ::std::convert::TryFrom<&str> for RevokeDelegationForEndUserAccountProjectId { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for RevokeDelegationForEndUserProjectId { + impl ::std::convert::TryFrom<&::std::string::String> + for RevokeDelegationForEndUserAccountProjectId + { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -30403,7 +34437,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for RevokeDelegationForEndUserProjectId { + impl ::std::convert::TryFrom<::std::string::String> for RevokeDelegationForEndUserAccountProjectId { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -30411,7 +34445,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for RevokeDelegationForEndUserProjectId { + impl<'de> ::serde::Deserialize<'de> for RevokeDelegationForEndUserAccountProjectId { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -30423,7 +34457,7 @@ pub mod types { }) } } - ///`RevokeDelegationForEndUserUserId` + ///`RevokeDelegationForEndUserAccountUserId` /// ///
JSON schema /// @@ -30439,24 +34473,26 @@ pub mod types { ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct RevokeDelegationForEndUserUserId(::std::string::String); - impl ::std::ops::Deref for RevokeDelegationForEndUserUserId { + pub struct RevokeDelegationForEndUserAccountUserId(::std::string::String); + impl ::std::ops::Deref for RevokeDelegationForEndUserAccountUserId { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: RevokeDelegationForEndUserUserId) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: RevokeDelegationForEndUserAccountUserId) -> Self { value.0 } } - impl ::std::convert::From<&RevokeDelegationForEndUserUserId> for RevokeDelegationForEndUserUserId { - fn from(value: &RevokeDelegationForEndUserUserId) -> Self { + impl ::std::convert::From<&RevokeDelegationForEndUserAccountUserId> + for RevokeDelegationForEndUserAccountUserId + { + fn from(value: &RevokeDelegationForEndUserAccountUserId) -> Self { value.clone() } } - impl ::std::str::FromStr for RevokeDelegationForEndUserUserId { + impl ::std::str::FromStr for RevokeDelegationForEndUserAccountUserId { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = @@ -30469,13 +34505,13 @@ pub mod types { Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for RevokeDelegationForEndUserUserId { + impl ::std::convert::TryFrom<&str> for RevokeDelegationForEndUserAccountUserId { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for RevokeDelegationForEndUserUserId { + impl ::std::convert::TryFrom<&::std::string::String> for RevokeDelegationForEndUserAccountUserId { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -30483,7 +34519,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for RevokeDelegationForEndUserUserId { + impl ::std::convert::TryFrom<::std::string::String> for RevokeDelegationForEndUserAccountUserId { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -30491,7 +34527,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for RevokeDelegationForEndUserUserId { + impl<'de> ::serde::Deserialize<'de> for RevokeDelegationForEndUserAccountUserId { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -30503,7 +34539,7 @@ pub mod types { }) } } - ///`RevokeDelegationForEndUserXIdempotencyKey` + ///`RevokeDelegationForEndUserAccountXIdempotencyKey` /// ///
JSON schema /// @@ -30517,26 +34553,28 @@ pub mod types { ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct RevokeDelegationForEndUserXIdempotencyKey(::std::string::String); - impl ::std::ops::Deref for RevokeDelegationForEndUserXIdempotencyKey { + pub struct RevokeDelegationForEndUserAccountXIdempotencyKey(::std::string::String); + impl ::std::ops::Deref for RevokeDelegationForEndUserAccountXIdempotencyKey { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: RevokeDelegationForEndUserXIdempotencyKey) -> Self { + impl ::std::convert::From + for ::std::string::String + { + fn from(value: RevokeDelegationForEndUserAccountXIdempotencyKey) -> Self { value.0 } } - impl ::std::convert::From<&RevokeDelegationForEndUserXIdempotencyKey> - for RevokeDelegationForEndUserXIdempotencyKey + impl ::std::convert::From<&RevokeDelegationForEndUserAccountXIdempotencyKey> + for RevokeDelegationForEndUserAccountXIdempotencyKey { - fn from(value: &RevokeDelegationForEndUserXIdempotencyKey) -> Self { + fn from(value: &RevokeDelegationForEndUserAccountXIdempotencyKey) -> Self { value.clone() } } - impl ::std::str::FromStr for RevokeDelegationForEndUserXIdempotencyKey { + impl ::std::str::FromStr for RevokeDelegationForEndUserAccountXIdempotencyKey { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { if value.chars().count() > 128usize { @@ -30548,13 +34586,15 @@ pub mod types { Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for RevokeDelegationForEndUserXIdempotencyKey { + impl ::std::convert::TryFrom<&str> for RevokeDelegationForEndUserAccountXIdempotencyKey { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for RevokeDelegationForEndUserXIdempotencyKey { + impl ::std::convert::TryFrom<&::std::string::String> + for RevokeDelegationForEndUserAccountXIdempotencyKey + { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -30562,7 +34602,9 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for RevokeDelegationForEndUserXIdempotencyKey { + impl ::std::convert::TryFrom<::std::string::String> + for RevokeDelegationForEndUserAccountXIdempotencyKey + { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -30570,7 +34612,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for RevokeDelegationForEndUserXIdempotencyKey { + impl<'de> ::serde::Deserialize<'de> for RevokeDelegationForEndUserAccountXIdempotencyKey { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -30582,56 +34624,111 @@ pub mod types { }) } } - ///`RevokeSpendPermissionAddress` + ///`RevokeDelegationForEndUserBody` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "type": "object", + /// "properties": { + /// "walletSecretId": { + /// "description": "When revoking with a wallet authentication scheme, the ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header.", + /// "examples": [ + /// "e051beeb-7163-4527-a5b6-35e301529ff2" + /// ], + /// "type": "string", + /// "pattern": "^[a-zA-Z0-9-]{1,100}$" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct RevokeDelegationForEndUserBody { + ///When revoking with a wallet authentication scheme, the ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. + #[serde( + rename = "walletSecretId", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub wallet_secret_id: ::std::option::Option, + } + impl ::std::convert::From<&RevokeDelegationForEndUserBody> for RevokeDelegationForEndUserBody { + fn from(value: &RevokeDelegationForEndUserBody) -> Self { + value.clone() + } + } + impl ::std::default::Default for RevokeDelegationForEndUserBody { + fn default() -> Self { + Self { + wallet_secret_id: Default::default(), + } + } + } + impl RevokeDelegationForEndUserBody { + pub fn builder() -> builder::RevokeDelegationForEndUserBody { + Default::default() + } + } + ///When revoking with a wallet authentication scheme, the ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header. /// ///
JSON schema /// /// ```json ///{ + /// "description": "When revoking with a wallet authentication scheme, the ID of the Temporary Wallet Secret that was used to sign the X-Wallet-Auth Header.", + /// "examples": [ + /// "e051beeb-7163-4527-a5b6-35e301529ff2" + /// ], /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// "pattern": "^[a-zA-Z0-9-]{1,100}$" ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct RevokeSpendPermissionAddress(::std::string::String); - impl ::std::ops::Deref for RevokeSpendPermissionAddress { + pub struct RevokeDelegationForEndUserBodyWalletSecretId(::std::string::String); + impl ::std::ops::Deref for RevokeDelegationForEndUserBodyWalletSecretId { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: RevokeSpendPermissionAddress) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: RevokeDelegationForEndUserBodyWalletSecretId) -> Self { value.0 } } - impl ::std::convert::From<&RevokeSpendPermissionAddress> for RevokeSpendPermissionAddress { - fn from(value: &RevokeSpendPermissionAddress) -> Self { + impl ::std::convert::From<&RevokeDelegationForEndUserBodyWalletSecretId> + for RevokeDelegationForEndUserBodyWalletSecretId + { + fn from(value: &RevokeDelegationForEndUserBodyWalletSecretId) -> Self { value.clone() } } - impl ::std::str::FromStr for RevokeSpendPermissionAddress { + impl ::std::str::FromStr for RevokeDelegationForEndUserBodyWalletSecretId { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() + ::regress::Regex::new("^[a-zA-Z0-9-]{1,100}$").unwrap() }); if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); + return Err("doesn't match pattern \"^[a-zA-Z0-9-]{1,100}$\"".into()); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for RevokeSpendPermissionAddress { + impl ::std::convert::TryFrom<&str> for RevokeDelegationForEndUserBodyWalletSecretId { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for RevokeSpendPermissionAddress { + impl ::std::convert::TryFrom<&::std::string::String> + for RevokeDelegationForEndUserBodyWalletSecretId + { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -30639,7 +34736,9 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for RevokeSpendPermissionAddress { + impl ::std::convert::TryFrom<::std::string::String> + for RevokeDelegationForEndUserBodyWalletSecretId + { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -30647,7 +34746,331 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for RevokeSpendPermissionAddress { + impl<'de> ::serde::Deserialize<'de> for RevokeDelegationForEndUserBodyWalletSecretId { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///`RevokeDelegationForEndUserProjectId` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "examples": [ + /// "8e03978e-40d5-43e8-bc93-6894a57f9324" + /// ], + /// "type": "string", + /// "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct RevokeDelegationForEndUserProjectId(::std::string::String); + impl ::std::ops::Deref for RevokeDelegationForEndUserProjectId { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: RevokeDelegationForEndUserProjectId) -> Self { + value.0 + } + } + impl ::std::convert::From<&RevokeDelegationForEndUserProjectId> + for RevokeDelegationForEndUserProjectId + { + fn from(value: &RevokeDelegationForEndUserProjectId) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for RevokeDelegationForEndUserProjectId { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new( + "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + ) + .unwrap() + }); + if PATTERN.find(value).is_none() { + return Err( + "doesn't match pattern \"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$\"" + .into(), + ); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for RevokeDelegationForEndUserProjectId { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for RevokeDelegationForEndUserProjectId { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for RevokeDelegationForEndUserProjectId { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for RevokeDelegationForEndUserProjectId { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///`RevokeDelegationForEndUserUserId` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "examples": [ + /// "e051beeb-7163-4527-a5b6-35e301529ff2" + /// ], + /// "type": "string", + /// "pattern": "^[a-zA-Z0-9-]{1,100}$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct RevokeDelegationForEndUserUserId(::std::string::String); + impl ::std::ops::Deref for RevokeDelegationForEndUserUserId { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: RevokeDelegationForEndUserUserId) -> Self { + value.0 + } + } + impl ::std::convert::From<&RevokeDelegationForEndUserUserId> for RevokeDelegationForEndUserUserId { + fn from(value: &RevokeDelegationForEndUserUserId) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for RevokeDelegationForEndUserUserId { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^[a-zA-Z0-9-]{1,100}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^[a-zA-Z0-9-]{1,100}$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for RevokeDelegationForEndUserUserId { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for RevokeDelegationForEndUserUserId { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for RevokeDelegationForEndUserUserId { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for RevokeDelegationForEndUserUserId { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///`RevokeDelegationForEndUserXIdempotencyKey` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "type": "string", + /// "maxLength": 128, + /// "minLength": 1 + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct RevokeDelegationForEndUserXIdempotencyKey(::std::string::String); + impl ::std::ops::Deref for RevokeDelegationForEndUserXIdempotencyKey { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: RevokeDelegationForEndUserXIdempotencyKey) -> Self { + value.0 + } + } + impl ::std::convert::From<&RevokeDelegationForEndUserXIdempotencyKey> + for RevokeDelegationForEndUserXIdempotencyKey + { + fn from(value: &RevokeDelegationForEndUserXIdempotencyKey) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for RevokeDelegationForEndUserXIdempotencyKey { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + if value.chars().count() > 128usize { + return Err("longer than 128 characters".into()); + } + if value.chars().count() < 1usize { + return Err("shorter than 1 characters".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for RevokeDelegationForEndUserXIdempotencyKey { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for RevokeDelegationForEndUserXIdempotencyKey { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for RevokeDelegationForEndUserXIdempotencyKey { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for RevokeDelegationForEndUserXIdempotencyKey { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///`RevokeSpendPermissionAddress` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{40}$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct RevokeSpendPermissionAddress(::std::string::String); + impl ::std::ops::Deref for RevokeSpendPermissionAddress { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: RevokeSpendPermissionAddress) -> Self { + value.0 + } + } + impl ::std::convert::From<&RevokeSpendPermissionAddress> for RevokeSpendPermissionAddress { + fn from(value: &RevokeSpendPermissionAddress) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for RevokeSpendPermissionAddress { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for RevokeSpendPermissionAddress { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for RevokeSpendPermissionAddress { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for RevokeSpendPermissionAddress { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for RevokeSpendPermissionAddress { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -37052,6 +41475,9 @@ pub mod types { /// "$ref": "#/components/schemas/EvmAddressCriterion" /// }, /// { + /// "$ref": "#/components/schemas/EvmNetworkCriterion" + /// }, + /// { /// "$ref": "#/components/schemas/EvmDataCriterion" /// }, /// { @@ -37105,6 +41531,9 @@ pub mod types { /// "$ref": "#/components/schemas/EvmAddressCriterion" /// }, /// { + /// "$ref": "#/components/schemas/EvmNetworkCriterion" + /// }, + /// { /// "$ref": "#/components/schemas/EvmDataCriterion" /// }, /// { @@ -37119,6 +41548,7 @@ pub mod types { pub enum SendUserOperationCriteriaItem { EthValueCriterion(EthValueCriterion), EvmAddressCriterion(EvmAddressCriterion), + EvmNetworkCriterion(EvmNetworkCriterion), EvmDataCriterion(EvmDataCriterion), NetUsdChangeCriterion(NetUsdChangeCriterion), } @@ -37137,6 +41567,11 @@ pub mod types { Self::EvmAddressCriterion(value) } } + impl ::std::convert::From for SendUserOperationCriteriaItem { + fn from(value: EvmNetworkCriterion) -> Self { + Self::EvmNetworkCriterion(value) + } + } impl ::std::convert::From for SendUserOperationCriteriaItem { fn from(value: EvmDataCriterion) -> Self { Self::EvmDataCriterion(value) @@ -38061,6 +42496,409 @@ pub mod types { }) } } + ///Details specific to SEPA (Single Euro Payments Area) payment methods. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "Details specific to SEPA (Single Euro Payments Area) payment methods.", + /// "examples": [ + /// { + /// "asset": "eur", + /// "bankName": "ING Bank", + /// "bic": "INGBNL2A", + /// "ibanLast4": "4300" + /// } + /// ], + /// "type": "object", + /// "required": [ + /// "asset", + /// "bankName", + /// "bic", + /// "ibanLast4" + /// ], + /// "properties": { + /// "asset": { + /// "description": "The asset for this payment method. Always `eur` for SEPA.", + /// "examples": [ + /// "eur" + /// ], + /// "type": "string" + /// }, + /// "bankName": { + /// "description": "The name of the bank.", + /// "examples": [ + /// "ING Bank" + /// ], + /// "type": "string" + /// }, + /// "bic": { + /// "description": "The Bank Identifier Code (BIC) / SWIFT code.", + /// "examples": [ + /// "INGBNL2A" + /// ], + /// "type": "string", + /// "pattern": "^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$" + /// }, + /// "ibanLast4": { + /// "description": "The last 4 characters of the IBAN.", + /// "examples": [ + /// "4300" + /// ], + /// "type": "string", + /// "pattern": "^[A-Z0-9]{4}$" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct SepaDetails { + ///The asset for this payment method. Always `eur` for SEPA. + pub asset: ::std::string::String, + ///The name of the bank. + #[serde(rename = "bankName")] + pub bank_name: ::std::string::String, + ///The Bank Identifier Code (BIC) / SWIFT code. + pub bic: SepaDetailsBic, + ///The last 4 characters of the IBAN. + #[serde(rename = "ibanLast4")] + pub iban_last4: SepaDetailsIbanLast4, + } + impl ::std::convert::From<&SepaDetails> for SepaDetails { + fn from(value: &SepaDetails) -> Self { + value.clone() + } + } + impl SepaDetails { + pub fn builder() -> builder::SepaDetails { + Default::default() + } + } + ///The Bank Identifier Code (BIC) / SWIFT code. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The Bank Identifier Code (BIC) / SWIFT code.", + /// "examples": [ + /// "INGBNL2A" + /// ], + /// "type": "string", + /// "pattern": "^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct SepaDetailsBic(::std::string::String); + impl ::std::ops::Deref for SepaDetailsBic { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: SepaDetailsBic) -> Self { + value.0 + } + } + impl ::std::convert::From<&SepaDetailsBic> for SepaDetailsBic { + fn from(value: &SepaDetailsBic) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for SepaDetailsBic { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for SepaDetailsBic { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for SepaDetailsBic { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for SepaDetailsBic { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for SepaDetailsBic { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///The last 4 characters of the IBAN. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The last 4 characters of the IBAN.", + /// "examples": [ + /// "4300" + /// ], + /// "type": "string", + /// "pattern": "^[A-Z0-9]{4}$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct SepaDetailsIbanLast4(::std::string::String); + impl ::std::ops::Deref for SepaDetailsIbanLast4 { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: SepaDetailsIbanLast4) -> Self { + value.0 + } + } + impl ::std::convert::From<&SepaDetailsIbanLast4> for SepaDetailsIbanLast4 { + fn from(value: &SepaDetailsIbanLast4) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for SepaDetailsIbanLast4 { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| ::regress::Regex::new("^[A-Z0-9]{4}$").unwrap()); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^[A-Z0-9]{4}$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for SepaDetailsIbanLast4 { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for SepaDetailsIbanLast4 { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for SepaDetailsIbanLast4 { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for SepaDetailsIbanLast4 { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///A SEPA (Single Euro Payments Area) payment method linked to your entity. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "title": "SepaPaymentMethod", + /// "description": "A SEPA (Single Euro Payments Area) payment method linked to your entity.", + /// "examples": [ + /// { + /// "active": true, + /// "createdAt": "2024-01-15T10:30:00Z", + /// "paymentMethodId": "paymentMethod_abc12345-6789-0abc-def0-123456789abc", + /// "paymentRail": "sepa", + /// "sepa": { + /// "asset": "eur", + /// "bankName": "ING Bank", + /// "bic": "INGBNL2A", + /// "ibanLast4": "4300" + /// }, + /// "updatedAt": "2024-01-15T10:30:00Z" + /// } + /// ], + /// "type": "object", + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/PaymentMethodBase" + /// }, + /// { + /// "type": "object", + /// "required": [ + /// "paymentRail", + /// "sepa" + /// ], + /// "properties": { + /// "paymentRail": { + /// "description": "The payment rail for this payment method.", + /// "examples": [ + /// "sepa" + /// ], + /// "type": "string", + /// "enum": [ + /// "sepa" + /// ] + /// }, + /// "sepa": { + /// "description": "SEPA (Single Euro Payments Area) details.", + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/SepaDetails" + /// } + /// ] + /// } + /// } + /// } + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct SepaPaymentMethod { + ///Whether the payment method is active and can be used in transfers. A payment method may be inactive due to verification requirements or entity-level restrictions. + pub active: bool, + ///The timestamp when the payment method was created. + #[serde(rename = "createdAt")] + pub created_at: ::chrono::DateTime<::chrono::offset::Utc>, + #[serde(rename = "paymentMethodId")] + pub payment_method_id: PaymentMethodId, + ///The payment rail for this payment method. + #[serde(rename = "paymentRail")] + pub payment_rail: SepaPaymentMethodPaymentRail, + ///SEPA (Single Euro Payments Area) details. + pub sepa: SepaDetails, + ///The timestamp when the payment method was last updated. + #[serde(rename = "updatedAt")] + pub updated_at: ::chrono::DateTime<::chrono::offset::Utc>, + } + impl ::std::convert::From<&SepaPaymentMethod> for SepaPaymentMethod { + fn from(value: &SepaPaymentMethod) -> Self { + value.clone() + } + } + impl SepaPaymentMethod { + pub fn builder() -> builder::SepaPaymentMethod { + Default::default() + } + } + ///The payment rail for this payment method. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The payment rail for this payment method.", + /// "examples": [ + /// "sepa" + /// ], + /// "type": "string", + /// "enum": [ + /// "sepa" + /// ] + ///} + /// ``` + ///
+ #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum SepaPaymentMethodPaymentRail { + #[serde(rename = "sepa")] + Sepa, + } + impl ::std::convert::From<&Self> for SepaPaymentMethodPaymentRail { + fn from(value: &SepaPaymentMethodPaymentRail) -> Self { + value.clone() + } + } + impl ::std::fmt::Display for SepaPaymentMethodPaymentRail { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Sepa => f.write_str("sepa"), + } + } + } + impl ::std::str::FromStr for SepaPaymentMethodPaymentRail { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "sepa" => Ok(Self::Sepa), + _ => Err("invalid value".into()), + } + } + } + impl ::std::convert::TryFrom<&str> for SepaPaymentMethodPaymentRail { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for SepaPaymentMethodPaymentRail { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for SepaPaymentMethodPaymentRail { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } ///`SettleX402PaymentBody` /// ///
JSON schema @@ -50926,6 +55764,167 @@ pub mod types { value.parse() } } + ///`SubmitDepositTravelRuleTransferId` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "examples": [ + /// "transfer_af2937b0-9846-4fe7-bfe9-ccc22d935114" + /// ], + /// "type": "string", + /// "pattern": "^transfer_[a-f0-9\\-]{36}$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct SubmitDepositTravelRuleTransferId(::std::string::String); + impl ::std::ops::Deref for SubmitDepositTravelRuleTransferId { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: SubmitDepositTravelRuleTransferId) -> Self { + value.0 + } + } + impl ::std::convert::From<&SubmitDepositTravelRuleTransferId> + for SubmitDepositTravelRuleTransferId + { + fn from(value: &SubmitDepositTravelRuleTransferId) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for SubmitDepositTravelRuleTransferId { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^transfer_[a-f0-9\\-]{36}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^transfer_[a-f0-9\\-]{36}$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for SubmitDepositTravelRuleTransferId { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for SubmitDepositTravelRuleTransferId { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for SubmitDepositTravelRuleTransferId { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for SubmitDepositTravelRuleTransferId { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///`SubmitDepositTravelRuleXIdempotencyKey` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "type": "string", + /// "maxLength": 128, + /// "minLength": 1 + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct SubmitDepositTravelRuleXIdempotencyKey(::std::string::String); + impl ::std::ops::Deref for SubmitDepositTravelRuleXIdempotencyKey { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: SubmitDepositTravelRuleXIdempotencyKey) -> Self { + value.0 + } + } + impl ::std::convert::From<&SubmitDepositTravelRuleXIdempotencyKey> + for SubmitDepositTravelRuleXIdempotencyKey + { + fn from(value: &SubmitDepositTravelRuleXIdempotencyKey) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for SubmitDepositTravelRuleXIdempotencyKey { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + if value.chars().count() > 128usize { + return Err("longer than 128 characters".into()); + } + if value.chars().count() < 1usize { + return Err("shorter than 1 characters".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for SubmitDepositTravelRuleXIdempotencyKey { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for SubmitDepositTravelRuleXIdempotencyKey { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for SubmitDepositTravelRuleXIdempotencyKey { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for SubmitDepositTravelRuleXIdempotencyKey { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } ///`SupportedX402PaymentKindsResponse` /// ///
JSON schema @@ -51083,6 +56082,507 @@ pub mod types { Default::default() } } + ///Details specific to SWIFT (international wire) payment methods. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "Details specific to SWIFT (international wire) payment methods.", + /// "examples": [ + /// { + /// "accountLast4": "5678", + /// "asset": "eur", + /// "bankName": "Deutsche Bank", + /// "bic": "DEUTDEFF", + /// "ibanLast4": "5678" + /// } + /// ], + /// "type": "object", + /// "required": [ + /// "accountLast4", + /// "asset", + /// "bankName", + /// "bic" + /// ], + /// "properties": { + /// "accountLast4": { + /// "description": "The last 4 characters of the account identifier. For IBAN-based accounts (e.g., EU), this is the last 4 characters of the IBAN. For account number-based accounts (e.g., US), this is the last 4 digits of the account number.", + /// "examples": [ + /// "5678" + /// ], + /// "type": "string", + /// "pattern": "^[A-Z0-9]{4}$" + /// }, + /// "asset": { + /// "description": "The asset for this payment method (e.g., `eur`, `gbp`).", + /// "examples": [ + /// "eur" + /// ], + /// "type": "string" + /// }, + /// "bankName": { + /// "description": "The name of the bank.", + /// "examples": [ + /// "Deutsche Bank" + /// ], + /// "type": "string" + /// }, + /// "bic": { + /// "description": "The Bank Identifier Code (BIC) / SWIFT code.", + /// "examples": [ + /// "DEUTDEFF" + /// ], + /// "type": "string", + /// "pattern": "^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$" + /// }, + /// "ibanLast4": { + /// "description": "Deprecated: use `accountLast4` instead. The last 4 characters of the account identifier.", + /// "deprecated": true, + /// "examples": [ + /// "5678" + /// ], + /// "type": "string", + /// "pattern": "^[A-Z0-9]{4}$" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct SwiftDetails { + ///The last 4 characters of the account identifier. For IBAN-based accounts (e.g., EU), this is the last 4 characters of the IBAN. For account number-based accounts (e.g., US), this is the last 4 digits of the account number. + #[serde(rename = "accountLast4")] + pub account_last4: SwiftDetailsAccountLast4, + ///The asset for this payment method (e.g., `eur`, `gbp`). + pub asset: ::std::string::String, + ///The name of the bank. + #[serde(rename = "bankName")] + pub bank_name: ::std::string::String, + ///The Bank Identifier Code (BIC) / SWIFT code. + pub bic: SwiftDetailsBic, + ///Deprecated: use `accountLast4` instead. The last 4 characters of the account identifier. + #[serde( + rename = "ibanLast4", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub iban_last4: ::std::option::Option, + } + impl ::std::convert::From<&SwiftDetails> for SwiftDetails { + fn from(value: &SwiftDetails) -> Self { + value.clone() + } + } + impl SwiftDetails { + pub fn builder() -> builder::SwiftDetails { + Default::default() + } + } + ///The last 4 characters of the account identifier. For IBAN-based accounts (e.g., EU), this is the last 4 characters of the IBAN. For account number-based accounts (e.g., US), this is the last 4 digits of the account number. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The last 4 characters of the account identifier. For IBAN-based accounts (e.g., EU), this is the last 4 characters of the IBAN. For account number-based accounts (e.g., US), this is the last 4 digits of the account number.", + /// "examples": [ + /// "5678" + /// ], + /// "type": "string", + /// "pattern": "^[A-Z0-9]{4}$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct SwiftDetailsAccountLast4(::std::string::String); + impl ::std::ops::Deref for SwiftDetailsAccountLast4 { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: SwiftDetailsAccountLast4) -> Self { + value.0 + } + } + impl ::std::convert::From<&SwiftDetailsAccountLast4> for SwiftDetailsAccountLast4 { + fn from(value: &SwiftDetailsAccountLast4) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for SwiftDetailsAccountLast4 { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| ::regress::Regex::new("^[A-Z0-9]{4}$").unwrap()); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^[A-Z0-9]{4}$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for SwiftDetailsAccountLast4 { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for SwiftDetailsAccountLast4 { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for SwiftDetailsAccountLast4 { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for SwiftDetailsAccountLast4 { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///The Bank Identifier Code (BIC) / SWIFT code. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The Bank Identifier Code (BIC) / SWIFT code.", + /// "examples": [ + /// "DEUTDEFF" + /// ], + /// "type": "string", + /// "pattern": "^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct SwiftDetailsBic(::std::string::String); + impl ::std::ops::Deref for SwiftDetailsBic { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: SwiftDetailsBic) -> Self { + value.0 + } + } + impl ::std::convert::From<&SwiftDetailsBic> for SwiftDetailsBic { + fn from(value: &SwiftDetailsBic) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for SwiftDetailsBic { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for SwiftDetailsBic { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for SwiftDetailsBic { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for SwiftDetailsBic { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for SwiftDetailsBic { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///Deprecated: use `accountLast4` instead. The last 4 characters of the account identifier. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "Deprecated: use `accountLast4` instead. The last 4 characters of the account identifier.", + /// "deprecated": true, + /// "examples": [ + /// "5678" + /// ], + /// "type": "string", + /// "pattern": "^[A-Z0-9]{4}$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct SwiftDetailsIbanLast4(::std::string::String); + impl ::std::ops::Deref for SwiftDetailsIbanLast4 { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: SwiftDetailsIbanLast4) -> Self { + value.0 + } + } + impl ::std::convert::From<&SwiftDetailsIbanLast4> for SwiftDetailsIbanLast4 { + fn from(value: &SwiftDetailsIbanLast4) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for SwiftDetailsIbanLast4 { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| ::regress::Regex::new("^[A-Z0-9]{4}$").unwrap()); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^[A-Z0-9]{4}$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for SwiftDetailsIbanLast4 { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for SwiftDetailsIbanLast4 { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for SwiftDetailsIbanLast4 { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for SwiftDetailsIbanLast4 { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///A SWIFT (international wire) payment method linked to your entity. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "title": "SwiftPaymentMethod", + /// "description": "A SWIFT (international wire) payment method linked to your entity.", + /// "examples": [ + /// { + /// "active": true, + /// "createdAt": "2024-01-15T10:30:00Z", + /// "paymentMethodId": "paymentMethod_def45678-1234-5678-9abc-def012345678", + /// "paymentRail": "swift", + /// "swift": { + /// "accountLast4": "5678", + /// "asset": "eur", + /// "bankName": "Deutsche Bank", + /// "bic": "DEUTDEFF", + /// "ibanLast4": "5678" + /// }, + /// "updatedAt": "2024-01-15T10:30:00Z" + /// } + /// ], + /// "type": "object", + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/PaymentMethodBase" + /// }, + /// { + /// "type": "object", + /// "required": [ + /// "paymentRail", + /// "swift" + /// ], + /// "properties": { + /// "paymentRail": { + /// "description": "The payment rail for this payment method.", + /// "examples": [ + /// "swift" + /// ], + /// "type": "string", + /// "enum": [ + /// "swift" + /// ] + /// }, + /// "swift": { + /// "description": "SWIFT (international wire) details.", + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/SwiftDetails" + /// } + /// ] + /// } + /// } + /// } + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct SwiftPaymentMethod { + ///Whether the payment method is active and can be used in transfers. A payment method may be inactive due to verification requirements or entity-level restrictions. + pub active: bool, + ///The timestamp when the payment method was created. + #[serde(rename = "createdAt")] + pub created_at: ::chrono::DateTime<::chrono::offset::Utc>, + #[serde(rename = "paymentMethodId")] + pub payment_method_id: PaymentMethodId, + ///The payment rail for this payment method. + #[serde(rename = "paymentRail")] + pub payment_rail: SwiftPaymentMethodPaymentRail, + ///SWIFT (international wire) details. + pub swift: SwiftDetails, + ///The timestamp when the payment method was last updated. + #[serde(rename = "updatedAt")] + pub updated_at: ::chrono::DateTime<::chrono::offset::Utc>, + } + impl ::std::convert::From<&SwiftPaymentMethod> for SwiftPaymentMethod { + fn from(value: &SwiftPaymentMethod) -> Self { + value.clone() + } + } + impl SwiftPaymentMethod { + pub fn builder() -> builder::SwiftPaymentMethod { + Default::default() + } + } + ///The payment rail for this payment method. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The payment rail for this payment method.", + /// "examples": [ + /// "swift" + /// ], + /// "type": "string", + /// "enum": [ + /// "swift" + /// ] + ///} + /// ``` + ///
+ #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum SwiftPaymentMethodPaymentRail { + #[serde(rename = "swift")] + Swift, + } + impl ::std::convert::From<&Self> for SwiftPaymentMethodPaymentRail { + fn from(value: &SwiftPaymentMethodPaymentRail) -> Self { + value.clone() + } + } + impl ::std::fmt::Display for SwiftPaymentMethodPaymentRail { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Swift => f.write_str("swift"), + } + } + } + impl ::std::str::FromStr for SwiftPaymentMethodPaymentRail { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "swift" => Ok(Self::Swift), + _ => Err("invalid value".into()), + } + } + } + impl ::std::convert::TryFrom<&str> for SwiftPaymentMethodPaymentRail { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for SwiftPaymentMethodPaymentRail { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for SwiftPaymentMethodPaymentRail { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } ///The 0x-prefixed address that holds the `fromToken` balance and has the `Permit2` allowance set for the swap. /// ///
JSON schema @@ -51900,448 +57400,818 @@ pub mod types { }) } } - ///`UpdateEvmAccountAddress` + ///A Transfer represents all the information needed to execute a transfer and tracks the lifecycle of a transfer from initiation through completion or failure. /// ///
JSON schema /// /// ```json ///{ - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// "description": "A Transfer represents all the information needed to execute a transfer and tracks the lifecycle of a transfer from initiation through completion or failure.", + /// "type": "object", + /// "required": [ + /// "source", + /// "target" + /// ], + /// "properties": { + /// "completedAt": { + /// "description": "The date and time the transfer was completed.", + /// "examples": [ + /// "2025-01-01T00:05:00Z" + /// ], + /// "type": "string", + /// "format": "date-time" + /// }, + /// "createdAt": { + /// "description": "The date and time the transfer was created. Required when validateOnly is false.", + /// "examples": [ + /// "2025-01-01T00:00:00Z" + /// ], + /// "type": "string", + /// "format": "date-time" + /// }, + /// "details": { + /// "$ref": "#/components/schemas/TransferDetails" + /// }, + /// "estimate": { + /// "$ref": "#/components/schemas/TransferEstimate" + /// }, + /// "exchangeRate": { + /// "$ref": "#/components/schemas/TransferExchangeRate" + /// }, + /// "executedAt": { + /// "description": "The date and time the transfer was executed and moved to processing. Only present when status has progressed beyond `quoted`.", + /// "examples": [ + /// "2025-01-01T00:01:30Z" + /// ], + /// "type": "string", + /// "format": "date-time" + /// }, + /// "expiresAt": { + /// "description": "The date and time when this transfer will expire if not executed. Only present for `quoted` status. A new transfer must be created to obtain an updated quote after expiration. Required when validateOnly is false.", + /// "examples": [ + /// "2025-01-01T00:15:00Z" + /// ], + /// "type": "string", + /// "format": "date-time" + /// }, + /// "failureReason": { + /// "description": "The reason for failure, if the transfer failed. Only present when status is `failed`.", + /// "examples": [ + /// "Insufficient balance to complete this transfer." + /// ], + /// "type": "string" + /// }, + /// "fees": { + /// "$ref": "#/components/schemas/TransferFees" + /// }, + /// "metadata": { + /// "$ref": "#/components/schemas/Metadata" + /// }, + /// "source": { + /// "$ref": "#/components/schemas/TransferSource" + /// }, + /// "sourceAmount": { + /// "description": "The amount of the source asset that will be transferred out, as a decimal string in standard unit denomination.", + /// "examples": [ + /// "103.50" + /// ], + /// "type": "string" + /// }, + /// "sourceAsset": { + /// "description": "The asset symbol of the source amount.", + /// "examples": [ + /// "usd" + /// ], + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/Asset" + /// } + /// ] + /// }, + /// "status": { + /// "$ref": "#/components/schemas/TransferStatus" + /// }, + /// "target": { + /// "$ref": "#/components/schemas/TransferTarget" + /// }, + /// "targetAmount": { + /// "description": "The amount of the target asset that will be received, as a decimal string in standard unit denomination.", + /// "examples": [ + /// "100.00" + /// ], + /// "type": "string" + /// }, + /// "targetAsset": { + /// "description": "The asset symbol of the target amount.", + /// "examples": [ + /// "usdc" + /// ], + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/Asset" + /// } + /// ] + /// }, + /// "transferId": { + /// "description": "The ID of the transfer. Required when validateOnly is false.", + /// "examples": [ + /// "transfer_af2937b0-9846-4fe7-bfe9-ccc22d935114" + /// ], + /// "type": "string" + /// }, + /// "updatedAt": { + /// "description": "The date and time the transfer was last updated. Required when validateOnly is false.", + /// "examples": [ + /// "2025-01-01T00:00:00Z" + /// ], + /// "type": "string", + /// "format": "date-time" + /// } + /// } ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct UpdateEvmAccountAddress(::std::string::String); - impl ::std::ops::Deref for UpdateEvmAccountAddress { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } - } - impl ::std::convert::From for ::std::string::String { - fn from(value: UpdateEvmAccountAddress) -> Self { - value.0 - } + #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct Transfer { + ///The date and time the transfer was completed. + #[serde( + rename = "completedAt", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub completed_at: ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + ///The date and time the transfer was created. Required when validateOnly is false. + #[serde( + rename = "createdAt", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub created_at: ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub details: ::std::option::Option, + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub estimate: ::std::option::Option, + #[serde( + rename = "exchangeRate", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub exchange_rate: ::std::option::Option, + ///The date and time the transfer was executed and moved to processing. Only present when status has progressed beyond `quoted`. + #[serde( + rename = "executedAt", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub executed_at: ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + ///The date and time when this transfer will expire if not executed. Only present for `quoted` status. A new transfer must be created to obtain an updated quote after expiration. Required when validateOnly is false. + #[serde( + rename = "expiresAt", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub expires_at: ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + ///The reason for failure, if the transfer failed. Only present when status is `failed`. + #[serde( + rename = "failureReason", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub failure_reason: ::std::option::Option<::std::string::String>, + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub fees: ::std::option::Option, + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub metadata: ::std::option::Option, + pub source: TransferSource, + ///The amount of the source asset that will be transferred out, as a decimal string in standard unit denomination. + #[serde( + rename = "sourceAmount", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub source_amount: ::std::option::Option<::std::string::String>, + ///The asset symbol of the source amount. + #[serde( + rename = "sourceAsset", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub source_asset: ::std::option::Option, + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub status: ::std::option::Option, + pub target: TransferTarget, + ///The amount of the target asset that will be received, as a decimal string in standard unit denomination. + #[serde( + rename = "targetAmount", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub target_amount: ::std::option::Option<::std::string::String>, + ///The asset symbol of the target amount. + #[serde( + rename = "targetAsset", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub target_asset: ::std::option::Option, + ///The ID of the transfer. Required when validateOnly is false. + #[serde( + rename = "transferId", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub transfer_id: ::std::option::Option<::std::string::String>, + ///The date and time the transfer was last updated. Required when validateOnly is false. + #[serde( + rename = "updatedAt", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub updated_at: ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, } - impl ::std::convert::From<&UpdateEvmAccountAddress> for UpdateEvmAccountAddress { - fn from(value: &UpdateEvmAccountAddress) -> Self { + impl ::std::convert::From<&Transfer> for Transfer { + fn from(value: &Transfer) -> Self { value.clone() } } - impl ::std::str::FromStr for UpdateEvmAccountAddress { - type Err = self::error::ConversionError; - fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() - }); - if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); - } - Ok(Self(value.to_string())) - } - } - impl ::std::convert::TryFrom<&str> for UpdateEvmAccountAddress { - type Error = self::error::ConversionError; - fn try_from(value: &str) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<&::std::string::String> for UpdateEvmAccountAddress { - type Error = self::error::ConversionError; - fn try_from( - value: &::std::string::String, - ) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<::std::string::String> for UpdateEvmAccountAddress { - type Error = self::error::ConversionError; - fn try_from( - value: ::std::string::String, - ) -> ::std::result::Result { - value.parse() - } - } - impl<'de> ::serde::Deserialize<'de> for UpdateEvmAccountAddress { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) + impl Transfer { + pub fn builder() -> builder::Transfer { + Default::default() } } - ///`UpdateEvmAccountBody` + ///Additional details about the transfer. For example, if the transfer was sent to a deposit destination, the information about that destination will be included in this field. /// ///
JSON schema /// /// ```json ///{ + /// "description": "Additional details about the transfer. For example, if the transfer was sent to a deposit destination, the information about that destination will be included in this field.", + /// "examples": [ + /// { + /// "depositDestination": { + /// "id": "depositDestination_af2937b0-9846-4fe7-bfe9-ccc22d935114" + /// }, + /// "onchainTransactions": [ + /// { + /// "network": "base", + /// "transactionHash": "0x363cd3b3d4f49497cf5076150cd709307b90e9fc897fdd623546ea7b9313cecb" + /// } + /// ] + /// } + /// ], /// "type": "object", /// "properties": { - /// "accountPolicy": { - /// "description": "The ID of the account-level policy to apply to the account, or an empty string to unset attached policy.", + /// "depositDestination": { + /// "$ref": "#/components/schemas/DepositDestinationReference" + /// }, + /// "onchainTransactions": { + /// "description": "The onchain transactions associated with the transfer.", /// "examples": [ - /// "123e4567-e89b-12d3-a456-426614174000" + /// [ + /// { + /// "network": "base", + /// "transactionHash": "0x363cd3b3d4f49497cf5076150cd709307b90e9fc897fdd623546ea7b9313cecb" + /// } + /// ] /// ], - /// "type": "string", - /// "pattern": "(^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$)|(^$)", - /// "x-audience": "public" + /// "type": "array", + /// "items": { + /// "description": "An onchain transaction associated with the transfer.", + /// "type": "object", + /// "required": [ + /// "network", + /// "transactionHash" + /// ], + /// "properties": { + /// "network": { + /// "$ref": "#/components/schemas/Network" + /// }, + /// "transactionHash": { + /// "description": "The transaction hash.", + /// "examples": [ + /// "0x363cd3b3d4f49497cf5076150cd709307b90e9fc897fdd623546ea7b9313cecb" + /// ], + /// "type": "string" + /// } + /// } + /// } /// }, - /// "name": { - /// "description": "An optional name for the account.\nAccount names can consist of alphanumeric characters and hyphens, and be between 2 and 36 characters long.\nAccount names must be unique across all EVM accounts in the developer's CDP Project.", + /// "travelRule": { + /// "description": "Travel rule compliance status for deposit transfers. Present when the transfer requires travel rule information.", /// "examples": [ - /// "my-wallet" + /// { + /// "status": "incomplete", + /// "statusMessage": "Originator date of birth is required." + /// } /// ], - /// "type": "string", - /// "pattern": "^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$" + /// "type": "object", + /// "properties": { + /// "status": { + /// "$ref": "#/components/schemas/TravelRuleStatus" + /// }, + /// "statusMessage": { + /// "description": "Additional details about the current travel rule status. For example, when status is `incomplete`, this may indicate the specific missing information required to proceed.", + /// "examples": [ + /// "Originator date of birth is required." + /// ], + /// "type": "string" + /// } + /// } /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct UpdateEvmAccountBody { - ///The ID of the account-level policy to apply to the account, or an empty string to unset attached policy. + pub struct TransferDetails { #[serde( - rename = "accountPolicy", + rename = "depositDestination", default, skip_serializing_if = "::std::option::Option::is_none" )] - pub account_policy: ::std::option::Option, - /**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.*/ - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub name: ::std::option::Option, + pub deposit_destination: ::std::option::Option, + ///The onchain transactions associated with the transfer. + #[serde( + rename = "onchainTransactions", + default, + skip_serializing_if = "::std::vec::Vec::is_empty" + )] + pub onchain_transactions: ::std::vec::Vec, + #[serde( + rename = "travelRule", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub travel_rule: ::std::option::Option, } - impl ::std::convert::From<&UpdateEvmAccountBody> for UpdateEvmAccountBody { - fn from(value: &UpdateEvmAccountBody) -> Self { + impl ::std::convert::From<&TransferDetails> for TransferDetails { + fn from(value: &TransferDetails) -> Self { value.clone() } } - impl ::std::default::Default for UpdateEvmAccountBody { + impl ::std::default::Default for TransferDetails { fn default() -> Self { Self { - account_policy: Default::default(), - name: Default::default(), + deposit_destination: Default::default(), + onchain_transactions: Default::default(), + travel_rule: Default::default(), } } } - impl UpdateEvmAccountBody { - pub fn builder() -> builder::UpdateEvmAccountBody { + impl TransferDetails { + pub fn builder() -> builder::TransferDetails { Default::default() } } - ///The ID of the account-level policy to apply to the account, or an empty string to unset attached policy. + ///An onchain transaction associated with the transfer. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The ID of the account-level policy to apply to the account, or an empty string to unset attached policy.", - /// "examples": [ - /// "123e4567-e89b-12d3-a456-426614174000" + /// "description": "An onchain transaction associated with the transfer.", + /// "type": "object", + /// "required": [ + /// "network", + /// "transactionHash" /// ], - /// "type": "string", - /// "pattern": "(^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$)|(^$)", - /// "x-audience": "public" + /// "properties": { + /// "network": { + /// "$ref": "#/components/schemas/Network" + /// }, + /// "transactionHash": { + /// "description": "The transaction hash.", + /// "examples": [ + /// "0x363cd3b3d4f49497cf5076150cd709307b90e9fc897fdd623546ea7b9313cecb" + /// ], + /// "type": "string" + /// } + /// } ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct UpdateEvmAccountBodyAccountPolicy(::std::string::String); - impl ::std::ops::Deref for UpdateEvmAccountBodyAccountPolicy { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } - } - impl ::std::convert::From for ::std::string::String { - fn from(value: UpdateEvmAccountBodyAccountPolicy) -> Self { - value.0 - } + #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct TransferDetailsOnchainTransactionsItem { + pub network: Network, + ///The transaction hash. + #[serde(rename = "transactionHash")] + pub transaction_hash: ::std::string::String, } - impl ::std::convert::From<&UpdateEvmAccountBodyAccountPolicy> - for UpdateEvmAccountBodyAccountPolicy + impl ::std::convert::From<&TransferDetailsOnchainTransactionsItem> + for TransferDetailsOnchainTransactionsItem { - fn from(value: &UpdateEvmAccountBodyAccountPolicy) -> Self { + fn from(value: &TransferDetailsOnchainTransactionsItem) -> Self { value.clone() } } - impl ::std::str::FromStr for UpdateEvmAccountBodyAccountPolicy { - type Err = self::error::ConversionError; - fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new( - || { - ::regress::Regex::new( - "(^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$)|(^$)", - ) - .unwrap() - }, - ); - if PATTERN.find(value).is_none() { - return Err( - "doesn't match pattern \"(^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$)|(^$)\"" - .into(), - ); - } - Ok(Self(value.to_string())) - } - } - impl ::std::convert::TryFrom<&str> for UpdateEvmAccountBodyAccountPolicy { - type Error = self::error::ConversionError; - fn try_from(value: &str) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<&::std::string::String> for UpdateEvmAccountBodyAccountPolicy { - type Error = self::error::ConversionError; - fn try_from( - value: &::std::string::String, - ) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<::std::string::String> for UpdateEvmAccountBodyAccountPolicy { - type Error = self::error::ConversionError; - fn try_from( - value: ::std::string::String, - ) -> ::std::result::Result { - value.parse() - } - } - impl<'de> ::serde::Deserialize<'de> for UpdateEvmAccountBodyAccountPolicy { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) + impl TransferDetailsOnchainTransactionsItem { + pub fn builder() -> builder::TransferDetailsOnchainTransactionsItem { + Default::default() } } - /**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.*/ + ///Travel rule compliance status for deposit transfers. Present when the transfer requires travel rule information. /// ///
JSON schema /// /// ```json ///{ - /// "description": "An optional name for the account.\nAccount names can consist of alphanumeric characters and hyphens, and be between 2 and 36 characters long.\nAccount names must be unique across all EVM accounts in the developer's CDP Project.", + /// "description": "Travel rule compliance status for deposit transfers. Present when the transfer requires travel rule information.", /// "examples": [ - /// "my-wallet" + /// { + /// "status": "incomplete", + /// "statusMessage": "Originator date of birth is required." + /// } /// ], - /// "type": "string", - /// "pattern": "^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$" + /// "type": "object", + /// "properties": { + /// "status": { + /// "$ref": "#/components/schemas/TravelRuleStatus" + /// }, + /// "statusMessage": { + /// "description": "Additional details about the current travel rule status. For example, when status is `incomplete`, this may indicate the specific missing information required to proceed.", + /// "examples": [ + /// "Originator date of birth is required." + /// ], + /// "type": "string" + /// } + /// } ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct UpdateEvmAccountBodyName(::std::string::String); - impl ::std::ops::Deref for UpdateEvmAccountBodyName { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } - } - impl ::std::convert::From for ::std::string::String { - fn from(value: UpdateEvmAccountBodyName) -> Self { - value.0 - } + #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct TransferDetailsTravelRule { + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub status: ::std::option::Option, + ///Additional details about the current travel rule status. For example, when status is `incomplete`, this may indicate the specific missing information required to proceed. + #[serde( + rename = "statusMessage", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub status_message: ::std::option::Option<::std::string::String>, } - impl ::std::convert::From<&UpdateEvmAccountBodyName> for UpdateEvmAccountBodyName { - fn from(value: &UpdateEvmAccountBodyName) -> Self { + impl ::std::convert::From<&TransferDetailsTravelRule> for TransferDetailsTravelRule { + fn from(value: &TransferDetailsTravelRule) -> Self { value.clone() } } - impl ::std::str::FromStr for UpdateEvmAccountBodyName { - type Err = self::error::ConversionError; - fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$").unwrap() - }); - if PATTERN.find(value).is_none() { - return Err( - "doesn't match pattern \"^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$\"".into(), - ); + impl ::std::default::Default for TransferDetailsTravelRule { + fn default() -> Self { + Self { + status: Default::default(), + status_message: Default::default(), } - Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for UpdateEvmAccountBodyName { - type Error = self::error::ConversionError; - fn try_from(value: &str) -> ::std::result::Result { - value.parse() + impl TransferDetailsTravelRule { + pub fn builder() -> builder::TransferDetailsTravelRule { + Default::default() } } - impl ::std::convert::TryFrom<&::std::string::String> for UpdateEvmAccountBodyName { - type Error = self::error::ConversionError; - fn try_from( - value: &::std::string::String, - ) -> ::std::result::Result { - value.parse() - } + /**A point-in-time snapshot of estimated values for a transfer where exact amounts cannot be locked in at quote time (e.g., when the executed rate is determined at execution time and moves with the market). + + Present in both pre-execution and post-execution states: + * **Quoted state:** top-level fields whose values cannot be guaranteed are absent; + `estimate` holds their estimated values. + + * **Completed state:** top-level fields contain the actual executed values; + `estimate` is retained as an immutable audit snapshot of the pre-execution estimate.*/ + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "A point-in-time snapshot of estimated values for a transfer where exact amounts cannot be locked in at quote time (e.g., when the executed rate is determined at execution time and moves with the market).\n\nPresent in both pre-execution and post-execution states:\n* **Quoted state:** top-level fields whose values cannot be guaranteed are absent;\n `estimate` holds their estimated values.\n\n* **Completed state:** top-level fields contain the actual executed values;\n `estimate` is retained as an immutable audit snapshot of the pre-execution estimate.", + /// "examples": [ + /// { + /// "estimatedAt": "2023-10-08T14:30:00Z", + /// "exchangeRate": { + /// "rate": "0.85", + /// "sourceAsset": "usdc", + /// "targetAsset": "eur" + /// }, + /// "fees": [ + /// { + /// "amount": "0.01", + /// "asset": "usdc", + /// "type": "conversion" + /// } + /// ], + /// "targetAmount": "85.00", + /// "targetAsset": "eur" + /// } + /// ], + /// "type": "object", + /// "required": [ + /// "estimatedAt" + /// ], + /// "properties": { + /// "estimatedAt": { + /// "description": "The date and time when this estimate was captured.", + /// "examples": [ + /// "2023-10-08T14:30:00Z" + /// ], + /// "type": "string", + /// "format": "date-time" + /// }, + /// "exchangeRate": { + /// "$ref": "#/components/schemas/TransferExchangeRate" + /// }, + /// "fees": { + /// "$ref": "#/components/schemas/TransferFees" + /// }, + /// "targetAmount": { + /// "description": "Estimated amount of the target asset that will be received, as a decimal string in standard unit denomination.", + /// "examples": [ + /// "85.00" + /// ], + /// "type": "string" + /// }, + /// "targetAsset": { + /// "description": "The asset symbol of the estimated target amount.", + /// "examples": [ + /// "eur" + /// ], + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/Asset" + /// } + /// ] + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct TransferEstimate { + ///The date and time when this estimate was captured. + #[serde(rename = "estimatedAt")] + pub estimated_at: ::chrono::DateTime<::chrono::offset::Utc>, + #[serde( + rename = "exchangeRate", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub exchange_rate: ::std::option::Option, + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub fees: ::std::option::Option, + ///Estimated amount of the target asset that will be received, as a decimal string in standard unit denomination. + #[serde( + rename = "targetAmount", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub target_amount: ::std::option::Option<::std::string::String>, + ///The asset symbol of the estimated target amount. + #[serde( + rename = "targetAsset", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub target_asset: ::std::option::Option, } - impl ::std::convert::TryFrom<::std::string::String> for UpdateEvmAccountBodyName { - type Error = self::error::ConversionError; - fn try_from( - value: ::std::string::String, - ) -> ::std::result::Result { - value.parse() + impl ::std::convert::From<&TransferEstimate> for TransferEstimate { + fn from(value: &TransferEstimate) -> Self { + value.clone() } } - impl<'de> ::serde::Deserialize<'de> for UpdateEvmAccountBodyName { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) + impl TransferEstimate { + pub fn builder() -> builder::TransferEstimate { + Default::default() } } - ///`UpdateEvmAccountXIdempotencyKey` + ///Exchange rate information for currency conversion. The rate indicates how much of the target asset is equivalent to one unit of the source asset. /// ///
JSON schema /// /// ```json ///{ - /// "type": "string", - /// "maxLength": 128, - /// "minLength": 1 + /// "description": "Exchange rate information for currency conversion. The rate indicates how much of the target asset is equivalent to one unit of the source asset.", + /// "examples": [ + /// { + /// "rate": "1", + /// "sourceAsset": "usd", + /// "targetAsset": "usdc" + /// } + /// ], + /// "type": "object", + /// "required": [ + /// "rate", + /// "sourceAsset", + /// "targetAsset" + /// ], + /// "properties": { + /// "rate": { + /// "description": "The exchange rate value as a decimal string. Indicates how many units of the target asset equal one unit of the source asset.", + /// "examples": [ + /// "1" + /// ], + /// "type": "string" + /// }, + /// "sourceAsset": { + /// "description": "The asset being converted from.", + /// "examples": [ + /// "usd" + /// ], + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/Asset" + /// } + /// ] + /// }, + /// "targetAsset": { + /// "description": "The asset being converted to.", + /// "examples": [ + /// "usdc" + /// ], + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/Asset" + /// } + /// ] + /// } + /// } ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct UpdateEvmAccountXIdempotencyKey(::std::string::String); - impl ::std::ops::Deref for UpdateEvmAccountXIdempotencyKey { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } - } - impl ::std::convert::From for ::std::string::String { - fn from(value: UpdateEvmAccountXIdempotencyKey) -> Self { - value.0 - } + #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct TransferExchangeRate { + ///The exchange rate value as a decimal string. Indicates how many units of the target asset equal one unit of the source asset. + pub rate: ::std::string::String, + ///The asset being converted from. + #[serde(rename = "sourceAsset")] + pub source_asset: Asset, + ///The asset being converted to. + #[serde(rename = "targetAsset")] + pub target_asset: Asset, } - impl ::std::convert::From<&UpdateEvmAccountXIdempotencyKey> for UpdateEvmAccountXIdempotencyKey { - fn from(value: &UpdateEvmAccountXIdempotencyKey) -> Self { + impl ::std::convert::From<&TransferExchangeRate> for TransferExchangeRate { + fn from(value: &TransferExchangeRate) -> Self { value.clone() } } - impl ::std::str::FromStr for UpdateEvmAccountXIdempotencyKey { - type Err = self::error::ConversionError; - fn from_str(value: &str) -> ::std::result::Result { - if value.chars().count() > 128usize { - return Err("longer than 128 characters".into()); - } - if value.chars().count() < 1usize { - return Err("shorter than 1 characters".into()); - } - Ok(Self(value.to_string())) - } - } - impl ::std::convert::TryFrom<&str> for UpdateEvmAccountXIdempotencyKey { - type Error = self::error::ConversionError; - fn try_from(value: &str) -> ::std::result::Result { - value.parse() + impl TransferExchangeRate { + pub fn builder() -> builder::TransferExchangeRate { + Default::default() } } - impl ::std::convert::TryFrom<&::std::string::String> for UpdateEvmAccountXIdempotencyKey { - type Error = self::error::ConversionError; - fn try_from( - value: &::std::string::String, - ) -> ::std::result::Result { - value.parse() - } + ///A single fee for a transfer. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "A single fee for a transfer.", + /// "type": "object", + /// "required": [ + /// "amount", + /// "asset", + /// "type" + /// ], + /// "properties": { + /// "amount": { + /// "description": "The amount of the fee in units of the asset specified by `asset`.", + /// "examples": [ + /// "1500000" + /// ], + /// "type": "string" + /// }, + /// "asset": { + /// "description": "The asset symbol.", + /// "examples": [ + /// "usd" + /// ], + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/Asset" + /// } + /// ] + /// }, + /// "type": { + /// "description": "The type of the fee, indicating its purpose.", + /// "examples": [ + /// "network" + /// ], + /// "type": "string", + /// "enum": [ + /// "bank", + /// "conversion", + /// "network", + /// "other" + /// ], + /// "x-enum-varnames": [ + /// "BankFee", + /// "ConversionFee", + /// "NetworkFee", + /// "OtherFee" + /// ] + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct TransferFee { + ///The amount of the fee in units of the asset specified by `asset`. + pub amount: ::std::string::String, + ///The asset symbol. + pub asset: Asset, + ///The type of the fee, indicating its purpose. + #[serde(rename = "type")] + pub type_: TransferFeeType, } - impl ::std::convert::TryFrom<::std::string::String> for UpdateEvmAccountXIdempotencyKey { - type Error = self::error::ConversionError; - fn try_from( - value: ::std::string::String, - ) -> ::std::result::Result { - value.parse() + impl ::std::convert::From<&TransferFee> for TransferFee { + fn from(value: &TransferFee) -> Self { + value.clone() } } - impl<'de> ::serde::Deserialize<'de> for UpdateEvmAccountXIdempotencyKey { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) + impl TransferFee { + pub fn builder() -> builder::TransferFee { + Default::default() } } - ///`UpdateEvmSmartAccountAddress` + ///The type of the fee, indicating its purpose. /// ///
JSON schema /// /// ```json ///{ + /// "description": "The type of the fee, indicating its purpose.", + /// "examples": [ + /// "network" + /// ], /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// "enum": [ + /// "bank", + /// "conversion", + /// "network", + /// "other" + /// ], + /// "x-enum-varnames": [ + /// "BankFee", + /// "ConversionFee", + /// "NetworkFee", + /// "OtherFee" + /// ] ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct UpdateEvmSmartAccountAddress(::std::string::String); - impl ::std::ops::Deref for UpdateEvmSmartAccountAddress { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } + #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum TransferFeeType { + #[serde(rename = "bank")] + Bank, + #[serde(rename = "conversion")] + Conversion, + #[serde(rename = "network")] + Network, + #[serde(rename = "other")] + Other, } - impl ::std::convert::From for ::std::string::String { - fn from(value: UpdateEvmSmartAccountAddress) -> Self { - value.0 + impl ::std::convert::From<&Self> for TransferFeeType { + fn from(value: &TransferFeeType) -> Self { + value.clone() } } - impl ::std::convert::From<&UpdateEvmSmartAccountAddress> for UpdateEvmSmartAccountAddress { - fn from(value: &UpdateEvmSmartAccountAddress) -> Self { - value.clone() + impl ::std::fmt::Display for TransferFeeType { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Bank => f.write_str("bank"), + Self::Conversion => f.write_str("conversion"), + Self::Network => f.write_str("network"), + Self::Other => f.write_str("other"), + } } } - impl ::std::str::FromStr for UpdateEvmSmartAccountAddress { + impl ::std::str::FromStr for TransferFeeType { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() - }); - if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); + match value { + "bank" => Ok(Self::Bank), + "conversion" => Ok(Self::Conversion), + "network" => Ok(Self::Network), + "other" => Ok(Self::Other), + _ => Err("invalid value".into()), } - Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for UpdateEvmSmartAccountAddress { + impl ::std::convert::TryFrom<&str> for TransferFeeType { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for UpdateEvmSmartAccountAddress { + impl ::std::convert::TryFrom<&::std::string::String> for TransferFeeType { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -52349,7 +58219,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for UpdateEvmSmartAccountAddress { + impl ::std::convert::TryFrom<::std::string::String> for TransferFeeType { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -52357,121 +58227,261 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for UpdateEvmSmartAccountAddress { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) + /**The fees associated with this transfer. Different transfer types have different fee structures. + + **NOTE:** These examples are not exhaustive. + + Common examples: + * **Crypto transfers**: Network fees (gas) paid in the native token + * **Fiat conversions**: Processing fees + exchange fees in USD + * **Wire transfers**: Wire fees ($15) + processing fees ($5) in USD + * **Crypto conversions**: Spread fees paid in the source asset.*/ + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The fees associated with this transfer. Different transfer types have different fee structures.\n\n**NOTE:** These examples are not exhaustive.\n\nCommon examples:\n* **Crypto transfers**: Network fees (gas) paid in the native token\n* **Fiat conversions**: Processing fees + exchange fees in USD\n* **Wire transfers**: Wire fees ($15) + processing fees ($5) in USD\n* **Crypto conversions**: Spread fees paid in the source asset.", + /// "examples": [ + /// [ + /// { + /// "amount": "20", + /// "asset": "usd", + /// "type": "bank" + /// }, + /// { + /// "amount": "1.00", + /// "asset": "usdc", + /// "type": "conversion" + /// }, + /// { + /// "amount": "0.01", + /// "asset": "usdc", + /// "type": "network" + /// } + /// ] + /// ], + /// "type": "array", + /// "items": { + /// "$ref": "#/components/schemas/TransferFee" + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + #[serde(transparent)] + pub struct TransferFees(pub ::std::vec::Vec); + impl ::std::ops::Deref for TransferFees { + type Target = ::std::vec::Vec; + fn deref(&self) -> &::std::vec::Vec { + &self.0 } } - ///`UpdateEvmSmartAccountBody` + impl ::std::convert::From for ::std::vec::Vec { + fn from(value: TransferFees) -> Self { + value.0 + } + } + impl ::std::convert::From<&TransferFees> for TransferFees { + fn from(value: &TransferFees) -> Self { + value.clone() + } + } + impl ::std::convert::From<::std::vec::Vec> for TransferFees { + fn from(value: ::std::vec::Vec) -> Self { + Self(value) + } + } + ///A request to create a transfer. /// ///
JSON schema /// /// ```json ///{ + /// "description": "A request to create a transfer.", /// "type": "object", + /// "required": [ + /// "amount", + /// "asset", + /// "execute", + /// "source", + /// "target" + /// ], /// "properties": { - /// "name": { - /// "description": "An optional name for the smart account.\nAccount names can consist of alphanumeric characters and hyphens, and be between 2 and 36 characters long.\nAccount names must be unique across all EVM smart accounts in the developer's CDP Project.", + /// "amount": { + /// "description": "The amount of the transfer, as a decimal string in standard unit denomination of the asset specified by `asset` (e.g., \"100.00\" for 100 USD, \"0.05\" for 0.05 ETH).", /// "examples": [ - /// "my-smart-account" + /// "100.00" + /// ], + /// "type": "string" + /// }, + /// "amountType": { + /// "description": "Specifies whether the given amount is to be received by the target or taken from the source.\n\n- `target`: The transfer `target` receives the exact value specified in `amount`. Fees are added to the amount taken from the transfer `source`.\n- `source`: The transfer `target` receives the value specified in `amount`, minus any fees.\n", + /// "default": "source", + /// "examples": [ + /// "source" /// ], /// "type": "string", - /// "pattern": "^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$" + /// "enum": [ + /// "target", + /// "source" + /// ] + /// }, + /// "asset": { + /// "description": "The symbol of the asset for the amount. This must be one of the assets of the source or target.", + /// "examples": [ + /// "usd" + /// ], + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/Asset" + /// } + /// ] + /// }, + /// "execute": { + /// "description": "Whether to immediately execute the transfer. If false, the transfer will be created in quoted status and must be executed manually via the /execute endpoint.", + /// "examples": [ + /// true + /// ], + /// "type": "boolean" + /// }, + /// "metadata": { + /// "$ref": "#/components/schemas/Metadata" + /// }, + /// "source": { + /// "$ref": "#/components/schemas/CreateTransferSource" + /// }, + /// "target": { + /// "$ref": "#/components/schemas/TransferTarget" + /// }, + /// "travelRule": { + /// "$ref": "#/components/schemas/TravelRule" + /// }, + /// "validateOnly": { + /// "description": "If true, validates the transfer without initiating it. If the request is valid, a 2xx will be returned. If the request is invalid, a 4xx error will be returned. The response will include an errorType, for e.g. invalid_target if the specified target cannot receive funds.", + /// "default": false, + /// "examples": [ + /// false + /// ], + /// "type": "boolean" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct UpdateEvmSmartAccountBody { - /**An optional name for the smart 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 smart accounts in the developer's CDP Project.*/ + pub struct TransferRequest { + ///The amount of the transfer, as a decimal string in standard unit denomination of the asset specified by `asset` (e.g., "100.00" for 100 USD, "0.05" for 0.05 ETH). + pub amount: ::std::string::String, + /**Specifies whether the given amount is to be received by the target or taken from the source. + + - `target`: The transfer `target` receives the exact value specified in `amount`. Fees are added to the amount taken from the transfer `source`. + - `source`: The transfer `target` receives the value specified in `amount`, minus any fees. + */ + #[serde( + rename = "amountType", + default = "defaults::transfer_request_amount_type" + )] + pub amount_type: TransferRequestAmountType, + ///The symbol of the asset for the amount. This must be one of the assets of the source or target. + pub asset: Asset, + ///Whether to immediately execute the transfer. If false, the transfer will be created in quoted status and must be executed manually via the /execute endpoint. + pub execute: bool, #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub name: ::std::option::Option, + pub metadata: ::std::option::Option, + pub source: CreateTransferSource, + pub target: TransferTarget, + #[serde( + rename = "travelRule", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub travel_rule: ::std::option::Option, + ///If true, validates the transfer without initiating it. If the request is valid, a 2xx will be returned. If the request is invalid, a 4xx error will be returned. The response will include an errorType, for e.g. invalid_target if the specified target cannot receive funds. + #[serde(rename = "validateOnly", default)] + pub validate_only: bool, } - impl ::std::convert::From<&UpdateEvmSmartAccountBody> for UpdateEvmSmartAccountBody { - fn from(value: &UpdateEvmSmartAccountBody) -> Self { + impl ::std::convert::From<&TransferRequest> for TransferRequest { + fn from(value: &TransferRequest) -> Self { value.clone() } } - impl ::std::default::Default for UpdateEvmSmartAccountBody { - fn default() -> Self { - Self { - name: Default::default(), - } - } - } - impl UpdateEvmSmartAccountBody { - pub fn builder() -> builder::UpdateEvmSmartAccountBody { + impl TransferRequest { + pub fn builder() -> builder::TransferRequest { Default::default() } } - /**An optional name for the smart 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 smart accounts in the developer's CDP Project.*/ + /**Specifies whether the given amount is to be received by the target or taken from the source. + + - `target`: The transfer `target` receives the exact value specified in `amount`. Fees are added to the amount taken from the transfer `source`. + - `source`: The transfer `target` receives the value specified in `amount`, minus any fees. + */ /// ///
JSON schema /// /// ```json ///{ - /// "description": "An optional name for the smart account.\nAccount names can consist of alphanumeric characters and hyphens, and be between 2 and 36 characters long.\nAccount names must be unique across all EVM smart accounts in the developer's CDP Project.", + /// "description": "Specifies whether the given amount is to be received by the target or taken from the source.\n\n- `target`: The transfer `target` receives the exact value specified in `amount`. Fees are added to the amount taken from the transfer `source`.\n- `source`: The transfer `target` receives the value specified in `amount`, minus any fees.\n", + /// "default": "source", /// "examples": [ - /// "my-smart-account" + /// "source" /// ], /// "type": "string", - /// "pattern": "^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$" + /// "enum": [ + /// "target", + /// "source" + /// ] ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct UpdateEvmSmartAccountBodyName(::std::string::String); - impl ::std::ops::Deref for UpdateEvmSmartAccountBodyName { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } + #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum TransferRequestAmountType { + #[serde(rename = "target")] + Target, + #[serde(rename = "source")] + Source, } - impl ::std::convert::From for ::std::string::String { - fn from(value: UpdateEvmSmartAccountBodyName) -> Self { - value.0 + impl ::std::convert::From<&Self> for TransferRequestAmountType { + fn from(value: &TransferRequestAmountType) -> Self { + value.clone() } } - impl ::std::convert::From<&UpdateEvmSmartAccountBodyName> for UpdateEvmSmartAccountBodyName { - fn from(value: &UpdateEvmSmartAccountBodyName) -> Self { - value.clone() + impl ::std::fmt::Display for TransferRequestAmountType { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Target => f.write_str("target"), + Self::Source => f.write_str("source"), + } } } - impl ::std::str::FromStr for UpdateEvmSmartAccountBodyName { + impl ::std::str::FromStr for TransferRequestAmountType { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$").unwrap() - }); - if PATTERN.find(value).is_none() { - return Err( - "doesn't match pattern \"^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$\"".into(), - ); + match value { + "target" => Ok(Self::Target), + "source" => Ok(Self::Source), + _ => Err("invalid value".into()), } - Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for UpdateEvmSmartAccountBodyName { + impl ::std::convert::TryFrom<&str> for TransferRequestAmountType { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for UpdateEvmSmartAccountBodyName { + impl ::std::convert::TryFrom<&::std::string::String> for TransferRequestAmountType { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -52479,7 +58489,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for UpdateEvmSmartAccountBodyName { + impl ::std::convert::TryFrom<::std::string::String> for TransferRequestAmountType { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -52487,122 +58497,153 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for UpdateEvmSmartAccountBodyName { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) + impl ::std::default::Default for TransferRequestAmountType { + fn default() -> Self { + TransferRequestAmountType::Source } } - ///`UpdatePolicyBody` + ///The source of the transfer. /// ///
JSON schema /// /// ```json ///{ - /// "type": "object", - /// "required": [ - /// "rules" + /// "description": "The source of the transfer.", + /// "examples": [ + /// {} /// ], - /// "properties": { - /// "description": { - /// "description": "An optional human-readable description for the policy.\nPolicy descriptions can consist of alphanumeric characters, spaces, commas, and periods, and be 50 characters or less.", - /// "examples": [ - /// "Default policy" - /// ], - /// "type": "string", - /// "pattern": "^[A-Za-z0-9 ,.]{1,50}$" + /// "oneOf": [ + /// { + /// "$ref": "#/components/schemas/transfers_Account" /// }, - /// "rules": { - /// "description": "A list of rules that comprise the policy. There is a limit of 10 rules per policy.", - /// "type": "array", - /// "items": { - /// "$ref": "#/components/schemas/Rule" - /// } + /// { + /// "$ref": "#/components/schemas/PaymentMethod" + /// }, + /// { + /// "$ref": "#/components/schemas/OnchainAddress" + /// }, + /// { + /// "$ref": "#/components/schemas/OriginatingBankAccountUS" /// } - /// } + /// ] ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct UpdatePolicyBody { - /**An optional human-readable description for the policy. - Policy descriptions can consist of alphanumeric characters, spaces, commas, and periods, and be 50 characters or less.*/ - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub description: ::std::option::Option, - ///A list of rules that comprise the policy. There is a limit of 10 rules per policy. - pub rules: ::std::vec::Vec, + #[serde(untagged)] + pub enum TransferSource { + TransfersAccount(TransfersAccount), + PaymentMethod(PaymentMethod), + OnchainAddress(OnchainAddress), + OriginatingBankAccountUs(OriginatingBankAccountUs), } - impl ::std::convert::From<&UpdatePolicyBody> for UpdatePolicyBody { - fn from(value: &UpdatePolicyBody) -> Self { + impl ::std::convert::From<&Self> for TransferSource { + fn from(value: &TransferSource) -> Self { value.clone() } } - impl UpdatePolicyBody { - pub fn builder() -> builder::UpdatePolicyBody { - Default::default() + impl ::std::convert::From for TransferSource { + fn from(value: TransfersAccount) -> Self { + Self::TransfersAccount(value) } } - /**An optional human-readable description for the policy. - Policy descriptions can consist of alphanumeric characters, spaces, commas, and periods, and be 50 characters or less.*/ + impl ::std::convert::From for TransferSource { + fn from(value: PaymentMethod) -> Self { + Self::PaymentMethod(value) + } + } + impl ::std::convert::From for TransferSource { + fn from(value: OnchainAddress) -> Self { + Self::OnchainAddress(value) + } + } + impl ::std::convert::From for TransferSource { + fn from(value: OriginatingBankAccountUs) -> Self { + Self::OriginatingBankAccountUs(value) + } + } + ///The current status of the transfer, indicating what action you need to take next. Required when validateOnly is false. /// ///
JSON schema /// /// ```json ///{ - /// "description": "An optional human-readable description for the policy.\nPolicy descriptions can consist of alphanumeric characters, spaces, commas, and periods, and be 50 characters or less.", + /// "description": "The current status of the transfer, indicating what action you need to take next. Required when validateOnly is false.", /// "examples": [ - /// "Default policy" + /// "quoted" /// ], /// "type": "string", - /// "pattern": "^[A-Za-z0-9 ,.]{1,50}$" + /// "enum": [ + /// "quoted", + /// "processing", + /// "completed", + /// "failed" + /// ], + /// "x-enum-descriptions": [ + /// "Transfer was created with `execute: true`, but is momentarily being quoted before executing _or_ the transfer was created with `execute: false`. It can be executed by calling `/v2/transfers/{transferId}/execute` with `execute: true`.", + /// "Transfer is executing after being quoted. No action needed - monitor progress via the transfers webhook.", + /// "Transfer completed successfully.", + /// "Transfer failed. See `failureReason` for details." + /// ] ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct UpdatePolicyBodyDescription(::std::string::String); - impl ::std::ops::Deref for UpdatePolicyBodyDescription { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } + #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum TransferStatus { + #[serde(rename = "quoted")] + Quoted, + #[serde(rename = "processing")] + Processing, + #[serde(rename = "completed")] + Completed, + #[serde(rename = "failed")] + Failed, } - impl ::std::convert::From for ::std::string::String { - fn from(value: UpdatePolicyBodyDescription) -> Self { - value.0 + impl ::std::convert::From<&Self> for TransferStatus { + fn from(value: &TransferStatus) -> Self { + value.clone() } } - impl ::std::convert::From<&UpdatePolicyBodyDescription> for UpdatePolicyBodyDescription { - fn from(value: &UpdatePolicyBodyDescription) -> Self { - value.clone() + impl ::std::fmt::Display for TransferStatus { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Quoted => f.write_str("quoted"), + Self::Processing => f.write_str("processing"), + Self::Completed => f.write_str("completed"), + Self::Failed => f.write_str("failed"), + } } } - impl ::std::str::FromStr for UpdatePolicyBodyDescription { + impl ::std::str::FromStr for TransferStatus { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^[A-Za-z0-9 ,.]{1,50}$").unwrap() - }); - if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^[A-Za-z0-9 ,.]{1,50}$\"".into()); + match value { + "quoted" => Ok(Self::Quoted), + "processing" => Ok(Self::Processing), + "completed" => Ok(Self::Completed), + "failed" => Ok(Self::Failed), + _ => Err("invalid value".into()), } - Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for UpdatePolicyBodyDescription { + impl ::std::convert::TryFrom<&str> for TransferStatus { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for UpdatePolicyBodyDescription { + impl ::std::convert::TryFrom<&::std::string::String> for TransferStatus { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -52610,7 +58651,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for UpdatePolicyBodyDescription { + impl ::std::convert::TryFrom<::std::string::String> for TransferStatus { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -52618,75 +58659,387 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for UpdatePolicyBodyDescription { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) - } - } - ///`UpdatePolicyPolicyId` + ///The target of the transfer. /// ///
JSON schema /// /// ```json ///{ - /// "type": "string", - /// "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" + /// "description": "The target of the transfer.", + /// "examples": [ + /// {} + /// ], + /// "oneOf": [ + /// { + /// "$ref": "#/components/schemas/transfers_Account" + /// }, + /// { + /// "$ref": "#/components/schemas/PaymentMethod" + /// }, + /// { + /// "$ref": "#/components/schemas/OnchainAddress" + /// }, + /// { + /// "$ref": "#/components/schemas/EmailInstrument" + /// } + /// ] ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct UpdatePolicyPolicyId(::std::string::String); - impl ::std::ops::Deref for UpdatePolicyPolicyId { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 + #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + #[serde(untagged)] + pub enum TransferTarget { + TransfersAccount(TransfersAccount), + PaymentMethod(PaymentMethod), + OnchainAddress(OnchainAddress), + EmailInstrument(EmailInstrument), + } + impl ::std::convert::From<&Self> for TransferTarget { + fn from(value: &TransferTarget) -> Self { + value.clone() } } - impl ::std::convert::From for ::std::string::String { - fn from(value: UpdatePolicyPolicyId) -> Self { - value.0 + impl ::std::convert::From for TransferTarget { + fn from(value: TransfersAccount) -> Self { + Self::TransfersAccount(value) } } - impl ::std::convert::From<&UpdatePolicyPolicyId> for UpdatePolicyPolicyId { - fn from(value: &UpdatePolicyPolicyId) -> Self { - value.clone() + impl ::std::convert::From for TransferTarget { + fn from(value: PaymentMethod) -> Self { + Self::PaymentMethod(value) } } - impl ::std::str::FromStr for UpdatePolicyPolicyId { + impl ::std::convert::From for TransferTarget { + fn from(value: OnchainAddress) -> Self { + Self::OnchainAddress(value) + } + } + impl ::std::convert::From for TransferTarget { + fn from(value: EmailInstrument) -> Self { + Self::EmailInstrument(value) + } + } + ///The Account specific details for the transfer. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "title": "Account", + /// "description": "The Account specific details for the transfer.", + /// "examples": [ + /// { + /// "accountId": "account_af2937b0-9846-4fe7-bfe9-ccc22d935114", + /// "asset": "usd" + /// } + /// ], + /// "type": "object", + /// "required": [ + /// "accountId", + /// "asset" + /// ], + /// "properties": { + /// "accountId": { + /// "description": "The ID of the Account.", + /// "type": "string" + /// }, + /// "asset": { + /// "$ref": "#/components/schemas/Asset" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct TransfersAccount { + ///The ID of the Account. + #[serde(rename = "accountId")] + pub account_id: ::std::string::String, + pub asset: Asset, + } + impl ::std::convert::From<&TransfersAccount> for TransfersAccount { + fn from(value: &TransfersAccount) -> Self { + value.clone() + } + } + impl TransfersAccount { + pub fn builder() -> builder::TransfersAccount { + Default::default() + } + } + ///Required Travel Rule fields differ by region. These requirements are determined based on which Coinbase entity the customer has signed the service agreement for. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "Required Travel Rule fields differ by region. These requirements are determined based on which Coinbase entity the customer has signed the service agreement for.", + /// "examples": [ + /// { + /// "beneficiary": { + /// "address": { + /// "city": "Paris", + /// "countryCode": "FR", + /// "line1": "456 Oak Ave", + /// "postCode": "75001" + /// }, + /// "name": "Jane Smith", + /// "walletType": "custodial" + /// }, + /// "isIntermediary": true, + /// "isSelf": false, + /// "originator": { + /// "address": { + /// "city": "Luxembourg", + /// "countryCode": "LU", + /// "line1": "123 Main St", + /// "line2": "Unit 201", + /// "postCode": "L-1234" + /// }, + /// "financialInstitution": "PayPal, Inc.", + /// "name": "John Doe", + /// "vasp": { + /// "address": { + /// "city": "San Francisco", + /// "countryCode": "US", + /// "line1": "123 Market St", + /// "line2": "Suite 400", + /// "postCode": "94105", + /// "state": "California" + /// }, + /// "identifier": "5493001KJTIIGC8Y1R17", + /// "name": "Fidelity Digital Asset Services, LLC" + /// } + /// } + /// } + /// ], + /// "type": "object", + /// "properties": { + /// "beneficiary": { + /// "$ref": "#/components/schemas/TravelRuleBeneficiary" + /// }, + /// "isIntermediary": { + /// "description": "Indicates whether Coinbase is being used as an intermediary Virtual Asset Service Provider (VASP) to send crypto on behalf of your customer.\n\n**Background:**\n\nThe Travel Rule (FATF Recommendation 16) requires VASPs to share originator and beneficiary information for virtual asset transfers. When Coinbase acts as an intermediary, additional Travel Rule data must be provided to satisfy compliance requirements.\n\n**Set to `true` when:**\n\n- Your organization is a VASP using Coinbase to send crypto **on behalf of your end customer**\n- In this scenario, Coinbase acts as an intermediary in the transfer chain and handles Travel Rule data exchange with the beneficiary VASP\n\n**Set to `false` (or omit) when:**\n\n- You are transferring funds directly from your own Coinbase account, where **Coinbase is your primary VASP** rather than an intermediary for another institution\n\n**Impact on required fields:**\n\nWhen `isIntermediary` is `true`, you must provide the `originator` object with details about the original sender, including:\n- Originator name\n- Originator address\n- Your VASP information (`virtualAssetServiceProvider` object with `name`, `address`, and `identifier`)\n", + /// "examples": [ + /// true + /// ], + /// "type": "boolean" + /// }, + /// "isSelf": { + /// "description": "Indicates whether the user attests that the receiving wallet belongs to them.", + /// "examples": [ + /// true + /// ], + /// "type": "boolean" + /// }, + /// "originator": { + /// "$ref": "#/components/schemas/TravelRuleOriginator" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct TravelRule { + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub beneficiary: ::std::option::Option, + /**Indicates whether Coinbase is being used as an intermediary Virtual Asset Service Provider (VASP) to send crypto on behalf of your customer. + + **Background:** + + The Travel Rule (FATF Recommendation 16) requires VASPs to share originator and beneficiary information for virtual asset transfers. When Coinbase acts as an intermediary, additional Travel Rule data must be provided to satisfy compliance requirements. + + **Set to `true` when:** + + - Your organization is a VASP using Coinbase to send crypto **on behalf of your end customer** + - In this scenario, Coinbase acts as an intermediary in the transfer chain and handles Travel Rule data exchange with the beneficiary VASP + + **Set to `false` (or omit) when:** + + - You are transferring funds directly from your own Coinbase account, where **Coinbase is your primary VASP** rather than an intermediary for another institution + + **Impact on required fields:** + + When `isIntermediary` is `true`, you must provide the `originator` object with details about the original sender, including: + - Originator name + - Originator address + - Your VASP information (`virtualAssetServiceProvider` object with `name`, `address`, and `identifier`) + */ + #[serde( + rename = "isIntermediary", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub is_intermediary: ::std::option::Option, + ///Indicates whether the user attests that the receiving wallet belongs to them. + #[serde( + rename = "isSelf", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub is_self: ::std::option::Option, + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub originator: ::std::option::Option, + } + impl ::std::convert::From<&TravelRule> for TravelRule { + fn from(value: &TravelRule) -> Self { + value.clone() + } + } + impl ::std::default::Default for TravelRule { + fn default() -> Self { + Self { + beneficiary: Default::default(), + is_intermediary: Default::default(), + is_self: Default::default(), + originator: Default::default(), + } + } + } + impl TravelRule { + pub fn builder() -> builder::TravelRule { + Default::default() + } + } + ///Beneficiary (receiver) party. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "Beneficiary (receiver) party.", + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/TravelRuleParty" + /// }, + /// { + /// "type": "object", + /// "properties": { + /// "walletType": { + /// "description": "The type of the beneficiary's wallet.", + /// "examples": [ + /// "custodial" + /// ], + /// "type": "string", + /// "enum": [ + /// "custodial", + /// "self_custody" + /// ] + /// } + /// } + /// } + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct TravelRuleBeneficiary { + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub address: ::std::option::Option, + ///Name of the financial institution. + #[serde( + rename = "financialInstitution", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub financial_institution: ::std::option::Option<::std::string::String>, + ///Full name of the party. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub name: ::std::option::Option<::std::string::String>, + ///The type of the beneficiary's wallet. + #[serde( + rename = "walletType", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub wallet_type: ::std::option::Option, + } + impl ::std::convert::From<&TravelRuleBeneficiary> for TravelRuleBeneficiary { + fn from(value: &TravelRuleBeneficiary) -> Self { + value.clone() + } + } + impl ::std::default::Default for TravelRuleBeneficiary { + fn default() -> Self { + Self { + address: Default::default(), + financial_institution: Default::default(), + name: Default::default(), + wallet_type: Default::default(), + } + } + } + impl TravelRuleBeneficiary { + pub fn builder() -> builder::TravelRuleBeneficiary { + Default::default() + } + } + ///The type of the beneficiary's wallet. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The type of the beneficiary's wallet.", + /// "examples": [ + /// "custodial" + /// ], + /// "type": "string", + /// "enum": [ + /// "custodial", + /// "self_custody" + /// ] + ///} + /// ``` + ///
+ #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum TravelRuleBeneficiaryWalletType { + #[serde(rename = "custodial")] + Custodial, + #[serde(rename = "self_custody")] + SelfCustody, + } + impl ::std::convert::From<&Self> for TravelRuleBeneficiaryWalletType { + fn from(value: &TravelRuleBeneficiaryWalletType) -> Self { + value.clone() + } + } + impl ::std::fmt::Display for TravelRuleBeneficiaryWalletType { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Custodial => f.write_str("custodial"), + Self::SelfCustody => f.write_str("self_custody"), + } + } + } + impl ::std::str::FromStr for TravelRuleBeneficiaryWalletType { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new( - || { - ::regress::Regex::new( - "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", - ) - .unwrap() - }, - ); - if PATTERN.find(value).is_none() { - return Err( - "doesn't match pattern \"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$\"" - .into(), - ); + match value { + "custodial" => Ok(Self::Custodial), + "self_custody" => Ok(Self::SelfCustody), + _ => Err("invalid value".into()), } - Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for UpdatePolicyPolicyId { + impl ::std::convert::TryFrom<&str> for TravelRuleBeneficiaryWalletType { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for UpdatePolicyPolicyId { + impl ::std::convert::TryFrom<&::std::string::String> for TravelRuleBeneficiaryWalletType { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -52694,7 +59047,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for UpdatePolicyPolicyId { + impl ::std::convert::TryFrom<::std::string::String> for TravelRuleBeneficiaryWalletType { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -52702,68 +59055,304 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for UpdatePolicyPolicyId { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) + ///Originator (sender) party. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "Originator (sender) party.", + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/TravelRuleParty" + /// }, + /// { + /// "type": "object", + /// "properties": { + /// "virtualAssetServiceProvider": { + /// "description": "Information about the originating Virtual Asset Service Provider (VASP) that handles cryptocurrency or other virtual assets on behalf of customers.", + /// "type": "object", + /// "properties": { + /// "address": { + /// "$ref": "#/components/schemas/PhysicalAddress" + /// }, + /// "identifier": { + /// "description": "The Legal Entity Identifier of the originating Virtual Asset Service Provider (VASP).", + /// "examples": [ + /// "5493001KJTIIGC8Y1R17" + /// ], + /// "type": "string" + /// }, + /// "name": { + /// "description": "The name of the originating Virtual Asset Service Provider (VASP).", + /// "examples": [ + /// "Fidelity Digital Asset Services, LLC" + /// ], + /// "type": "string" + /// } + /// } + /// } + /// } + /// } + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct TravelRuleOriginator { + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub address: ::std::option::Option, + ///Name of the financial institution. + #[serde( + rename = "financialInstitution", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub financial_institution: ::std::option::Option<::std::string::String>, + ///Full name of the party. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub name: ::std::option::Option<::std::string::String>, + #[serde( + rename = "virtualAssetServiceProvider", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub virtual_asset_service_provider: + ::std::option::Option, + } + impl ::std::convert::From<&TravelRuleOriginator> for TravelRuleOriginator { + fn from(value: &TravelRuleOriginator) -> Self { + value.clone() } } - ///`UpdatePolicyXIdempotencyKey` + impl ::std::default::Default for TravelRuleOriginator { + fn default() -> Self { + Self { + address: Default::default(), + financial_institution: Default::default(), + name: Default::default(), + virtual_asset_service_provider: Default::default(), + } + } + } + impl TravelRuleOriginator { + pub fn builder() -> builder::TravelRuleOriginator { + Default::default() + } + } + ///Information about the originating Virtual Asset Service Provider (VASP) that handles cryptocurrency or other virtual assets on behalf of customers. /// ///
JSON schema /// /// ```json ///{ - /// "type": "string", - /// "maxLength": 128, - /// "minLength": 1 + /// "description": "Information about the originating Virtual Asset Service Provider (VASP) that handles cryptocurrency or other virtual assets on behalf of customers.", + /// "type": "object", + /// "properties": { + /// "address": { + /// "$ref": "#/components/schemas/PhysicalAddress" + /// }, + /// "identifier": { + /// "description": "The Legal Entity Identifier of the originating Virtual Asset Service Provider (VASP).", + /// "examples": [ + /// "5493001KJTIIGC8Y1R17" + /// ], + /// "type": "string" + /// }, + /// "name": { + /// "description": "The name of the originating Virtual Asset Service Provider (VASP).", + /// "examples": [ + /// "Fidelity Digital Asset Services, LLC" + /// ], + /// "type": "string" + /// } + /// } ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct UpdatePolicyXIdempotencyKey(::std::string::String); - impl ::std::ops::Deref for UpdatePolicyXIdempotencyKey { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 + #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct TravelRuleOriginatorVirtualAssetServiceProvider { + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub address: ::std::option::Option, + ///The Legal Entity Identifier of the originating Virtual Asset Service Provider (VASP). + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub identifier: ::std::option::Option<::std::string::String>, + ///The name of the originating Virtual Asset Service Provider (VASP). + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub name: ::std::option::Option<::std::string::String>, + } + impl ::std::convert::From<&TravelRuleOriginatorVirtualAssetServiceProvider> + for TravelRuleOriginatorVirtualAssetServiceProvider + { + fn from(value: &TravelRuleOriginatorVirtualAssetServiceProvider) -> Self { + value.clone() } } - impl ::std::convert::From for ::std::string::String { - fn from(value: UpdatePolicyXIdempotencyKey) -> Self { - value.0 + impl ::std::default::Default for TravelRuleOriginatorVirtualAssetServiceProvider { + fn default() -> Self { + Self { + address: Default::default(), + identifier: Default::default(), + name: Default::default(), + } } } - impl ::std::convert::From<&UpdatePolicyXIdempotencyKey> for UpdatePolicyXIdempotencyKey { - fn from(value: &UpdatePolicyXIdempotencyKey) -> Self { + impl TravelRuleOriginatorVirtualAssetServiceProvider { + pub fn builder() -> builder::TravelRuleOriginatorVirtualAssetServiceProvider { + Default::default() + } + } + ///Information about a party (originator or beneficiary) for travel rule compliance. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "Information about a party (originator or beneficiary) for travel rule compliance.", + /// "examples": [ + /// { + /// "address": { + /// "city": "San Francisco", + /// "countryCode": "US", + /// "line1": "123 Main St", + /// "line2": "Unit 201", + /// "postCode": "94105", + /// "state": "California" + /// }, + /// "name": "John Doe" + /// } + /// ], + /// "type": "object", + /// "properties": { + /// "address": { + /// "$ref": "#/components/schemas/PhysicalAddress" + /// }, + /// "financialInstitution": { + /// "description": "Name of the financial institution.", + /// "examples": [ + /// "PayPal, Inc." + /// ], + /// "type": "string" + /// }, + /// "name": { + /// "description": "Full name of the party.", + /// "examples": [ + /// "John Doe" + /// ], + /// "type": "string" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct TravelRuleParty { + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub address: ::std::option::Option, + ///Name of the financial institution. + #[serde( + rename = "financialInstitution", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub financial_institution: ::std::option::Option<::std::string::String>, + ///Full name of the party. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub name: ::std::option::Option<::std::string::String>, + } + impl ::std::convert::From<&TravelRuleParty> for TravelRuleParty { + fn from(value: &TravelRuleParty) -> Self { value.clone() } } - impl ::std::str::FromStr for UpdatePolicyXIdempotencyKey { + impl ::std::default::Default for TravelRuleParty { + fn default() -> Self { + Self { + address: Default::default(), + financial_institution: Default::default(), + name: Default::default(), + } + } + } + impl TravelRuleParty { + pub fn builder() -> builder::TravelRuleParty { + Default::default() + } + } + ///The status of a travel rule submission. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The status of a travel rule submission.", + /// "examples": [ + /// "incomplete" + /// ], + /// "type": "string", + /// "enum": [ + /// "incomplete", + /// "completed" + /// ], + /// "x-enum-descriptions": [ + /// "Additional fields are required before the transfer can proceed.", + /// "All requirements are satisfied and the transfer will proceed." + /// ], + /// "x-enum-varnames": [ + /// "TravelRuleStatusIncomplete", + /// "TravelRuleStatusCompleted" + /// ] + ///} + /// ``` + ///
+ #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum TravelRuleStatus { + #[serde(rename = "incomplete")] + Incomplete, + #[serde(rename = "completed")] + Completed, + } + impl ::std::convert::From<&Self> for TravelRuleStatus { + fn from(value: &TravelRuleStatus) -> Self { + value.clone() + } + } + impl ::std::fmt::Display for TravelRuleStatus { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Incomplete => f.write_str("incomplete"), + Self::Completed => f.write_str("completed"), + } + } + } + impl ::std::str::FromStr for TravelRuleStatus { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - if value.chars().count() > 128usize { - return Err("longer than 128 characters".into()); - } - if value.chars().count() < 1usize { - return Err("shorter than 1 characters".into()); + match value { + "incomplete" => Ok(Self::Incomplete), + "completed" => Ok(Self::Completed), + _ => Err("invalid value".into()), } - Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for UpdatePolicyXIdempotencyKey { + impl ::std::convert::TryFrom<&str> for TravelRuleStatus { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for UpdatePolicyXIdempotencyKey { + impl ::std::convert::TryFrom<&::std::string::String> for TravelRuleStatus { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -52771,7 +59360,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for UpdatePolicyXIdempotencyKey { + impl ::std::convert::TryFrom<::std::string::String> for TravelRuleStatus { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -52779,68 +59368,56 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for UpdatePolicyXIdempotencyKey { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) - } - } - ///`UpdateSolanaAccountAddress` + ///`UpdateEvmAccountAddress` /// ///
JSON schema /// /// ```json ///{ /// "type": "string", - /// "pattern": "^[1-9A-HJ-NP-Za-km-z]{32,44}$" + /// "pattern": "^0x[0-9a-fA-F]{40}$" ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct UpdateSolanaAccountAddress(::std::string::String); - impl ::std::ops::Deref for UpdateSolanaAccountAddress { + pub struct UpdateEvmAccountAddress(::std::string::String); + impl ::std::ops::Deref for UpdateEvmAccountAddress { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: UpdateSolanaAccountAddress) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: UpdateEvmAccountAddress) -> Self { value.0 } } - impl ::std::convert::From<&UpdateSolanaAccountAddress> for UpdateSolanaAccountAddress { - fn from(value: &UpdateSolanaAccountAddress) -> Self { + impl ::std::convert::From<&UpdateEvmAccountAddress> for UpdateEvmAccountAddress { + fn from(value: &UpdateEvmAccountAddress) -> Self { value.clone() } } - impl ::std::str::FromStr for UpdateSolanaAccountAddress { + impl ::std::str::FromStr for UpdateEvmAccountAddress { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^[1-9A-HJ-NP-Za-km-z]{32,44}$").unwrap() + ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() }); if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^[1-9A-HJ-NP-Za-km-z]{32,44}$\"".into()); + return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for UpdateSolanaAccountAddress { + impl ::std::convert::TryFrom<&str> for UpdateEvmAccountAddress { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for UpdateSolanaAccountAddress { + impl ::std::convert::TryFrom<&::std::string::String> for UpdateEvmAccountAddress { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -52848,7 +59425,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for UpdateSolanaAccountAddress { + impl ::std::convert::TryFrom<::std::string::String> for UpdateEvmAccountAddress { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -52856,7 +59433,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for UpdateSolanaAccountAddress { + impl<'de> ::serde::Deserialize<'de> for UpdateEvmAccountAddress { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -52868,7 +59445,7 @@ pub mod types { }) } } - ///`UpdateSolanaAccountBody` + ///`UpdateEvmAccountBody` /// ///
JSON schema /// @@ -52886,7 +59463,7 @@ pub mod types { /// "x-audience": "public" /// }, /// "name": { - /// "description": "An optional name for the account. Account names can consist of alphanumeric characters and hyphens, and be between 2 and 36 characters long.\nAccount names must be unique across all Solana accounts in the developer's CDP Project.", + /// "description": "An optional name for the account.\nAccount names can consist of alphanumeric characters and hyphens, and be between 2 and 36 characters long.\nAccount names must be unique across all EVM accounts in the developer's CDP Project.", /// "examples": [ /// "my-wallet" /// ], @@ -52898,25 +59475,26 @@ pub mod types { /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct UpdateSolanaAccountBody { + pub struct UpdateEvmAccountBody { ///The ID of the account-level policy to apply to the account, or an empty string to unset attached policy. #[serde( rename = "accountPolicy", default, skip_serializing_if = "::std::option::Option::is_none" )] - pub account_policy: ::std::option::Option, - /**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 Solana accounts in the developer's CDP Project.*/ + pub account_policy: ::std::option::Option, + /**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.*/ #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub name: ::std::option::Option, + pub name: ::std::option::Option, } - impl ::std::convert::From<&UpdateSolanaAccountBody> for UpdateSolanaAccountBody { - fn from(value: &UpdateSolanaAccountBody) -> Self { + impl ::std::convert::From<&UpdateEvmAccountBody> for UpdateEvmAccountBody { + fn from(value: &UpdateEvmAccountBody) -> Self { value.clone() } } - impl ::std::default::Default for UpdateSolanaAccountBody { + impl ::std::default::Default for UpdateEvmAccountBody { fn default() -> Self { Self { account_policy: Default::default(), @@ -52924,8 +59502,8 @@ pub mod types { } } } - impl UpdateSolanaAccountBody { - pub fn builder() -> builder::UpdateSolanaAccountBody { + impl UpdateEvmAccountBody { + pub fn builder() -> builder::UpdateEvmAccountBody { Default::default() } } @@ -52947,26 +59525,26 @@ pub mod types { ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct UpdateSolanaAccountBodyAccountPolicy(::std::string::String); - impl ::std::ops::Deref for UpdateSolanaAccountBodyAccountPolicy { + pub struct UpdateEvmAccountBodyAccountPolicy(::std::string::String); + impl ::std::ops::Deref for UpdateEvmAccountBodyAccountPolicy { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: UpdateSolanaAccountBodyAccountPolicy) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: UpdateEvmAccountBodyAccountPolicy) -> Self { value.0 } } - impl ::std::convert::From<&UpdateSolanaAccountBodyAccountPolicy> - for UpdateSolanaAccountBodyAccountPolicy + impl ::std::convert::From<&UpdateEvmAccountBodyAccountPolicy> + for UpdateEvmAccountBodyAccountPolicy { - fn from(value: &UpdateSolanaAccountBodyAccountPolicy) -> Self { + fn from(value: &UpdateEvmAccountBodyAccountPolicy) -> Self { value.clone() } } - impl ::std::str::FromStr for UpdateSolanaAccountBodyAccountPolicy { + impl ::std::str::FromStr for UpdateEvmAccountBodyAccountPolicy { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new( @@ -52986,13 +59564,13 @@ pub mod types { Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for UpdateSolanaAccountBodyAccountPolicy { + impl ::std::convert::TryFrom<&str> for UpdateEvmAccountBodyAccountPolicy { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for UpdateSolanaAccountBodyAccountPolicy { + impl ::std::convert::TryFrom<&::std::string::String> for UpdateEvmAccountBodyAccountPolicy { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -53000,7 +59578,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for UpdateSolanaAccountBodyAccountPolicy { + impl ::std::convert::TryFrom<::std::string::String> for UpdateEvmAccountBodyAccountPolicy { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -53008,7 +59586,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for UpdateSolanaAccountBodyAccountPolicy { + impl<'de> ::serde::Deserialize<'de> for UpdateEvmAccountBodyAccountPolicy { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -53020,14 +59598,15 @@ pub mod types { }) } } - /**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 Solana accounts in the developer's CDP Project.*/ + /**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.*/ /// ///
JSON schema /// /// ```json ///{ - /// "description": "An optional name for the account. Account names can consist of alphanumeric characters and hyphens, and be between 2 and 36 characters long.\nAccount names must be unique across all Solana accounts in the developer's CDP Project.", + /// "description": "An optional name for the account.\nAccount names can consist of alphanumeric characters and hyphens, and be between 2 and 36 characters long.\nAccount names must be unique across all EVM accounts in the developer's CDP Project.", /// "examples": [ /// "my-wallet" /// ], @@ -53038,24 +59617,24 @@ pub mod types { ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct UpdateSolanaAccountBodyName(::std::string::String); - impl ::std::ops::Deref for UpdateSolanaAccountBodyName { + pub struct UpdateEvmAccountBodyName(::std::string::String); + impl ::std::ops::Deref for UpdateEvmAccountBodyName { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: UpdateSolanaAccountBodyName) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: UpdateEvmAccountBodyName) -> Self { value.0 } } - impl ::std::convert::From<&UpdateSolanaAccountBodyName> for UpdateSolanaAccountBodyName { - fn from(value: &UpdateSolanaAccountBodyName) -> Self { + impl ::std::convert::From<&UpdateEvmAccountBodyName> for UpdateEvmAccountBodyName { + fn from(value: &UpdateEvmAccountBodyName) -> Self { value.clone() } } - impl ::std::str::FromStr for UpdateSolanaAccountBodyName { + impl ::std::str::FromStr for UpdateEvmAccountBodyName { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = @@ -53070,13 +59649,13 @@ pub mod types { Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for UpdateSolanaAccountBodyName { + impl ::std::convert::TryFrom<&str> for UpdateEvmAccountBodyName { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for UpdateSolanaAccountBodyName { + impl ::std::convert::TryFrom<&::std::string::String> for UpdateEvmAccountBodyName { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -53084,7 +59663,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for UpdateSolanaAccountBodyName { + impl ::std::convert::TryFrom<::std::string::String> for UpdateEvmAccountBodyName { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -53092,7 +59671,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for UpdateSolanaAccountBodyName { + impl<'de> ::serde::Deserialize<'de> for UpdateEvmAccountBodyName { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -53104,7 +59683,7 @@ pub mod types { }) } } - ///`UpdateSolanaAccountXIdempotencyKey` + ///`UpdateEvmAccountXIdempotencyKey` /// ///
JSON schema /// @@ -53118,26 +59697,24 @@ pub mod types { ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct UpdateSolanaAccountXIdempotencyKey(::std::string::String); - impl ::std::ops::Deref for UpdateSolanaAccountXIdempotencyKey { + pub struct UpdateEvmAccountXIdempotencyKey(::std::string::String); + impl ::std::ops::Deref for UpdateEvmAccountXIdempotencyKey { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: UpdateSolanaAccountXIdempotencyKey) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: UpdateEvmAccountXIdempotencyKey) -> Self { value.0 } } - impl ::std::convert::From<&UpdateSolanaAccountXIdempotencyKey> - for UpdateSolanaAccountXIdempotencyKey - { - fn from(value: &UpdateSolanaAccountXIdempotencyKey) -> Self { + impl ::std::convert::From<&UpdateEvmAccountXIdempotencyKey> for UpdateEvmAccountXIdempotencyKey { + fn from(value: &UpdateEvmAccountXIdempotencyKey) -> Self { value.clone() } } - impl ::std::str::FromStr for UpdateSolanaAccountXIdempotencyKey { + impl ::std::str::FromStr for UpdateEvmAccountXIdempotencyKey { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { if value.chars().count() > 128usize { @@ -53149,13 +59726,13 @@ pub mod types { Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for UpdateSolanaAccountXIdempotencyKey { + impl ::std::convert::TryFrom<&str> for UpdateEvmAccountXIdempotencyKey { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for UpdateSolanaAccountXIdempotencyKey { + impl ::std::convert::TryFrom<&::std::string::String> for UpdateEvmAccountXIdempotencyKey { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -53163,7 +59740,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for UpdateSolanaAccountXIdempotencyKey { + impl ::std::convert::TryFrom<::std::string::String> for UpdateEvmAccountXIdempotencyKey { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -53171,7 +59748,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for UpdateSolanaAccountXIdempotencyKey { + impl<'de> ::serde::Deserialize<'de> for UpdateEvmAccountXIdempotencyKey { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -53183,281 +59760,186 @@ pub mod types { }) } } - ///A valid URI. + ///`UpdateEvmSmartAccountAddress` /// ///
JSON schema /// /// ```json ///{ - /// "description": "A valid URI.", - /// "examples": [ - /// "foo://bar" - /// ], /// "type": "string", - /// "format": "uri", - /// "maxLength": 2048, - /// "minLength": 5, - /// "pattern": "^.*://.*$" + /// "pattern": "^0x[0-9a-fA-F]{40}$" ///} /// ``` ///
- #[derive( - ::serde::Deserialize, ::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, - )] + #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct Uri(pub ::std::string::String); - impl ::std::ops::Deref for Uri { + pub struct UpdateEvmSmartAccountAddress(::std::string::String); + impl ::std::ops::Deref for UpdateEvmSmartAccountAddress { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: Uri) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: UpdateEvmSmartAccountAddress) -> Self { value.0 } } - impl ::std::convert::From<&Uri> for Uri { - fn from(value: &Uri) -> Self { + impl ::std::convert::From<&UpdateEvmSmartAccountAddress> for UpdateEvmSmartAccountAddress { + fn from(value: &UpdateEvmSmartAccountAddress) -> Self { value.clone() } } - impl ::std::convert::From<::std::string::String> for Uri { - fn from(value: ::std::string::String) -> Self { - Self(value) - } - } - impl ::std::str::FromStr for Uri { - type Err = ::std::convert::Infallible; - fn from_str(value: &str) -> ::std::result::Result { + impl ::std::str::FromStr for UpdateEvmSmartAccountAddress { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); + } Ok(Self(value.to_string())) } } - impl ::std::fmt::Display for Uri { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - self.0.fmt(f) - } - } - ///A valid HTTP or HTTPS URL. - /// - ///
JSON schema - /// - /// ```json - ///{ - /// "description": "A valid HTTP or HTTPS URL.", - /// "examples": [ - /// "https://example.com" - /// ], - /// "type": "string", - /// "format": "uri", - /// "maxLength": 2048, - /// "minLength": 11, - /// "pattern": "^https?://.*$" - ///} - /// ``` - ///
- #[derive( - ::serde::Deserialize, ::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, - )] - #[serde(transparent)] - pub struct Url(pub ::std::string::String); - impl ::std::ops::Deref for Url { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } - } - impl ::std::convert::From for ::std::string::String { - fn from(value: Url) -> Self { - value.0 - } - } - impl ::std::convert::From<&Url> for Url { - fn from(value: &Url) -> Self { - value.clone() + impl ::std::convert::TryFrom<&str> for UpdateEvmSmartAccountAddress { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() } } - impl ::std::convert::From<::std::string::String> for Url { - fn from(value: ::std::string::String) -> Self { - Self(value) + impl ::std::convert::TryFrom<&::std::string::String> for UpdateEvmSmartAccountAddress { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() } } - impl ::std::str::FromStr for Url { - type Err = ::std::convert::Infallible; - fn from_str(value: &str) -> ::std::result::Result { - Ok(Self(value.to_string())) + impl ::std::convert::TryFrom<::std::string::String> for UpdateEvmSmartAccountAddress { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() } } - impl ::std::fmt::Display for Url { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - self.0.fmt(f) + impl<'de> ::serde::Deserialize<'de> for UpdateEvmSmartAccountAddress { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) } } - ///The receipt that contains information about the execution of user operation. + ///`UpdateEvmSmartAccountBody` /// ///
JSON schema /// /// ```json ///{ - /// "description": "The receipt that contains information about the execution of user operation.", - /// "examples": [ - /// { - /// "blockHash": "0x386544b58930c0ec9e8f3ed09fb4cdb76b9ae0a1a37ddcacebe3925b57978e65", - /// "blockNumber": 29338819, - /// "gasUsed": "100000", - /// "revert": { - /// "data": "0x123", - /// "message": "reason for failure" - /// } - /// } - /// ], /// "type": "object", /// "properties": { - /// "blockHash": { - /// "description": "The block hash of the block including the transaction as 0x-prefixed string.", - /// "examples": [ - /// "0x386544b58930c0ec9e8f3ed09fb4cdb76b9ae0a1a37ddcacebe3925b57978e65" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{64}$|^$" - /// }, - /// "blockNumber": { - /// "description": "The block height (number) of the block including the transaction.", - /// "examples": [ - /// 29338819 - /// ], - /// "type": "integer" - /// }, - /// "gasUsed": { - /// "description": "The gas used for landing this user operation.", - /// "examples": [ - /// "100000" - /// ], - /// "type": "string" - /// }, - /// "revert": { - /// "$ref": "#/components/schemas/UserOperationReceiptRevert" - /// }, - /// "transactionHash": { - /// "description": "The hash of this transaction as 0x-prefixed string.", + /// "name": { + /// "description": "An optional name for the smart account.\nAccount names can consist of alphanumeric characters and hyphens, and be between 2 and 36 characters long.\nAccount names must be unique across all EVM smart accounts in the developer's CDP Project.", /// "examples": [ - /// "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" + /// "my-smart-account" /// ], /// "type": "string", - /// "pattern": "^0x[a-fA-F0-9]{64}$" + /// "pattern": "^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct UserOperationReceipt { - ///The block hash of the block including the transaction as 0x-prefixed string. - #[serde( - rename = "blockHash", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub block_hash: ::std::option::Option, - ///The block height (number) of the block including the transaction. - #[serde( - rename = "blockNumber", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub block_number: ::std::option::Option, - ///The gas used for landing this user operation. - #[serde( - rename = "gasUsed", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub gas_used: ::std::option::Option<::std::string::String>, + pub struct UpdateEvmSmartAccountBody { + /**An optional name for the smart 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 smart accounts in the developer's CDP Project.*/ #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub revert: ::std::option::Option, - ///The hash of this transaction as 0x-prefixed string. - #[serde( - rename = "transactionHash", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub transaction_hash: ::std::option::Option, + pub name: ::std::option::Option, } - impl ::std::convert::From<&UserOperationReceipt> for UserOperationReceipt { - fn from(value: &UserOperationReceipt) -> Self { + impl ::std::convert::From<&UpdateEvmSmartAccountBody> for UpdateEvmSmartAccountBody { + fn from(value: &UpdateEvmSmartAccountBody) -> Self { value.clone() } } - impl ::std::default::Default for UserOperationReceipt { + impl ::std::default::Default for UpdateEvmSmartAccountBody { fn default() -> Self { Self { - block_hash: Default::default(), - block_number: Default::default(), - gas_used: Default::default(), - revert: Default::default(), - transaction_hash: Default::default(), + name: Default::default(), } } } - impl UserOperationReceipt { - pub fn builder() -> builder::UserOperationReceipt { + impl UpdateEvmSmartAccountBody { + pub fn builder() -> builder::UpdateEvmSmartAccountBody { Default::default() } } - ///The block hash of the block including the transaction as 0x-prefixed string. + /**An optional name for the smart 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 smart accounts in the developer's CDP Project.*/ /// ///
JSON schema /// /// ```json ///{ - /// "description": "The block hash of the block including the transaction as 0x-prefixed string.", + /// "description": "An optional name for the smart account.\nAccount names can consist of alphanumeric characters and hyphens, and be between 2 and 36 characters long.\nAccount names must be unique across all EVM smart accounts in the developer's CDP Project.", /// "examples": [ - /// "0x386544b58930c0ec9e8f3ed09fb4cdb76b9ae0a1a37ddcacebe3925b57978e65" + /// "my-smart-account" /// ], /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{64}$|^$" + /// "pattern": "^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$" ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct UserOperationReceiptBlockHash(::std::string::String); - impl ::std::ops::Deref for UserOperationReceiptBlockHash { + pub struct UpdateEvmSmartAccountBodyName(::std::string::String); + impl ::std::ops::Deref for UpdateEvmSmartAccountBodyName { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: UserOperationReceiptBlockHash) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: UpdateEvmSmartAccountBodyName) -> Self { value.0 } } - impl ::std::convert::From<&UserOperationReceiptBlockHash> for UserOperationReceiptBlockHash { - fn from(value: &UserOperationReceiptBlockHash) -> Self { + impl ::std::convert::From<&UpdateEvmSmartAccountBodyName> for UpdateEvmSmartAccountBodyName { + fn from(value: &UpdateEvmSmartAccountBodyName) -> Self { value.clone() } } - impl ::std::str::FromStr for UserOperationReceiptBlockHash { + impl ::std::str::FromStr for UpdateEvmSmartAccountBodyName { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[0-9a-fA-F]{64}$|^$").unwrap() + ::regress::Regex::new("^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$").unwrap() }); if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]{64}$|^$\"".into()); + return Err( + "doesn't match pattern \"^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$\"".into(), + ); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for UserOperationReceiptBlockHash { + impl ::std::convert::TryFrom<&str> for UpdateEvmSmartAccountBodyName { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for UserOperationReceiptBlockHash { + impl ::std::convert::TryFrom<&::std::string::String> for UpdateEvmSmartAccountBodyName { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -53465,7 +59947,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for UserOperationReceiptBlockHash { + impl ::std::convert::TryFrom<::std::string::String> for UpdateEvmSmartAccountBodyName { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -53473,7 +59955,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for UserOperationReceiptBlockHash { + impl<'de> ::serde::Deserialize<'de> for UpdateEvmSmartAccountBodyName { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -53485,113 +59967,110 @@ pub mod types { }) } } - ///The revert data if the user operation has reverted. + ///`UpdatePolicyBody` /// ///
JSON schema /// /// ```json ///{ - /// "description": "The revert data if the user operation has reverted.", - /// "examples": [ - /// { - /// "data": "0x123", - /// "message": "reason for failure" - /// } - /// ], /// "type": "object", /// "required": [ - /// "data", - /// "message" + /// "rules" /// ], /// "properties": { - /// "data": { - /// "description": "The 0x-prefixed raw hex string.", + /// "description": { + /// "description": "An optional human-readable description for the policy.\nPolicy descriptions can consist of alphanumeric characters, spaces, commas, and periods, and be 50 characters or less.", /// "examples": [ - /// "0x123" + /// "Default policy" /// ], /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]*$" + /// "pattern": "^[A-Za-z0-9 ,.]{1,50}$" /// }, - /// "message": { - /// "description": "Human-readable revert reason if able to decode.", - /// "examples": [ - /// "reason for failure" - /// ], - /// "type": "string" + /// "rules": { + /// "description": "A list of rules that comprise the policy. There is a limit of 10 rules per policy.", + /// "type": "array", + /// "items": { + /// "$ref": "#/components/schemas/Rule" + /// } /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct UserOperationReceiptRevert { - ///The 0x-prefixed raw hex string. - pub data: UserOperationReceiptRevertData, - ///Human-readable revert reason if able to decode. - pub message: ::std::string::String, + pub struct UpdatePolicyBody { + /**An optional human-readable description for the policy. + Policy descriptions can consist of alphanumeric characters, spaces, commas, and periods, and be 50 characters or less.*/ + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub description: ::std::option::Option, + ///A list of rules that comprise the policy. There is a limit of 10 rules per policy. + pub rules: ::std::vec::Vec, } - impl ::std::convert::From<&UserOperationReceiptRevert> for UserOperationReceiptRevert { - fn from(value: &UserOperationReceiptRevert) -> Self { + impl ::std::convert::From<&UpdatePolicyBody> for UpdatePolicyBody { + fn from(value: &UpdatePolicyBody) -> Self { value.clone() } } - impl UserOperationReceiptRevert { - pub fn builder() -> builder::UserOperationReceiptRevert { + impl UpdatePolicyBody { + pub fn builder() -> builder::UpdatePolicyBody { Default::default() } } - ///The 0x-prefixed raw hex string. + /**An optional human-readable description for the policy. + Policy descriptions can consist of alphanumeric characters, spaces, commas, and periods, and be 50 characters or less.*/ /// ///
JSON schema /// /// ```json ///{ - /// "description": "The 0x-prefixed raw hex string.", + /// "description": "An optional human-readable description for the policy.\nPolicy descriptions can consist of alphanumeric characters, spaces, commas, and periods, and be 50 characters or less.", /// "examples": [ - /// "0x123" + /// "Default policy" /// ], /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]*$" + /// "pattern": "^[A-Za-z0-9 ,.]{1,50}$" ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct UserOperationReceiptRevertData(::std::string::String); - impl ::std::ops::Deref for UserOperationReceiptRevertData { + pub struct UpdatePolicyBodyDescription(::std::string::String); + impl ::std::ops::Deref for UpdatePolicyBodyDescription { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: UserOperationReceiptRevertData) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: UpdatePolicyBodyDescription) -> Self { value.0 } } - impl ::std::convert::From<&UserOperationReceiptRevertData> for UserOperationReceiptRevertData { - fn from(value: &UserOperationReceiptRevertData) -> Self { + impl ::std::convert::From<&UpdatePolicyBodyDescription> for UpdatePolicyBodyDescription { + fn from(value: &UpdatePolicyBodyDescription) -> Self { value.clone() } } - impl ::std::str::FromStr for UserOperationReceiptRevertData { + impl ::std::str::FromStr for UpdatePolicyBodyDescription { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| ::regress::Regex::new("^0x[0-9a-fA-F]*$").unwrap()); + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^[A-Za-z0-9 ,.]{1,50}$").unwrap() + }); if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]*$\"".into()); + return Err("doesn't match pattern \"^[A-Za-z0-9 ,.]{1,50}$\"".into()); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for UserOperationReceiptRevertData { + impl ::std::convert::TryFrom<&str> for UpdatePolicyBodyDescription { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for UserOperationReceiptRevertData { + impl ::std::convert::TryFrom<&::std::string::String> for UpdatePolicyBodyDescription { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -53599,7 +60078,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for UserOperationReceiptRevertData { + impl ::std::convert::TryFrom<::std::string::String> for UpdatePolicyBodyDescription { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -53607,7 +60086,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for UserOperationReceiptRevertData { + impl<'de> ::serde::Deserialize<'de> for UpdatePolicyBodyDescription { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -53619,62 +60098,63 @@ pub mod types { }) } } - ///The hash of this transaction as 0x-prefixed string. + ///`UpdatePolicyPolicyId` /// ///
JSON schema /// /// ```json ///{ - /// "description": "The hash of this transaction as 0x-prefixed string.", - /// "examples": [ - /// "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" - /// ], /// "type": "string", - /// "pattern": "^0x[a-fA-F0-9]{64}$" + /// "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct UserOperationReceiptTransactionHash(::std::string::String); - impl ::std::ops::Deref for UserOperationReceiptTransactionHash { + pub struct UpdatePolicyPolicyId(::std::string::String); + impl ::std::ops::Deref for UpdatePolicyPolicyId { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: UserOperationReceiptTransactionHash) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: UpdatePolicyPolicyId) -> Self { value.0 } } - impl ::std::convert::From<&UserOperationReceiptTransactionHash> - for UserOperationReceiptTransactionHash - { - fn from(value: &UserOperationReceiptTransactionHash) -> Self { + impl ::std::convert::From<&UpdatePolicyPolicyId> for UpdatePolicyPolicyId { + fn from(value: &UpdatePolicyPolicyId) -> Self { value.clone() } } - impl ::std::str::FromStr for UserOperationReceiptTransactionHash { + impl ::std::str::FromStr for UpdatePolicyPolicyId { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[a-fA-F0-9]{64}$").unwrap() - }); + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new( + || { + ::regress::Regex::new( + "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", + ) + .unwrap() + }, + ); if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[a-fA-F0-9]{64}$\"".into()); + return Err( + "doesn't match pattern \"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$\"" + .into(), + ); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for UserOperationReceiptTransactionHash { + impl ::std::convert::TryFrom<&str> for UpdatePolicyPolicyId { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for UserOperationReceiptTransactionHash { + impl ::std::convert::TryFrom<&::std::string::String> for UpdatePolicyPolicyId { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -53682,7 +60162,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for UserOperationReceiptTransactionHash { + impl ::std::convert::TryFrom<::std::string::String> for UpdatePolicyPolicyId { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -53690,7 +60170,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for UserOperationReceiptTransactionHash { + impl<'de> ::serde::Deserialize<'de> for UpdatePolicyPolicyId { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -53702,228 +60182,133 @@ pub mod types { }) } } - ///The request body for a developer to verify an end user's access token. + ///`UpdatePolicyXIdempotencyKey` /// ///
JSON schema /// /// ```json ///{ - /// "description": "The request body for a developer to verify an end user's access token.", - /// "type": "object", - /// "required": [ - /// "accessToken" - /// ], - /// "properties": { - /// "accessToken": { - /// "description": "The access token in JWT format to verify.", - /// "examples": [ - /// "eyJhbGciOiJFUzI1NiIsImtpZCI6IjA1ZGNmYTU1LWY1NzktNDg5YS1iNThhLTFlMDI5Nzk0N2VlNiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJjZHAtYXBpIiwiYXV0aF90eXBlIjoiZW1haWwiLCJleHAiOjE3NTM5ODAyOTksImlhdCI6MTc1Mzk3ODQ5OSwiaXNzIjoiY2RwLWFwaSIsImp0aSI6IjA3ZWY5M2JlLTYzMDQtNGQ1YS05NmE3LWJlMGI5MWI0ZTE3NCIsInByb2plY3RfaWQiOiJjNzRkOGI4OC0wOTNiLTQyZDItOGE4Yy1kZGM1YzVlMGViNDMiLCJzdWIiOiJjYTM4YTM4ZC0xNmE5LTRkMjYtYTcxZC0zOWY2NmY5YzZiN2UifQ.1SU0pOy-WR002qUw4hd_UmZWRSLz-ZL6v7PvQvZMKVE6a51x_tqeUeRGaTGuYl1whg0eccMObmK7FqXKRH6E4g" - /// ], - /// "type": "string" - /// } - /// } + /// "type": "string", + /// "maxLength": 128, + /// "minLength": 1 ///} /// ``` ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct ValidateEndUserAccessTokenBody { - ///The access token in JWT format to verify. - #[serde(rename = "accessToken")] - pub access_token: ::std::string::String, + #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct UpdatePolicyXIdempotencyKey(::std::string::String); + impl ::std::ops::Deref for UpdatePolicyXIdempotencyKey { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } } - impl ::std::convert::From<&ValidateEndUserAccessTokenBody> for ValidateEndUserAccessTokenBody { - fn from(value: &ValidateEndUserAccessTokenBody) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: UpdatePolicyXIdempotencyKey) -> Self { + value.0 + } + } + impl ::std::convert::From<&UpdatePolicyXIdempotencyKey> for UpdatePolicyXIdempotencyKey { + fn from(value: &UpdatePolicyXIdempotencyKey) -> Self { value.clone() } } - impl ValidateEndUserAccessTokenBody { - pub fn builder() -> builder::ValidateEndUserAccessTokenBody { - Default::default() + impl ::std::str::FromStr for UpdatePolicyXIdempotencyKey { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + if value.chars().count() > 128usize { + return Err("longer than 128 characters".into()); + } + if value.chars().count() < 1usize { + return Err("shorter than 1 characters".into()); + } + Ok(Self(value.to_string())) } } - ///`VerifyX402PaymentBody` - /// - ///
JSON schema - /// - /// ```json - ///{ - /// "type": "object", - /// "required": [ - /// "paymentPayload", - /// "paymentRequirements", - /// "x402Version" - /// ], - /// "properties": { - /// "paymentPayload": { - /// "$ref": "#/components/schemas/x402PaymentPayload" - /// }, - /// "paymentRequirements": { - /// "$ref": "#/components/schemas/x402PaymentRequirements" - /// }, - /// "x402Version": { - /// "$ref": "#/components/schemas/X402Version" - /// } - /// } - ///} - /// ``` - ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct VerifyX402PaymentBody { - #[serde(rename = "paymentPayload")] - pub payment_payload: X402PaymentPayload, - #[serde(rename = "paymentRequirements")] - pub payment_requirements: X402PaymentRequirements, - #[serde(rename = "x402Version")] - pub x402_version: X402Version, - } - impl ::std::convert::From<&VerifyX402PaymentBody> for VerifyX402PaymentBody { - fn from(value: &VerifyX402PaymentBody) -> Self { - value.clone() + impl ::std::convert::TryFrom<&str> for UpdatePolicyXIdempotencyKey { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() } } - impl VerifyX402PaymentBody { - pub fn builder() -> builder::VerifyX402PaymentBody { - Default::default() + impl ::std::convert::TryFrom<&::std::string::String> for UpdatePolicyXIdempotencyKey { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() } } - ///`VerifyX402PaymentResponse` - /// - ///
JSON schema - /// - /// ```json - ///{ - /// "type": "object", - /// "required": [ - /// "isValid", - /// "payer" - /// ], - /// "properties": { - /// "invalidMessage": { - /// "description": "The message describing the invalid reason.", - /// "examples": [ - /// "Insufficient funds" - /// ], - /// "type": "string" - /// }, - /// "invalidReason": { - /// "$ref": "#/components/schemas/x402VerifyInvalidReason" - /// }, - /// "isValid": { - /// "description": "Indicates whether the payment is valid.", - /// "examples": [ - /// false - /// ], - /// "type": "boolean" - /// }, - /// "payer": { - /// "description": "The onchain address of the client that is paying for the resource.\n\nFor EVM networks, the payer will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, the payer will be a base58-encoded Solana address.", - /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" - /// ], - /// "type": "string", - /// "pattern": "^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$" - /// } - /// } - ///} - /// ``` - ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct VerifyX402PaymentResponse { - ///The message describing the invalid reason. - #[serde( - rename = "invalidMessage", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub invalid_message: ::std::option::Option<::std::string::String>, - #[serde( - rename = "invalidReason", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub invalid_reason: ::std::option::Option, - ///Indicates whether the payment is valid. - #[serde(rename = "isValid")] - pub is_valid: bool, - /**The onchain address of the client that is paying for the resource. - - For EVM networks, the payer will be a 0x-prefixed, checksum EVM address. - - For Solana-based networks, the payer will be a base58-encoded Solana address.*/ - pub payer: VerifyX402PaymentResponsePayer, - } - impl ::std::convert::From<&VerifyX402PaymentResponse> for VerifyX402PaymentResponse { - fn from(value: &VerifyX402PaymentResponse) -> Self { - value.clone() + impl ::std::convert::TryFrom<::std::string::String> for UpdatePolicyXIdempotencyKey { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() } } - impl VerifyX402PaymentResponse { - pub fn builder() -> builder::VerifyX402PaymentResponse { - Default::default() + impl<'de> ::serde::Deserialize<'de> for UpdatePolicyXIdempotencyKey { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) } } - /**The onchain address of the client that is paying for the resource. - - For EVM networks, the payer will be a 0x-prefixed, checksum EVM address. - - For Solana-based networks, the payer will be a base58-encoded Solana address.*/ + ///`UpdateSolanaAccountAddress` /// ///
JSON schema /// /// ```json ///{ - /// "description": "The onchain address of the client that is paying for the resource.\n\nFor EVM networks, the payer will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, the payer will be a base58-encoded Solana address.", - /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" - /// ], /// "type": "string", - /// "pattern": "^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$" + /// "pattern": "^[1-9A-HJ-NP-Za-km-z]{32,44}$" ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct VerifyX402PaymentResponsePayer(::std::string::String); - impl ::std::ops::Deref for VerifyX402PaymentResponsePayer { + pub struct UpdateSolanaAccountAddress(::std::string::String); + impl ::std::ops::Deref for UpdateSolanaAccountAddress { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: VerifyX402PaymentResponsePayer) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: UpdateSolanaAccountAddress) -> Self { value.0 } } - impl ::std::convert::From<&VerifyX402PaymentResponsePayer> for VerifyX402PaymentResponsePayer { - fn from(value: &VerifyX402PaymentResponsePayer) -> Self { + impl ::std::convert::From<&UpdateSolanaAccountAddress> for UpdateSolanaAccountAddress { + fn from(value: &UpdateSolanaAccountAddress) -> Self { value.clone() } } - impl ::std::str::FromStr for VerifyX402PaymentResponsePayer { + impl ::std::str::FromStr for UpdateSolanaAccountAddress { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$") - .unwrap() + ::regress::Regex::new("^[1-9A-HJ-NP-Za-km-z]{32,44}$").unwrap() }); if PATTERN.find(value).is_none() { - return Err( - "doesn't match pattern \"^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$\"" - .into(), - ); + return Err("doesn't match pattern \"^[1-9A-HJ-NP-Za-km-z]{32,44}$\"".into()); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for VerifyX402PaymentResponsePayer { + impl ::std::convert::TryFrom<&str> for UpdateSolanaAccountAddress { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for VerifyX402PaymentResponsePayer { + impl ::std::convert::TryFrom<&::std::string::String> for UpdateSolanaAccountAddress { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -53931,7 +60316,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for VerifyX402PaymentResponsePayer { + impl ::std::convert::TryFrom<::std::string::String> for UpdateSolanaAccountAddress { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -53939,7 +60324,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for VerifyX402PaymentResponsePayer { + impl<'de> ::serde::Deserialize<'de> for UpdateSolanaAccountAddress { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -53951,364 +60336,131 @@ pub mod types { }) } } - ///Response containing a list of webhook event delivery attempts. - /// - ///
JSON schema - /// - /// ```json - ///{ - /// "description": "Response containing a list of webhook event delivery attempts.", - /// "examples": [ - /// { - /// "events": [ - /// { - /// "createdAt": "2025-01-15T10:30:00Z", - /// "eventId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", - /// "eventTypeName": "onchain.activity.detected", - /// "response": { - /// "body": "ok", - /// "elapsedTimeMs": 142, - /// "httpCode": 200 - /// }, - /// "retryCount": 0, - /// "status": "succeeded", - /// "succeededAt": "2025-01-15T10:30:02Z" - /// } - /// ] - /// } - /// ], - /// "type": "object", - /// "required": [ - /// "events" - /// ], - /// "properties": { - /// "events": { - /// "description": "The list of webhook event delivery attempts.", - /// "type": "array", - /// "items": { - /// "$ref": "#/components/schemas/WebhookEventResponse" - /// } - /// } - /// } - ///} - /// ``` - ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct WebhookEventListResponse { - ///The list of webhook event delivery attempts. - pub events: ::std::vec::Vec, - } - impl ::std::convert::From<&WebhookEventListResponse> for WebhookEventListResponse { - fn from(value: &WebhookEventListResponse) -> Self { - value.clone() - } - } - impl WebhookEventListResponse { - pub fn builder() -> builder::WebhookEventListResponse { - Default::default() - } - } - ///Details of a webhook event delivery attempt for a subscription. + ///`UpdateSolanaAccountBody` /// ///
JSON schema /// /// ```json ///{ - /// "description": "Details of a webhook event delivery attempt for a subscription.", - /// "examples": [ - /// { - /// "createdAt": "2025-01-15T10:30:00Z", - /// "eventId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", - /// "eventTypeName": "onchain.activity.detected", - /// "response": { - /// "body": "ok", - /// "elapsedTimeMs": 142, - /// "httpCode": 200 - /// }, - /// "retryCount": 0, - /// "status": "succeeded", - /// "succeededAt": "2025-01-15T10:30:02Z" - /// } - /// ], /// "type": "object", - /// "required": [ - /// "createdAt", - /// "eventId", - /// "eventTypeName", - /// "retryCount", - /// "status" - /// ], /// "properties": { - /// "createdAt": { - /// "description": "Timestamp when the event delivery attempt was created.", - /// "examples": [ - /// "2025-01-15T10:30:00Z" - /// ], - /// "type": "string", - /// "format": "date-time" - /// }, - /// "eventId": { - /// "description": "Unique identifier for the webhook event.", - /// "examples": [ - /// "a1b2c3d4-e5f6-7890-abcd-ef1234567890" - /// ], - /// "type": "string" - /// }, - /// "eventTypeName": { - /// "description": "The type of event that was delivered (e.g., \"onchain.activity.detected\").", - /// "examples": [ - /// "onchain.activity.detected" - /// ], - /// "type": "string" - /// }, - /// "response": { - /// "$ref": "#/components/schemas/WebhookEventResponseDetail" - /// }, - /// "retryCount": { - /// "description": "Number of delivery retry attempts so far.", - /// "examples": [ - /// 0 - /// ], - /// "type": "integer" - /// }, - /// "status": { - /// "description": "Current delivery status of the event.", + /// "accountPolicy": { + /// "description": "The ID of the account-level policy to apply to the account, or an empty string to unset attached policy.", /// "examples": [ - /// "succeeded" + /// "123e4567-e89b-12d3-a456-426614174000" /// ], /// "type": "string", - /// "enum": [ - /// "pending", - /// "processing", - /// "succeeded", - /// "failed", - /// "retrying" - /// ] + /// "pattern": "(^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$)|(^$)", + /// "x-audience": "public" /// }, - /// "succeededAt": { - /// "description": "Timestamp when the event was successfully delivered. Only present if status is \"succeeded\".", + /// "name": { + /// "description": "An optional name for the account. Account names can consist of alphanumeric characters and hyphens, and be between 2 and 36 characters long.\nAccount names must be unique across all Solana accounts in the developer's CDP Project.", /// "examples": [ - /// "2025-01-15T10:30:02Z" + /// "my-wallet" /// ], /// "type": "string", - /// "format": "date-time" + /// "pattern": "^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct WebhookEventResponse { - ///Timestamp when the event delivery attempt was created. - #[serde(rename = "createdAt")] - pub created_at: ::chrono::DateTime<::chrono::offset::Utc>, - ///Unique identifier for the webhook event. - #[serde(rename = "eventId")] - pub event_id: ::std::string::String, - ///The type of event that was delivered (e.g., "onchain.activity.detected"). - #[serde(rename = "eventTypeName")] - pub event_type_name: ::std::string::String, - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub response: ::std::option::Option, - ///Number of delivery retry attempts so far. - #[serde(rename = "retryCount")] - pub retry_count: i64, - ///Current delivery status of the event. - pub status: WebhookEventResponseStatus, - ///Timestamp when the event was successfully delivered. Only present if status is "succeeded". + pub struct UpdateSolanaAccountBody { + ///The ID of the account-level policy to apply to the account, or an empty string to unset attached policy. #[serde( - rename = "succeededAt", + rename = "accountPolicy", default, skip_serializing_if = "::std::option::Option::is_none" )] - pub succeeded_at: ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, - } - impl ::std::convert::From<&WebhookEventResponse> for WebhookEventResponse { - fn from(value: &WebhookEventResponse) -> Self { - value.clone() - } - } - impl WebhookEventResponse { - pub fn builder() -> builder::WebhookEventResponse { - Default::default() - } - } - ///Details of the HTTP response received from the webhook target. - /// - ///
JSON schema - /// - /// ```json - ///{ - /// "description": "Details of the HTTP response received from the webhook target.", - /// "examples": [ - /// { - /// "body": "ok", - /// "elapsedTimeMs": 142, - /// "httpCode": 200 - /// } - /// ], - /// "type": "object", - /// "properties": { - /// "body": { - /// "description": "Response body returned by the webhook target.", - /// "examples": [ - /// "ok" - /// ], - /// "type": "string" - /// }, - /// "elapsedTimeMs": { - /// "description": "Round-trip time of the webhook delivery in milliseconds.", - /// "examples": [ - /// 142 - /// ], - /// "type": "integer" - /// }, - /// "errorName": { - /// "description": "Error name if the delivery failed (e.g., timeout, connection_refused).", - /// "examples": [ - /// "timeout" - /// ], - /// "type": "string" - /// }, - /// "httpCode": { - /// "description": "HTTP status code returned by the webhook target.", - /// "examples": [ - /// 200 - /// ], - /// "type": "integer" - /// } - /// } - ///} - /// ``` - ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct WebhookEventResponseDetail { - ///Response body returned by the webhook target. + pub account_policy: ::std::option::Option, + /**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 Solana accounts in the developer's CDP Project.*/ #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub body: ::std::option::Option<::std::string::String>, - ///Round-trip time of the webhook delivery in milliseconds. - #[serde( - rename = "elapsedTimeMs", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub elapsed_time_ms: ::std::option::Option, - ///Error name if the delivery failed (e.g., timeout, connection_refused). - #[serde( - rename = "errorName", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub error_name: ::std::option::Option<::std::string::String>, - ///HTTP status code returned by the webhook target. - #[serde( - rename = "httpCode", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub http_code: ::std::option::Option, + pub name: ::std::option::Option, } - impl ::std::convert::From<&WebhookEventResponseDetail> for WebhookEventResponseDetail { - fn from(value: &WebhookEventResponseDetail) -> Self { + impl ::std::convert::From<&UpdateSolanaAccountBody> for UpdateSolanaAccountBody { + fn from(value: &UpdateSolanaAccountBody) -> Self { value.clone() } } - impl ::std::default::Default for WebhookEventResponseDetail { + impl ::std::default::Default for UpdateSolanaAccountBody { fn default() -> Self { Self { - body: Default::default(), - elapsed_time_ms: Default::default(), - error_name: Default::default(), - http_code: Default::default(), + account_policy: Default::default(), + name: Default::default(), } } } - impl WebhookEventResponseDetail { - pub fn builder() -> builder::WebhookEventResponseDetail { + impl UpdateSolanaAccountBody { + pub fn builder() -> builder::UpdateSolanaAccountBody { Default::default() } } - ///Current delivery status of the event. + ///The ID of the account-level policy to apply to the account, or an empty string to unset attached policy. /// ///
JSON schema /// /// ```json ///{ - /// "description": "Current delivery status of the event.", + /// "description": "The ID of the account-level policy to apply to the account, or an empty string to unset attached policy.", /// "examples": [ - /// "succeeded" + /// "123e4567-e89b-12d3-a456-426614174000" /// ], /// "type": "string", - /// "enum": [ - /// "pending", - /// "processing", - /// "succeeded", - /// "failed", - /// "retrying" - /// ] + /// "pattern": "(^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$)|(^$)", + /// "x-audience": "public" ///} /// ``` ///
- #[derive( - ::serde::Deserialize, - ::serde::Serialize, - Clone, - Copy, - Debug, - Eq, - Hash, - Ord, - PartialEq, - PartialOrd, - )] - pub enum WebhookEventResponseStatus { - #[serde(rename = "pending")] - Pending, - #[serde(rename = "processing")] - Processing, - #[serde(rename = "succeeded")] - Succeeded, - #[serde(rename = "failed")] - Failed, - #[serde(rename = "retrying")] - Retrying, + #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct UpdateSolanaAccountBodyAccountPolicy(::std::string::String); + impl ::std::ops::Deref for UpdateSolanaAccountBodyAccountPolicy { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } } - impl ::std::convert::From<&Self> for WebhookEventResponseStatus { - fn from(value: &WebhookEventResponseStatus) -> Self { - value.clone() + impl ::std::convert::From for ::std::string::String { + fn from(value: UpdateSolanaAccountBodyAccountPolicy) -> Self { + value.0 } } - impl ::std::fmt::Display for WebhookEventResponseStatus { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - match *self { - Self::Pending => f.write_str("pending"), - Self::Processing => f.write_str("processing"), - Self::Succeeded => f.write_str("succeeded"), - Self::Failed => f.write_str("failed"), - Self::Retrying => f.write_str("retrying"), - } + impl ::std::convert::From<&UpdateSolanaAccountBodyAccountPolicy> + for UpdateSolanaAccountBodyAccountPolicy + { + fn from(value: &UpdateSolanaAccountBodyAccountPolicy) -> Self { + value.clone() } } - impl ::std::str::FromStr for WebhookEventResponseStatus { + impl ::std::str::FromStr for UpdateSolanaAccountBodyAccountPolicy { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - match value { - "pending" => Ok(Self::Pending), - "processing" => Ok(Self::Processing), - "succeeded" => Ok(Self::Succeeded), - "failed" => Ok(Self::Failed), - "retrying" => Ok(Self::Retrying), - _ => Err("invalid value".into()), + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new( + || { + ::regress::Regex::new( + "(^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$)|(^$)", + ) + .unwrap() + }, + ); + if PATTERN.find(value).is_none() { + return Err( + "doesn't match pattern \"(^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$)|(^$)\"" + .into(), + ); } + Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for WebhookEventResponseStatus { + impl ::std::convert::TryFrom<&str> for UpdateSolanaAccountBodyAccountPolicy { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for WebhookEventResponseStatus { + impl ::std::convert::TryFrom<&::std::string::String> for UpdateSolanaAccountBodyAccountPolicy { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -54316,7 +60468,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for WebhookEventResponseStatus { + impl ::std::convert::TryFrom<::std::string::String> for UpdateSolanaAccountBodyAccountPolicy { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -54324,478 +60476,154 @@ pub mod types { value.parse() } } - ///`WebhookSubscriptionListResponse` - /// - ///
JSON schema - /// - /// ```json - ///{ - /// "allOf": [ - /// { - /// "description": "Response containing a list of webhook subscriptions.", - /// "type": "object", - /// "required": [ - /// "subscriptions" - /// ], - /// "properties": { - /// "subscriptions": { - /// "description": "The list of webhook subscriptions.", - /// "type": "array", - /// "items": { - /// "$ref": "#/components/schemas/WebhookSubscriptionResponse" - /// } - /// } - /// } - /// }, - /// { - /// "$ref": "#/components/schemas/ListResponse" - /// } - /// ] - ///} - /// ``` - ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct WebhookSubscriptionListResponse { - ///The token for the next page of items, if any. - #[serde( - rename = "nextPageToken", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub next_page_token: ::std::option::Option<::std::string::String>, - ///The list of webhook subscriptions. - pub subscriptions: ::std::vec::Vec, - } - impl ::std::convert::From<&WebhookSubscriptionListResponse> for WebhookSubscriptionListResponse { - fn from(value: &WebhookSubscriptionListResponse) -> Self { - value.clone() - } - } - impl WebhookSubscriptionListResponse { - pub fn builder() -> builder::WebhookSubscriptionListResponse { - Default::default() + impl<'de> ::serde::Deserialize<'de> for UpdateSolanaAccountBodyAccountPolicy { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) } } - /**Request to create a new webhook subscription with support for multi-label filtering. - */ + /**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 Solana accounts in the developer's CDP Project.*/ /// ///
JSON schema /// /// ```json ///{ - /// "description": "Request to create a new webhook subscription with support for multi-label filtering.\n", - /// "type": "object", - /// "required": [ - /// "eventTypes", - /// "isEnabled", - /// "target" + /// "description": "An optional name for the account. Account names can consist of alphanumeric characters and hyphens, and be between 2 and 36 characters long.\nAccount names must be unique across all Solana accounts in the developer's CDP Project.", + /// "examples": [ + /// "my-wallet" /// ], - /// "properties": { - /// "description": { - /// "description": "Description of the webhook subscription.", - /// "examples": [ - /// "Subscription for token transfer events" - /// ], - /// "allOf": [ - /// { - /// "$ref": "#/components/schemas/Description" - /// } - /// ] - /// }, - /// "eventTypes": { - /// "description": "Types of events to subscribe to. Event types follow a dot-separated format:\nservice.resource.verb (e.g., \"onchain.activity.detected\", \"wallet.activity.detected\", \"onramp.transaction.created\",\n\"acceptance.payment_session.authorization_succeeded\").\nThe subscription will only receive events matching these types AND the label filter(s).\n", - /// "examples": [ - /// [ - /// "onchain.activity.detected" - /// ] - /// ], - /// "type": "array", - /// "items": { - /// "type": "string" - /// } - /// }, - /// "isEnabled": { - /// "description": "Whether the subscription is enabled.", - /// "examples": [ - /// true - /// ], - /// "type": "boolean" - /// }, - /// "labels": { - /// "description": "Optional. Multi-label filters using total overlap logic. Total overlap means the subscription will only trigger when\nan event contains ALL the key-value pairs specified here. Additional labels on\nthe event are allowed and will not prevent matching. Omit to receive all events for the selected event types.\n\n**Note:** Currently, labels are supported for onchain webhooks only.\n\nSee [allowed labels for onchain webhooks](https://docs.cdp.coinbase.com/api-reference/v2/rest-api/webhooks/create-webhook-subscription#onchain-label-filtering).\n", - /// "examples": [ - /// { - /// "contract_address": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913", - /// "event_name": "Transfer", - /// "network": "base-mainnet" - /// } - /// ], - /// "type": "object", - /// "additionalProperties": { - /// "type": "string" - /// } - /// }, - /// "metadata": { - /// "$ref": "#/components/schemas/Metadata" - /// }, - /// "target": { - /// "$ref": "#/components/schemas/WebhookTarget" - /// } - /// } + /// "type": "string", + /// "pattern": "^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$" ///} /// ``` ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct WebhookSubscriptionRequest { - ///Description of the webhook subscription. - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub description: ::std::option::Option, - /**Types of events to subscribe to. Event types follow a dot-separated format: - service.resource.verb (e.g., "onchain.activity.detected", "wallet.activity.detected", "onramp.transaction.created", - "acceptance.payment_session.authorization_succeeded"). - The subscription will only receive events matching these types AND the label filter(s). - */ - #[serde(rename = "eventTypes")] - pub event_types: ::std::vec::Vec<::std::string::String>, - ///Whether the subscription is enabled. - #[serde(rename = "isEnabled")] - pub is_enabled: bool, - /**Optional. Multi-label filters using total overlap logic. Total overlap means the subscription will only trigger when - an event contains ALL the key-value pairs specified here. Additional labels on - the event are allowed and will not prevent matching. Omit to receive all events for the selected event types. - - **Note:** Currently, labels are supported for onchain webhooks only. - - See [allowed labels for onchain webhooks](https://docs.cdp.coinbase.com/api-reference/v2/rest-api/webhooks/create-webhook-subscription#onchain-label-filtering). - */ - #[serde( - default, - skip_serializing_if = ":: std :: collections :: HashMap::is_empty" - )] - pub labels: ::std::collections::HashMap<::std::string::String, ::std::string::String>, - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub metadata: ::std::option::Option, - pub target: WebhookTarget, - } - impl ::std::convert::From<&WebhookSubscriptionRequest> for WebhookSubscriptionRequest { - fn from(value: &WebhookSubscriptionRequest) -> Self { - value.clone() + #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct UpdateSolanaAccountBodyName(::std::string::String); + impl ::std::ops::Deref for UpdateSolanaAccountBodyName { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 } } - impl WebhookSubscriptionRequest { - pub fn builder() -> builder::WebhookSubscriptionRequest { - Default::default() + impl ::std::convert::From for ::std::string::String { + fn from(value: UpdateSolanaAccountBodyName) -> Self { + value.0 } } - ///Response containing webhook subscription details. - /// - ///
JSON schema - /// - /// ```json - ///{ - /// "description": "Response containing webhook subscription details.", - /// "examples": [ - /// { - /// "createdAt": "2025-11-12T09:19:52.051Z", - /// "description": "USDC Transfer events to specific address.", - /// "eventTypes": [ - /// "onchain.activity.detected" - /// ], - /// "isEnabled": true, - /// "labels": { - /// "contract_address": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913", - /// "event_name": "Transfer", - /// "network": "base-mainnet", - /// "transaction_to": "0xf5042e6ffac5a625d4e7848e0b01373d8eb9e222" - /// }, - /// "metadata": { - /// "secret": "a1b2c3d4-e5f6-7890-abcd-ef1234567890" - /// }, - /// "secret": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", - /// "subscriptionId": "123e4567-e89b-12d3-a456-426614174000", - /// "target": { - /// "url": "https://api.example.com/webhooks" - /// }, - /// "updatedAt": "2025-11-13T11:30:00.000Z" - /// } - /// ], - /// "type": "object", - /// "required": [ - /// "createdAt", - /// "eventTypes", - /// "isEnabled", - /// "secret", - /// "subscriptionId", - /// "target" - /// ], - /// "properties": { - /// "createdAt": { - /// "description": "When the subscription was created.", - /// "examples": [ - /// "2025-01-15T10:30:00Z" - /// ], - /// "type": "string", - /// "format": "date-time" - /// }, - /// "description": { - /// "description": "Description of the webhook subscription.", - /// "examples": [ - /// "Subscription for token transfer events" - /// ], - /// "allOf": [ - /// { - /// "$ref": "#/components/schemas/Description" - /// } - /// ] - /// }, - /// "eventTypes": { - /// "description": "Types of events to subscribe to. Event types follow a dot-separated format:\nservice.resource.verb (e.g., \"onchain.activity.detected\", \"wallet.activity.detected\", \"onramp.transaction.created\",\n\"acceptance.payment_session.authorization_succeeded\").\n", - /// "examples": [ - /// [ - /// "onchain.activity.detected" - /// ] - /// ], - /// "type": "array", - /// "items": { - /// "type": "string" - /// } - /// }, - /// "isEnabled": { - /// "description": "Whether the subscription is enabled.", - /// "examples": [ - /// true - /// ], - /// "type": "boolean" - /// }, - /// "labels": { - /// "description": "Multi-label filters using total overlap logic. Total overlap means the subscription only triggers when events contain ALL these key-value pairs.\nPresent when subscription uses multi-label format.\n", - /// "examples": [ - /// { - /// "contract_address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", - /// "env": "dev", - /// "team": "payments" - /// } - /// ], - /// "type": "object", - /// "additionalProperties": { - /// "type": "string" - /// } - /// }, - /// "metadata": { - /// "description": "Additional metadata for the subscription.", - /// "examples": [ - /// { - /// "secret": "123e4567-e89b-12d3-a456-426614174000" - /// } - /// ], - /// "allOf": [ - /// { - /// "$ref": "#/components/schemas/Metadata" - /// }, - /// { - /// "type": "object", - /// "properties": { - /// "secret": { - /// "description": "Use the root-level `secret` field instead. Maintained for backward compatibility only.", - /// "deprecated": true, - /// "examples": [ - /// "123e4567-e89b-12d3-a456-426614174000" - /// ], - /// "type": "string", - /// "format": "uuid" - /// } - /// } - /// } - /// ] - /// }, - /// "secret": { - /// "description": "Secret for webhook signature validation.", - /// "examples": [ - /// "123e4567-e89b-12d3-a456-426614174000" - /// ], - /// "type": "string", - /// "format": "uuid" - /// }, - /// "subscriptionId": { - /// "description": "Unique identifier for the subscription.", - /// "examples": [ - /// "123e4567-e89b-12d3-a456-426614174000" - /// ], - /// "type": "string", - /// "format": "uuid" - /// }, - /// "target": { - /// "$ref": "#/components/schemas/WebhookTarget" - /// }, - /// "updatedAt": { - /// "description": "When the subscription was last updated.", - /// "examples": [ - /// "2025-01-16T14:00:00Z" - /// ], - /// "type": "string", - /// "format": "date-time" - /// } - /// } - ///} - /// ``` - ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct WebhookSubscriptionResponse { - ///When the subscription was created. - #[serde(rename = "createdAt")] - pub created_at: ::chrono::DateTime<::chrono::offset::Utc>, - ///Description of the webhook subscription. - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub description: ::std::option::Option, - /**Types of events to subscribe to. Event types follow a dot-separated format: - service.resource.verb (e.g., "onchain.activity.detected", "wallet.activity.detected", "onramp.transaction.created", - "acceptance.payment_session.authorization_succeeded"). - */ - #[serde(rename = "eventTypes")] - pub event_types: ::std::vec::Vec<::std::string::String>, - ///Whether the subscription is enabled. - #[serde(rename = "isEnabled")] - pub is_enabled: bool, - /**Multi-label filters using total overlap logic. Total overlap means the subscription only triggers when events contain ALL these key-value pairs. - Present when subscription uses multi-label format. - */ - #[serde( - default, - skip_serializing_if = ":: std :: collections :: HashMap::is_empty" - )] - pub labels: ::std::collections::HashMap<::std::string::String, ::std::string::String>, - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub metadata: ::std::option::Option, - ///Secret for webhook signature validation. - pub secret: ::uuid::Uuid, - ///Unique identifier for the subscription. - #[serde(rename = "subscriptionId")] - pub subscription_id: ::uuid::Uuid, - pub target: WebhookTarget, - ///When the subscription was last updated. - #[serde( - rename = "updatedAt", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub updated_at: ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, - } - impl ::std::convert::From<&WebhookSubscriptionResponse> for WebhookSubscriptionResponse { - fn from(value: &WebhookSubscriptionResponse) -> Self { + impl ::std::convert::From<&UpdateSolanaAccountBodyName> for UpdateSolanaAccountBodyName { + fn from(value: &UpdateSolanaAccountBodyName) -> Self { value.clone() } } - impl WebhookSubscriptionResponse { - pub fn builder() -> builder::WebhookSubscriptionResponse { - Default::default() + impl ::std::str::FromStr for UpdateSolanaAccountBodyName { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err( + "doesn't match pattern \"^[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$\"".into(), + ); + } + Ok(Self(value.to_string())) } } - ///Additional metadata for the subscription. - /// - ///
JSON schema - /// - /// ```json - ///{ - /// "description": "Additional metadata for the subscription.", - /// "examples": [ - /// { - /// "secret": "123e4567-e89b-12d3-a456-426614174000" - /// } - /// ], - /// "allOf": [ - /// { - /// "$ref": "#/components/schemas/Metadata" - /// }, - /// { - /// "type": "object", - /// "properties": { - /// "secret": { - /// "description": "Use the root-level `secret` field instead. Maintained for backward compatibility only.", - /// "deprecated": true, - /// "examples": [ - /// "123e4567-e89b-12d3-a456-426614174000" - /// ], - /// "type": "string", - /// "format": "uuid" - /// } - /// } - /// } - /// ] - ///} - /// ``` - ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct WebhookSubscriptionResponseMetadata { - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub secret: ::std::option::Option<::uuid::Uuid>, - #[serde(flatten)] - pub extra: ::std::collections::HashMap< - ::std::string::String, - WebhookSubscriptionResponseMetadataExtraValue, - >, + impl ::std::convert::TryFrom<&str> for UpdateSolanaAccountBodyName { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } } - impl ::std::convert::From<&WebhookSubscriptionResponseMetadata> - for WebhookSubscriptionResponseMetadata - { - fn from(value: &WebhookSubscriptionResponseMetadata) -> Self { - value.clone() + impl ::std::convert::TryFrom<&::std::string::String> for UpdateSolanaAccountBodyName { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() } } - impl WebhookSubscriptionResponseMetadata { - pub fn builder() -> builder::WebhookSubscriptionResponseMetadata { - Default::default() + impl ::std::convert::TryFrom<::std::string::String> for UpdateSolanaAccountBodyName { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() } } - ///`WebhookSubscriptionResponseMetadataExtraValue` + impl<'de> ::serde::Deserialize<'de> for UpdateSolanaAccountBodyName { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///`UpdateSolanaAccountXIdempotencyKey` /// ///
JSON schema /// /// ```json ///{ /// "type": "string", - /// "maxLength": 500 + /// "maxLength": 128, + /// "minLength": 1 ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct WebhookSubscriptionResponseMetadataExtraValue(::std::string::String); - impl ::std::ops::Deref for WebhookSubscriptionResponseMetadataExtraValue { + pub struct UpdateSolanaAccountXIdempotencyKey(::std::string::String); + impl ::std::ops::Deref for UpdateSolanaAccountXIdempotencyKey { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: WebhookSubscriptionResponseMetadataExtraValue) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: UpdateSolanaAccountXIdempotencyKey) -> Self { value.0 } } - impl ::std::convert::From<&WebhookSubscriptionResponseMetadataExtraValue> - for WebhookSubscriptionResponseMetadataExtraValue + impl ::std::convert::From<&UpdateSolanaAccountXIdempotencyKey> + for UpdateSolanaAccountXIdempotencyKey { - fn from(value: &WebhookSubscriptionResponseMetadataExtraValue) -> Self { + fn from(value: &UpdateSolanaAccountXIdempotencyKey) -> Self { value.clone() } } - impl ::std::str::FromStr for WebhookSubscriptionResponseMetadataExtraValue { + impl ::std::str::FromStr for UpdateSolanaAccountXIdempotencyKey { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - if value.chars().count() > 500usize { - return Err("longer than 500 characters".into()); + if value.chars().count() > 128usize { + return Err("longer than 128 characters".into()); + } + if value.chars().count() < 1usize { + return Err("shorter than 1 characters".into()); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for WebhookSubscriptionResponseMetadataExtraValue { + impl ::std::convert::TryFrom<&str> for UpdateSolanaAccountXIdempotencyKey { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> - for WebhookSubscriptionResponseMetadataExtraValue - { + impl ::std::convert::TryFrom<&::std::string::String> for UpdateSolanaAccountXIdempotencyKey { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -54803,9 +60631,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> - for WebhookSubscriptionResponseMetadataExtraValue - { + impl ::std::convert::TryFrom<::std::string::String> for UpdateSolanaAccountXIdempotencyKey { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -54813,7 +60639,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for WebhookSubscriptionResponseMetadataExtraValue { + impl<'de> ::serde::Deserialize<'de> for UpdateSolanaAccountXIdempotencyKey { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -54825,581 +60651,498 @@ pub mod types { }) } } - /**Request to update an existing webhook subscription. - */ + ///A valid URI. /// ///
JSON schema /// /// ```json ///{ - /// "description": "Request to update an existing webhook subscription.\n", - /// "type": "object", - /// "required": [ - /// "eventTypes", - /// "isEnabled", - /// "target" + /// "description": "A valid URI.", + /// "examples": [ + /// "foo://bar" + /// ], + /// "type": "string", + /// "format": "uri", + /// "maxLength": 2048, + /// "minLength": 5, + /// "pattern": "^.*://.*$" + ///} + /// ``` + ///
+ #[derive( + ::serde::Deserialize, ::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, + )] + #[serde(transparent)] + pub struct Uri(pub ::std::string::String); + impl ::std::ops::Deref for Uri { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: Uri) -> Self { + value.0 + } + } + impl ::std::convert::From<&Uri> for Uri { + fn from(value: &Uri) -> Self { + value.clone() + } + } + impl ::std::convert::From<::std::string::String> for Uri { + fn from(value: ::std::string::String) -> Self { + Self(value) + } + } + impl ::std::str::FromStr for Uri { + type Err = ::std::convert::Infallible; + fn from_str(value: &str) -> ::std::result::Result { + Ok(Self(value.to_string())) + } + } + impl ::std::fmt::Display for Uri { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + self.0.fmt(f) + } + } + ///A valid HTTP or HTTPS URL. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "A valid HTTP or HTTPS URL.", + /// "examples": [ + /// "https://example.com" + /// ], + /// "type": "string", + /// "format": "uri", + /// "maxLength": 2048, + /// "minLength": 11, + /// "pattern": "^https?://.*$" + ///} + /// ``` + ///
+ #[derive( + ::serde::Deserialize, ::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, + )] + #[serde(transparent)] + pub struct Url(pub ::std::string::String); + impl ::std::ops::Deref for Url { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: Url) -> Self { + value.0 + } + } + impl ::std::convert::From<&Url> for Url { + fn from(value: &Url) -> Self { + value.clone() + } + } + impl ::std::convert::From<::std::string::String> for Url { + fn from(value: ::std::string::String) -> Self { + Self(value) + } + } + impl ::std::str::FromStr for Url { + type Err = ::std::convert::Infallible; + fn from_str(value: &str) -> ::std::result::Result { + Ok(Self(value.to_string())) + } + } + impl ::std::fmt::Display for Url { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + self.0.fmt(f) + } + } + ///The receipt that contains information about the execution of user operation. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The receipt that contains information about the execution of user operation.", + /// "examples": [ + /// { + /// "blockHash": "0x386544b58930c0ec9e8f3ed09fb4cdb76b9ae0a1a37ddcacebe3925b57978e65", + /// "blockNumber": 29338819, + /// "gasUsed": "100000", + /// "revert": { + /// "data": "0x123", + /// "message": "reason for failure" + /// } + /// } /// ], + /// "type": "object", /// "properties": { - /// "description": { - /// "description": "Description of the webhook subscription.", + /// "blockHash": { + /// "description": "The block hash of the block including the transaction as 0x-prefixed string.", /// "examples": [ - /// "Updated subscription for token transfer events" + /// "0x386544b58930c0ec9e8f3ed09fb4cdb76b9ae0a1a37ddcacebe3925b57978e65" /// ], - /// "allOf": [ - /// { - /// "$ref": "#/components/schemas/Description" - /// } - /// ] + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{64}$|^$" /// }, - /// "eventTypes": { - /// "description": "Types of events to subscribe to. Event types follow a three-part dot-separated format:\nservice.resource.verb (e.g., \"onchain.activity.detected\", \"wallet.activity.detected\", \"onramp.transaction.created\").\n", + /// "blockNumber": { + /// "description": "The block height (number) of the block including the transaction.", /// "examples": [ - /// [ - /// "onchain.activity.detected" - /// ] + /// 29338819 /// ], - /// "type": "array", - /// "items": { - /// "type": "string" - /// } + /// "type": "integer" /// }, - /// "isEnabled": { - /// "description": "Whether the subscription is enabled.", + /// "gasUsed": { + /// "description": "The gas used for landing this user operation.", /// "examples": [ - /// false + /// "100000" /// ], - /// "type": "boolean" + /// "type": "string" /// }, - /// "labels": { - /// "description": "Optional. Multi-label filters that trigger only when an event contains ALL of these key-value pairs.\n\n**Note:** Currently, labels are supported for onchain webhooks only.\n\nSee [allowed labels for onchain webhooks](https://docs.cdp.coinbase.com/api-reference/v2/rest-api/webhooks/create-webhook-subscription#onchain-label-filtering).\nOmit to receive all events for the selected event types.\n", + /// "revert": { + /// "$ref": "#/components/schemas/UserOperationReceiptRevert" + /// }, + /// "transactionHash": { + /// "description": "The hash of this transaction as 0x-prefixed string.", /// "examples": [ - /// { - /// "contract_address": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913", - /// "event_name": "Transfer", - /// "network": "base-mainnet" - /// } + /// "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" /// ], - /// "type": "object", - /// "additionalProperties": { - /// "type": "string" - /// } - /// }, - /// "metadata": { - /// "$ref": "#/components/schemas/Metadata" - /// }, - /// "target": { - /// "$ref": "#/components/schemas/WebhookTarget" + /// "type": "string", + /// "pattern": "^0x[a-fA-F0-9]{64}$" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct WebhookSubscriptionUpdateRequest { - ///Description of the webhook subscription. - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub description: ::std::option::Option, - /**Types of events to subscribe to. Event types follow a three-part dot-separated format: - service.resource.verb (e.g., "onchain.activity.detected", "wallet.activity.detected", "onramp.transaction.created"). - */ - #[serde(rename = "eventTypes")] - pub event_types: ::std::vec::Vec<::std::string::String>, - ///Whether the subscription is enabled. - #[serde(rename = "isEnabled")] - pub is_enabled: bool, - /**Optional. Multi-label filters that trigger only when an event contains ALL of these key-value pairs. - - **Note:** Currently, labels are supported for onchain webhooks only. - - See [allowed labels for onchain webhooks](https://docs.cdp.coinbase.com/api-reference/v2/rest-api/webhooks/create-webhook-subscription#onchain-label-filtering). - Omit to receive all events for the selected event types. - */ + pub struct UserOperationReceipt { + ///The block hash of the block including the transaction as 0x-prefixed string. #[serde( + rename = "blockHash", default, - skip_serializing_if = ":: std :: collections :: HashMap::is_empty" + skip_serializing_if = "::std::option::Option::is_none" )] - pub labels: ::std::collections::HashMap<::std::string::String, ::std::string::String>, + pub block_hash: ::std::option::Option, + ///The block height (number) of the block including the transaction. + #[serde( + rename = "blockNumber", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub block_number: ::std::option::Option, + ///The gas used for landing this user operation. + #[serde( + rename = "gasUsed", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub gas_used: ::std::option::Option<::std::string::String>, #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub metadata: ::std::option::Option, - pub target: WebhookTarget, + pub revert: ::std::option::Option, + ///The hash of this transaction as 0x-prefixed string. + #[serde( + rename = "transactionHash", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub transaction_hash: ::std::option::Option, } - impl ::std::convert::From<&WebhookSubscriptionUpdateRequest> for WebhookSubscriptionUpdateRequest { - fn from(value: &WebhookSubscriptionUpdateRequest) -> Self { + impl ::std::convert::From<&UserOperationReceipt> for UserOperationReceipt { + fn from(value: &UserOperationReceipt) -> Self { value.clone() } } - impl WebhookSubscriptionUpdateRequest { - pub fn builder() -> builder::WebhookSubscriptionUpdateRequest { + impl ::std::default::Default for UserOperationReceipt { + fn default() -> Self { + Self { + block_hash: Default::default(), + block_number: Default::default(), + gas_used: Default::default(), + revert: Default::default(), + transaction_hash: Default::default(), + } + } + } + impl UserOperationReceipt { + pub fn builder() -> builder::UserOperationReceipt { Default::default() } } - /**Target configuration for webhook delivery. - Specifies the destination URL and any custom headers to include in webhook requests. - */ + ///The block hash of the block including the transaction as 0x-prefixed string. /// ///
JSON schema /// /// ```json ///{ - /// "description": "Target configuration for webhook delivery.\nSpecifies the destination URL and any custom headers to include in webhook requests.\n", + /// "description": "The block hash of the block including the transaction as 0x-prefixed string.", /// "examples": [ - /// { - /// "headers": { - /// "Authorization": "Bearer token123", - /// "Content-Type": "application/json" - /// }, - /// "url": "https://api.example.com/webhooks" - /// } - /// ], - /// "type": "object", - /// "required": [ - /// "url" + /// "0x386544b58930c0ec9e8f3ed09fb4cdb76b9ae0a1a37ddcacebe3925b57978e65" /// ], - /// "properties": { - /// "headers": { - /// "description": "Additional headers to include in webhook requests.", - /// "examples": [ - /// { - /// "Authorization": "Bearer token123", - /// "Content-Type": "application/json" - /// } - /// ], - /// "type": "object", - /// "additionalProperties": { - /// "type": "string" - /// } - /// }, - /// "url": { - /// "description": "The webhook URL to deliver events to.", - /// "examples": [ - /// "https://api.example.com/webhooks" - /// ], - /// "allOf": [ - /// { - /// "$ref": "#/components/schemas/Url" - /// } - /// ] - /// } - /// } + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{64}$|^$" ///} /// ``` ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct WebhookTarget { - ///Additional headers to include in webhook requests. - #[serde( - default, - skip_serializing_if = ":: std :: collections :: HashMap::is_empty" - )] - pub headers: ::std::collections::HashMap<::std::string::String, ::std::string::String>, - ///The webhook URL to deliver events to. - pub url: Url, + #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct UserOperationReceiptBlockHash(::std::string::String); + impl ::std::ops::Deref for UserOperationReceiptBlockHash { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } } - impl ::std::convert::From<&WebhookTarget> for WebhookTarget { - fn from(value: &WebhookTarget) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: UserOperationReceiptBlockHash) -> Self { + value.0 + } + } + impl ::std::convert::From<&UserOperationReceiptBlockHash> for UserOperationReceiptBlockHash { + fn from(value: &UserOperationReceiptBlockHash) -> Self { value.clone() } } - impl WebhookTarget { - pub fn builder() -> builder::WebhookTarget { - Default::default() + impl ::std::str::FromStr for UserOperationReceiptBlockHash { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^0x[0-9a-fA-F]{64}$|^$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^0x[0-9a-fA-F]{64}$|^$\"".into()); + } + Ok(Self(value.to_string())) } } - ///Response containing x402 resources associated with a merchant payment address. + impl ::std::convert::TryFrom<&str> for UserOperationReceiptBlockHash { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for UserOperationReceiptBlockHash { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for UserOperationReceiptBlockHash { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for UserOperationReceiptBlockHash { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///The revert data if the user operation has reverted. /// ///
JSON schema /// /// ```json ///{ - /// "description": "Response containing x402 resources associated with a merchant payment address.", + /// "description": "The revert data if the user operation has reverted.", + /// "examples": [ + /// { + /// "data": "0x123", + /// "message": "reason for failure" + /// } + /// ], /// "type": "object", /// "required": [ - /// "pagination", - /// "payTo", - /// "resources", - /// "x402Version" + /// "data", + /// "message" /// ], /// "properties": { - /// "pagination": { - /// "description": "Pagination information for the response.", + /// "data": { + /// "description": "The 0x-prefixed raw hex string.", /// "examples": [ - /// { - /// "limit": 20, - /// "offset": 0, - /// "total": 10 - /// } + /// "0x123" /// ], - /// "type": "object", - /// "properties": { - /// "limit": { - /// "description": "The number of resources returned per page.", - /// "examples": [ - /// 20 - /// ], - /// "type": "integer" - /// }, - /// "offset": { - /// "description": "The offset of the first resource returned.", - /// "examples": [ - /// 0 - /// ], - /// "type": "integer" - /// }, - /// "total": { - /// "description": "The total number of resources associated with the merchant's payTo address.", - /// "examples": [ - /// 10 - /// ], - /// "type": "integer" - /// } - /// } - /// }, - /// "payTo": { - /// "$ref": "#/components/schemas/BlockchainAddress" + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]*$" /// }, - /// "resources": { - /// "description": "List of discovered x402 resources associated with the merchant's payTo address.", + /// "message": { + /// "description": "Human-readable revert reason if able to decode.", /// "examples": [ - /// [ - /// { - /// "accepts": [ - /// { - /// "amount": "1000000", - /// "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", - /// "maxTimeoutSeconds": 60, - /// "network": "eip155:8453", - /// "payTo": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "scheme": "exact" - /// } - /// ], - /// "description": "Premium API access for data analysis.", - /// "extensions": { - /// "bazaar": { - /// "info": { - /// "input": { - /// "method": "POST", - /// "type": "http" - /// } - /// }, - /// "schema": {} - /// } - /// }, - /// "lastUpdated": "2024-01-15T10:30:00Z", - /// "quality": { - /// "l30DaysTotalCalls": 42, - /// "l30DaysUniquePayers": 15, - /// "lastCalledAt": "2024-01-15T10:30:00Z" - /// }, - /// "resource": "https://api.example.com/premium/data", - /// "type": "http", - /// "x402Version": 2 - /// } - /// ] + /// "reason for failure" /// ], - /// "type": "array", - /// "items": { - /// "$ref": "#/components/schemas/x402DiscoveryResource" - /// } - /// }, - /// "x402Version": { - /// "$ref": "#/components/schemas/X402Version" + /// "type": "string" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402DiscoveryMerchantResponse { - pub pagination: X402DiscoveryMerchantResponsePagination, - #[serde(rename = "payTo")] - pub pay_to: BlockchainAddress, - ///List of discovered x402 resources associated with the merchant's payTo address. - pub resources: ::std::vec::Vec, - #[serde(rename = "x402Version")] - pub x402_version: X402Version, + pub struct UserOperationReceiptRevert { + ///The 0x-prefixed raw hex string. + pub data: UserOperationReceiptRevertData, + ///Human-readable revert reason if able to decode. + pub message: ::std::string::String, } - impl ::std::convert::From<&X402DiscoveryMerchantResponse> for X402DiscoveryMerchantResponse { - fn from(value: &X402DiscoveryMerchantResponse) -> Self { + impl ::std::convert::From<&UserOperationReceiptRevert> for UserOperationReceiptRevert { + fn from(value: &UserOperationReceiptRevert) -> Self { value.clone() } } - impl X402DiscoveryMerchantResponse { - pub fn builder() -> builder::X402DiscoveryMerchantResponse { + impl UserOperationReceiptRevert { + pub fn builder() -> builder::UserOperationReceiptRevert { Default::default() } } - ///Pagination information for the response. + ///The 0x-prefixed raw hex string. /// ///
JSON schema /// /// ```json ///{ - /// "description": "Pagination information for the response.", + /// "description": "The 0x-prefixed raw hex string.", /// "examples": [ - /// { - /// "limit": 20, - /// "offset": 0, - /// "total": 10 - /// } + /// "0x123" /// ], - /// "type": "object", - /// "properties": { - /// "limit": { - /// "description": "The number of resources returned per page.", - /// "examples": [ - /// 20 - /// ], - /// "type": "integer" - /// }, - /// "offset": { - /// "description": "The offset of the first resource returned.", - /// "examples": [ - /// 0 - /// ], - /// "type": "integer" - /// }, - /// "total": { - /// "description": "The total number of resources associated with the merchant's payTo address.", - /// "examples": [ - /// 10 - /// ], - /// "type": "integer" - /// } - /// } + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]*$" ///} /// ``` ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402DiscoveryMerchantResponsePagination { - ///The number of resources returned per page. - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub limit: ::std::option::Option, - ///The offset of the first resource returned. - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub offset: ::std::option::Option, - ///The total number of resources associated with the merchant's payTo address. - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub total: ::std::option::Option, + #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct UserOperationReceiptRevertData(::std::string::String); + impl ::std::ops::Deref for UserOperationReceiptRevertData { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } } - impl ::std::convert::From<&X402DiscoveryMerchantResponsePagination> - for X402DiscoveryMerchantResponsePagination - { - fn from(value: &X402DiscoveryMerchantResponsePagination) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: UserOperationReceiptRevertData) -> Self { + value.0 + } + } + impl ::std::convert::From<&UserOperationReceiptRevertData> for UserOperationReceiptRevertData { + fn from(value: &UserOperationReceiptRevertData) -> Self { value.clone() } } - impl ::std::default::Default for X402DiscoveryMerchantResponsePagination { - fn default() -> Self { - Self { - limit: Default::default(), - offset: Default::default(), - total: Default::default(), + impl ::std::str::FromStr for UserOperationReceiptRevertData { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| ::regress::Regex::new("^0x[0-9a-fA-F]*$").unwrap()); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^0x[0-9a-fA-F]*$\"".into()); } + Ok(Self(value.to_string())) } } - impl X402DiscoveryMerchantResponsePagination { - pub fn builder() -> builder::X402DiscoveryMerchantResponsePagination { - Default::default() + impl ::std::convert::TryFrom<&str> for UserOperationReceiptRevertData { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() } } - ///A single discovered x402 resource. - /// - ///
JSON schema - /// - /// ```json - ///{ - /// "description": "A single discovered x402 resource.", - /// "type": "object", - /// "required": [ - /// "resource", - /// "type", - /// "x402Version" - /// ], - /// "properties": { - /// "accepts": { - /// "description": "Payment requirements accepted by the resource.", - /// "examples": [ - /// [ - /// { - /// "amount": "1000000", - /// "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", - /// "maxTimeoutSeconds": 60, - /// "network": "eip155:8453", - /// "payTo": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "scheme": "exact" - /// } - /// ] - /// ], - /// "type": "array", - /// "items": { - /// "$ref": "#/components/schemas/x402PaymentRequirements" - /// } - /// }, - /// "description": { - /// "description": "A human-readable description of the resource.", - /// "examples": [ - /// "Real-time weather forecast data" - /// ], - /// "type": "string" - /// }, - /// "extensions": { - /// "description": "Map of x402 protocol extensions supported by the resource, keyed by extension name.", - /// "examples": [ - /// { - /// "bazaar": { - /// "info": { - /// "input": { - /// "method": "GET", - /// "type": "http" - /// } - /// }, - /// "schema": {} - /// } - /// } - /// ], - /// "type": "object", - /// "additionalProperties": true - /// }, - /// "lastUpdated": { - /// "description": "Timestamp of the last update.", - /// "examples": [ - /// "2024-01-15T10:30:00Z" - /// ], - /// "type": "string", - /// "format": "date-time" - /// }, - /// "quality": { - /// "$ref": "#/components/schemas/x402ResourceQuality" - /// }, - /// "resource": { - /// "description": "The URL of the resource.", - /// "examples": [ - /// "https://api.example.com/weather/forecast" - /// ], - /// "type": "string" - /// }, - /// "type": { - /// "description": "Communication protocol (e.g., \"http\", \"mcp\").", - /// "examples": [ - /// "http" - /// ], - /// "type": "string", - /// "enum": [ - /// "http", - /// "mcp" - /// ] - /// }, - /// "x402Version": { - /// "$ref": "#/components/schemas/X402Version" - /// } - /// } - ///} - /// ``` - ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402DiscoveryResource { - ///Payment requirements accepted by the resource. - #[serde(default, skip_serializing_if = "::std::vec::Vec::is_empty")] - pub accepts: ::std::vec::Vec, - ///A human-readable description of the resource. - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub description: ::std::option::Option<::std::string::String>, - ///Map of x402 protocol extensions supported by the resource, keyed by extension name. - #[serde(default, skip_serializing_if = "::serde_json::Map::is_empty")] - pub extensions: ::serde_json::Map<::std::string::String, ::serde_json::Value>, - ///Timestamp of the last update. - #[serde( - rename = "lastUpdated", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub last_updated: ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub quality: ::std::option::Option, - ///The URL of the resource. - pub resource: ::std::string::String, - ///Communication protocol (e.g., "http", "mcp"). - #[serde(rename = "type")] - pub type_: X402DiscoveryResourceType, - #[serde(rename = "x402Version")] - pub x402_version: X402Version, + impl ::std::convert::TryFrom<&::std::string::String> for UserOperationReceiptRevertData { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } } - impl ::std::convert::From<&X402DiscoveryResource> for X402DiscoveryResource { - fn from(value: &X402DiscoveryResource) -> Self { - value.clone() + impl ::std::convert::TryFrom<::std::string::String> for UserOperationReceiptRevertData { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() } } - impl X402DiscoveryResource { - pub fn builder() -> builder::X402DiscoveryResource { - Default::default() + impl<'de> ::serde::Deserialize<'de> for UserOperationReceiptRevertData { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) } } - ///Communication protocol (e.g., "http", "mcp"). + ///The hash of this transaction as 0x-prefixed string. /// ///
JSON schema /// /// ```json ///{ - /// "description": "Communication protocol (e.g., \"http\", \"mcp\").", + /// "description": "The hash of this transaction as 0x-prefixed string.", /// "examples": [ - /// "http" + /// "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" /// ], /// "type": "string", - /// "enum": [ - /// "http", - /// "mcp" - /// ] + /// "pattern": "^0x[a-fA-F0-9]{64}$" ///} /// ``` ///
- #[derive( - ::serde::Deserialize, - ::serde::Serialize, - Clone, - Copy, - Debug, - Eq, - Hash, - Ord, - PartialEq, - PartialOrd, - )] - pub enum X402DiscoveryResourceType { - #[serde(rename = "http")] - Http, - #[serde(rename = "mcp")] - Mcp, + #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct UserOperationReceiptTransactionHash(::std::string::String); + impl ::std::ops::Deref for UserOperationReceiptTransactionHash { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } } - impl ::std::convert::From<&Self> for X402DiscoveryResourceType { - fn from(value: &X402DiscoveryResourceType) -> Self { - value.clone() + impl ::std::convert::From for ::std::string::String { + fn from(value: UserOperationReceiptTransactionHash) -> Self { + value.0 } } - impl ::std::fmt::Display for X402DiscoveryResourceType { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - match *self { - Self::Http => f.write_str("http"), - Self::Mcp => f.write_str("mcp"), - } + impl ::std::convert::From<&UserOperationReceiptTransactionHash> + for UserOperationReceiptTransactionHash + { + fn from(value: &UserOperationReceiptTransactionHash) -> Self { + value.clone() } } - impl ::std::str::FromStr for X402DiscoveryResourceType { + impl ::std::str::FromStr for UserOperationReceiptTransactionHash { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - match value { - "http" => Ok(Self::Http), - "mcp" => Ok(Self::Mcp), - _ => Err("invalid value".into()), + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^0x[a-fA-F0-9]{64}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^0x[a-fA-F0-9]{64}$\"".into()); } + Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for X402DiscoveryResourceType { + impl ::std::convert::TryFrom<&str> for UserOperationReceiptTransactionHash { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for X402DiscoveryResourceType { + impl ::std::convert::TryFrom<&::std::string::String> for UserOperationReceiptTransactionHash { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -55407,7 +61150,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for X402DiscoveryResourceType { + impl ::std::convert::TryFrom<::std::string::String> for UserOperationReceiptTransactionHash { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -55415,446 +61158,240 @@ pub mod types { value.parse() } } - ///Response containing discovered x402 resources. + impl<'de> ::serde::Deserialize<'de> for UserOperationReceiptTransactionHash { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///The request body for a developer to verify an end user's access token. /// ///
JSON schema /// /// ```json ///{ - /// "description": "Response containing discovered x402 resources.", + /// "description": "The request body for a developer to verify an end user's access token.", /// "type": "object", /// "required": [ - /// "items", - /// "pagination", - /// "x402Version" + /// "accessToken" /// ], /// "properties": { - /// "items": { - /// "description": "List of discovered x402 resources.", - /// "examples": [ - /// [] - /// ], - /// "type": "array", - /// "items": { - /// "$ref": "#/components/schemas/x402DiscoveryResource" - /// } - /// }, - /// "pagination": { - /// "description": "Pagination information for the response.", + /// "accessToken": { + /// "description": "The access token in JWT format to verify.", /// "examples": [ - /// { - /// "limit": 100, - /// "offset": 0, - /// "total": 1000 - /// } + /// "eyJhbGciOiJFUzI1NiIsImtpZCI6IjA1ZGNmYTU1LWY1NzktNDg5YS1iNThhLTFlMDI5Nzk0N2VlNiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJjZHAtYXBpIiwiYXV0aF90eXBlIjoiZW1haWwiLCJleHAiOjE3NTM5ODAyOTksImlhdCI6MTc1Mzk3ODQ5OSwiaXNzIjoiY2RwLWFwaSIsImp0aSI6IjA3ZWY5M2JlLTYzMDQtNGQ1YS05NmE3LWJlMGI5MWI0ZTE3NCIsInByb2plY3RfaWQiOiJjNzRkOGI4OC0wOTNiLTQyZDItOGE4Yy1kZGM1YzVlMGViNDMiLCJzdWIiOiJjYTM4YTM4ZC0xNmE5LTRkMjYtYTcxZC0zOWY2NmY5YzZiN2UifQ.1SU0pOy-WR002qUw4hd_UmZWRSLz-ZL6v7PvQvZMKVE6a51x_tqeUeRGaTGuYl1whg0eccMObmK7FqXKRH6E4g" /// ], - /// "type": "object", - /// "properties": { - /// "limit": { - /// "description": "The number of discovered x402 resources to return per page.", - /// "examples": [ - /// 100 - /// ], - /// "type": "integer" - /// }, - /// "offset": { - /// "description": "The offset of the first discovered x402 resource to return.", - /// "examples": [ - /// 0 - /// ], - /// "type": "integer" - /// }, - /// "total": { - /// "description": "The total number of discovered x402 resources.", - /// "examples": [ - /// 1000 - /// ], - /// "type": "integer" - /// } - /// } - /// }, - /// "x402Version": { - /// "$ref": "#/components/schemas/X402Version" + /// "type": "string" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402DiscoveryResourcesResponse { - ///List of discovered x402 resources. - pub items: ::std::vec::Vec, - pub pagination: X402DiscoveryResourcesResponsePagination, - #[serde(rename = "x402Version")] - pub x402_version: X402Version, + pub struct ValidateEndUserAccessTokenBody { + ///The access token in JWT format to verify. + #[serde(rename = "accessToken")] + pub access_token: ::std::string::String, } - impl ::std::convert::From<&X402DiscoveryResourcesResponse> for X402DiscoveryResourcesResponse { - fn from(value: &X402DiscoveryResourcesResponse) -> Self { + impl ::std::convert::From<&ValidateEndUserAccessTokenBody> for ValidateEndUserAccessTokenBody { + fn from(value: &ValidateEndUserAccessTokenBody) -> Self { value.clone() } } - impl X402DiscoveryResourcesResponse { - pub fn builder() -> builder::X402DiscoveryResourcesResponse { + impl ValidateEndUserAccessTokenBody { + pub fn builder() -> builder::ValidateEndUserAccessTokenBody { Default::default() } } - ///Pagination information for the response. + ///`VerifyX402PaymentBody` /// ///
JSON schema /// /// ```json ///{ - /// "description": "Pagination information for the response.", - /// "examples": [ - /// { - /// "limit": 100, - /// "offset": 0, - /// "total": 1000 - /// } - /// ], /// "type": "object", + /// "required": [ + /// "paymentPayload", + /// "paymentRequirements", + /// "x402Version" + /// ], /// "properties": { - /// "limit": { - /// "description": "The number of discovered x402 resources to return per page.", - /// "examples": [ - /// 100 - /// ], - /// "type": "integer" + /// "paymentPayload": { + /// "$ref": "#/components/schemas/x402PaymentPayload" /// }, - /// "offset": { - /// "description": "The offset of the first discovered x402 resource to return.", - /// "examples": [ - /// 0 - /// ], - /// "type": "integer" + /// "paymentRequirements": { + /// "$ref": "#/components/schemas/x402PaymentRequirements" /// }, - /// "total": { - /// "description": "The total number of discovered x402 resources.", - /// "examples": [ - /// 1000 - /// ], - /// "type": "integer" + /// "x402Version": { + /// "$ref": "#/components/schemas/X402Version" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402DiscoveryResourcesResponsePagination { - ///The number of discovered x402 resources to return per page. - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub limit: ::std::option::Option, - ///The offset of the first discovered x402 resource to return. - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub offset: ::std::option::Option, - ///The total number of discovered x402 resources. - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub total: ::std::option::Option, + pub struct VerifyX402PaymentBody { + #[serde(rename = "paymentPayload")] + pub payment_payload: X402PaymentPayload, + #[serde(rename = "paymentRequirements")] + pub payment_requirements: X402PaymentRequirements, + #[serde(rename = "x402Version")] + pub x402_version: X402Version, } - impl ::std::convert::From<&X402DiscoveryResourcesResponsePagination> - for X402DiscoveryResourcesResponsePagination - { - fn from(value: &X402DiscoveryResourcesResponsePagination) -> Self { + impl ::std::convert::From<&VerifyX402PaymentBody> for VerifyX402PaymentBody { + fn from(value: &VerifyX402PaymentBody) -> Self { value.clone() } } - impl ::std::default::Default for X402DiscoveryResourcesResponsePagination { - fn default() -> Self { - Self { - limit: Default::default(), - offset: Default::default(), - total: Default::default(), - } - } - } - impl X402DiscoveryResourcesResponsePagination { - pub fn builder() -> builder::X402DiscoveryResourcesResponsePagination { + impl VerifyX402PaymentBody { + pub fn builder() -> builder::VerifyX402PaymentBody { Default::default() } } - ///The x402 protocol exact scheme payload for EVM networks. The scheme is implemented using ERC-3009. For more details, please see [EVM Exact Scheme Details](https://github.com/coinbase/x402/blob/main/specs/schemes/exact/scheme_exact_evm.md). + ///`VerifyX402PaymentResponse` /// ///
JSON schema /// /// ```json ///{ - /// "title": "x402ExactEvmPayload", - /// "description": "The x402 protocol exact scheme payload for EVM networks. The scheme is implemented using ERC-3009. For more details, please see [EVM Exact Scheme Details](https://github.com/coinbase/x402/blob/main/specs/schemes/exact/scheme_exact_evm.md).", - /// "examples": [ - /// { - /// "authorization": { - /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "nonce": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", - /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "validAfter": "1716150000", - /// "validBefore": "1716150000", - /// "value": "1000000000000000000" - /// }, - /// "signature": "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" - /// } - /// ], /// "type": "object", /// "required": [ - /// "authorization", - /// "signature" + /// "isValid", + /// "payer" /// ], /// "properties": { - /// "authorization": { - /// "description": "The authorization data for the ERC-3009 authorization message.", + /// "invalidMessage": { + /// "description": "The message describing the invalid reason.", /// "examples": [ - /// { - /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "nonce": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", - /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "validAfter": "1716150000", - /// "validBefore": "1716150000", - /// "value": "1000000000000000000" - /// } + /// "Insufficient funds" /// ], - /// "type": "object", - /// "required": [ - /// "from", - /// "nonce", - /// "to", - /// "validAfter", - /// "validBefore", - /// "value" + /// "type": "string" + /// }, + /// "invalidReason": { + /// "$ref": "#/components/schemas/x402VerifyInvalidReason" + /// }, + /// "isValid": { + /// "description": "Indicates whether the payment is valid.", + /// "examples": [ + /// false /// ], - /// "properties": { - /// "from": { - /// "description": "The 0x-prefixed, checksum EVM address of the sender of the payment.", - /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" - /// }, - /// "nonce": { - /// "description": "The hex-encoded nonce of the payment (bytes32).", - /// "examples": [ - /// "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{64}$" - /// }, - /// "to": { - /// "description": "The 0x-prefixed, checksum EVM address of the recipient of the payment.", - /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" - /// }, - /// "validAfter": { - /// "description": "The unix timestamp after which the payment is valid.", - /// "examples": [ - /// "1716150000" - /// ], - /// "type": "string" - /// }, - /// "validBefore": { - /// "description": "The unix timestamp before which the payment is valid.", - /// "examples": [ - /// "1716150000" - /// ], - /// "type": "string" - /// }, - /// "value": { - /// "description": "The value of the payment, in atomic units of the payment asset.", - /// "examples": [ - /// "1000000000000000000" - /// ], - /// "type": "string" - /// } - /// } - /// }, - /// "signature": { - /// "description": "The EIP-712 hex-encoded signature of the ERC-3009 authorization message. Smart account signatures may be longer than 65 bytes.", - /// "examples": [ - /// "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{130,}$" - /// } - /// } - ///} - /// ``` - ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402ExactEvmPayload { - pub authorization: X402ExactEvmPayloadAuthorization, - ///The EIP-712 hex-encoded signature of the ERC-3009 authorization message. Smart account signatures may be longer than 65 bytes. - pub signature: X402ExactEvmPayloadSignature, - } - impl ::std::convert::From<&X402ExactEvmPayload> for X402ExactEvmPayload { - fn from(value: &X402ExactEvmPayload) -> Self { - value.clone() - } - } - impl X402ExactEvmPayload { - pub fn builder() -> builder::X402ExactEvmPayload { - Default::default() - } - } - ///The authorization data for the ERC-3009 authorization message. - /// - ///
JSON schema - /// - /// ```json - ///{ - /// "description": "The authorization data for the ERC-3009 authorization message.", - /// "examples": [ - /// { - /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "nonce": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", - /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "validAfter": "1716150000", - /// "validBefore": "1716150000", - /// "value": "1000000000000000000" - /// } - /// ], - /// "type": "object", - /// "required": [ - /// "from", - /// "nonce", - /// "to", - /// "validAfter", - /// "validBefore", - /// "value" - /// ], - /// "properties": { - /// "from": { - /// "description": "The 0x-prefixed, checksum EVM address of the sender of the payment.", - /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" - /// }, - /// "nonce": { - /// "description": "The hex-encoded nonce of the payment (bytes32).", - /// "examples": [ - /// "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{64}$" + /// "type": "boolean" /// }, - /// "to": { - /// "description": "The 0x-prefixed, checksum EVM address of the recipient of the payment.", + /// "payer": { + /// "description": "The onchain address of the client that is paying for the resource.\n\nFor EVM networks, the payer will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, the payer will be a base58-encoded Solana address.", /// "examples": [ /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" /// ], /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" - /// }, - /// "validAfter": { - /// "description": "The unix timestamp after which the payment is valid.", - /// "examples": [ - /// "1716150000" - /// ], - /// "type": "string" - /// }, - /// "validBefore": { - /// "description": "The unix timestamp before which the payment is valid.", - /// "examples": [ - /// "1716150000" - /// ], - /// "type": "string" - /// }, - /// "value": { - /// "description": "The value of the payment, in atomic units of the payment asset.", - /// "examples": [ - /// "1000000000000000000" - /// ], - /// "type": "string" + /// "pattern": "^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402ExactEvmPayloadAuthorization { - ///The 0x-prefixed, checksum EVM address of the sender of the payment. - pub from: X402ExactEvmPayloadAuthorizationFrom, - ///The hex-encoded nonce of the payment (bytes32). - pub nonce: X402ExactEvmPayloadAuthorizationNonce, - ///The 0x-prefixed, checksum EVM address of the recipient of the payment. - pub to: X402ExactEvmPayloadAuthorizationTo, - ///The unix timestamp after which the payment is valid. - #[serde(rename = "validAfter")] - pub valid_after: ::std::string::String, - ///The unix timestamp before which the payment is valid. - #[serde(rename = "validBefore")] - pub valid_before: ::std::string::String, - ///The value of the payment, in atomic units of the payment asset. - pub value: ::std::string::String, + pub struct VerifyX402PaymentResponse { + ///The message describing the invalid reason. + #[serde( + rename = "invalidMessage", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub invalid_message: ::std::option::Option<::std::string::String>, + #[serde( + rename = "invalidReason", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub invalid_reason: ::std::option::Option, + ///Indicates whether the payment is valid. + #[serde(rename = "isValid")] + pub is_valid: bool, + /**The onchain address of the client that is paying for the resource. + + For EVM networks, the payer will be a 0x-prefixed, checksum EVM address. + + For Solana-based networks, the payer will be a base58-encoded Solana address.*/ + pub payer: VerifyX402PaymentResponsePayer, } - impl ::std::convert::From<&X402ExactEvmPayloadAuthorization> for X402ExactEvmPayloadAuthorization { - fn from(value: &X402ExactEvmPayloadAuthorization) -> Self { + impl ::std::convert::From<&VerifyX402PaymentResponse> for VerifyX402PaymentResponse { + fn from(value: &VerifyX402PaymentResponse) -> Self { value.clone() } } - impl X402ExactEvmPayloadAuthorization { - pub fn builder() -> builder::X402ExactEvmPayloadAuthorization { + impl VerifyX402PaymentResponse { + pub fn builder() -> builder::VerifyX402PaymentResponse { Default::default() } } - ///The 0x-prefixed, checksum EVM address of the sender of the payment. + /**The onchain address of the client that is paying for the resource. + + For EVM networks, the payer will be a 0x-prefixed, checksum EVM address. + + For Solana-based networks, the payer will be a base58-encoded Solana address.*/ /// ///
JSON schema /// /// ```json ///{ - /// "description": "The 0x-prefixed, checksum EVM address of the sender of the payment.", + /// "description": "The onchain address of the client that is paying for the resource.\n\nFor EVM networks, the payer will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, the payer will be a base58-encoded Solana address.", /// "examples": [ /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" /// ], /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// "pattern": "^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$" ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct X402ExactEvmPayloadAuthorizationFrom(::std::string::String); - impl ::std::ops::Deref for X402ExactEvmPayloadAuthorizationFrom { + pub struct VerifyX402PaymentResponsePayer(::std::string::String); + impl ::std::ops::Deref for VerifyX402PaymentResponsePayer { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: X402ExactEvmPayloadAuthorizationFrom) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: VerifyX402PaymentResponsePayer) -> Self { value.0 } } - impl ::std::convert::From<&X402ExactEvmPayloadAuthorizationFrom> - for X402ExactEvmPayloadAuthorizationFrom - { - fn from(value: &X402ExactEvmPayloadAuthorizationFrom) -> Self { + impl ::std::convert::From<&VerifyX402PaymentResponsePayer> for VerifyX402PaymentResponsePayer { + fn from(value: &VerifyX402PaymentResponsePayer) -> Self { value.clone() } } - impl ::std::str::FromStr for X402ExactEvmPayloadAuthorizationFrom { + impl ::std::str::FromStr for VerifyX402PaymentResponsePayer { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() + ::regress::Regex::new("^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$") + .unwrap() }); if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); + return Err( + "doesn't match pattern \"^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$\"" + .into(), + ); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for X402ExactEvmPayloadAuthorizationFrom { + impl ::std::convert::TryFrom<&str> for VerifyX402PaymentResponsePayer { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for X402ExactEvmPayloadAuthorizationFrom { + impl ::std::convert::TryFrom<&::std::string::String> for VerifyX402PaymentResponsePayer { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -55862,7 +61399,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for X402ExactEvmPayloadAuthorizationFrom { + impl ::std::convert::TryFrom<::std::string::String> for VerifyX402PaymentResponsePayer { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -55870,7 +61407,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for X402ExactEvmPayloadAuthorizationFrom { + impl<'de> ::serde::Deserialize<'de> for VerifyX402PaymentResponsePayer { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -55882,226 +61419,364 @@ pub mod types { }) } } - ///The hex-encoded nonce of the payment (bytes32). + ///Response containing a list of webhook event delivery attempts. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The hex-encoded nonce of the payment (bytes32).", + /// "description": "Response containing a list of webhook event delivery attempts.", /// "examples": [ - /// "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" + /// { + /// "events": [ + /// { + /// "createdAt": "2025-01-15T10:30:00Z", + /// "eventId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", + /// "eventTypeName": "onchain.activity.detected", + /// "response": { + /// "body": "ok", + /// "elapsedTimeMs": 142, + /// "httpCode": 200 + /// }, + /// "retryCount": 0, + /// "status": "succeeded", + /// "succeededAt": "2025-01-15T10:30:02Z" + /// } + /// ] + /// } /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{64}$" + /// "type": "object", + /// "required": [ + /// "events" + /// ], + /// "properties": { + /// "events": { + /// "description": "The list of webhook event delivery attempts.", + /// "type": "array", + /// "items": { + /// "$ref": "#/components/schemas/WebhookEventResponse" + /// } + /// } + /// } ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct X402ExactEvmPayloadAuthorizationNonce(::std::string::String); - impl ::std::ops::Deref for X402ExactEvmPayloadAuthorizationNonce { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } - } - impl ::std::convert::From for ::std::string::String { - fn from(value: X402ExactEvmPayloadAuthorizationNonce) -> Self { - value.0 - } + #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct WebhookEventListResponse { + ///The list of webhook event delivery attempts. + pub events: ::std::vec::Vec, } - impl ::std::convert::From<&X402ExactEvmPayloadAuthorizationNonce> - for X402ExactEvmPayloadAuthorizationNonce - { - fn from(value: &X402ExactEvmPayloadAuthorizationNonce) -> Self { + impl ::std::convert::From<&WebhookEventListResponse> for WebhookEventListResponse { + fn from(value: &WebhookEventListResponse) -> Self { value.clone() } } - impl ::std::str::FromStr for X402ExactEvmPayloadAuthorizationNonce { - type Err = self::error::ConversionError; - fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[0-9a-fA-F]{64}$").unwrap() - }); - if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]{64}$\"".into()); - } - Ok(Self(value.to_string())) - } - } - impl ::std::convert::TryFrom<&str> for X402ExactEvmPayloadAuthorizationNonce { - type Error = self::error::ConversionError; - fn try_from(value: &str) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<&::std::string::String> for X402ExactEvmPayloadAuthorizationNonce { - type Error = self::error::ConversionError; - fn try_from( - value: &::std::string::String, - ) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<::std::string::String> for X402ExactEvmPayloadAuthorizationNonce { - type Error = self::error::ConversionError; - fn try_from( - value: ::std::string::String, - ) -> ::std::result::Result { - value.parse() - } - } - impl<'de> ::serde::Deserialize<'de> for X402ExactEvmPayloadAuthorizationNonce { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) + impl WebhookEventListResponse { + pub fn builder() -> builder::WebhookEventListResponse { + Default::default() } } - ///The 0x-prefixed, checksum EVM address of the recipient of the payment. + ///Details of a webhook event delivery attempt for a subscription. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The 0x-prefixed, checksum EVM address of the recipient of the payment.", + /// "description": "Details of a webhook event delivery attempt for a subscription.", /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// { + /// "createdAt": "2025-01-15T10:30:00Z", + /// "eventId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", + /// "eventTypeName": "onchain.activity.detected", + /// "response": { + /// "body": "ok", + /// "elapsedTimeMs": 142, + /// "httpCode": 200 + /// }, + /// "retryCount": 0, + /// "status": "succeeded", + /// "succeededAt": "2025-01-15T10:30:02Z" + /// } /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// "type": "object", + /// "required": [ + /// "createdAt", + /// "eventId", + /// "eventTypeName", + /// "retryCount", + /// "status" + /// ], + /// "properties": { + /// "createdAt": { + /// "description": "Timestamp when the event delivery attempt was created.", + /// "examples": [ + /// "2025-01-15T10:30:00Z" + /// ], + /// "type": "string", + /// "format": "date-time" + /// }, + /// "eventId": { + /// "description": "Unique identifier for the webhook event.", + /// "examples": [ + /// "a1b2c3d4-e5f6-7890-abcd-ef1234567890" + /// ], + /// "type": "string" + /// }, + /// "eventTypeName": { + /// "description": "The type of event that was delivered (e.g., \"onchain.activity.detected\").", + /// "examples": [ + /// "onchain.activity.detected" + /// ], + /// "type": "string" + /// }, + /// "response": { + /// "$ref": "#/components/schemas/WebhookEventResponseDetail" + /// }, + /// "retryCount": { + /// "description": "Number of delivery retry attempts so far.", + /// "examples": [ + /// 0 + /// ], + /// "type": "integer" + /// }, + /// "status": { + /// "description": "Current delivery status of the event.", + /// "examples": [ + /// "succeeded" + /// ], + /// "type": "string", + /// "enum": [ + /// "pending", + /// "processing", + /// "succeeded", + /// "failed", + /// "retrying" + /// ] + /// }, + /// "succeededAt": { + /// "description": "Timestamp when the event was successfully delivered. Only present if status is \"succeeded\".", + /// "examples": [ + /// "2025-01-15T10:30:02Z" + /// ], + /// "type": "string", + /// "format": "date-time" + /// } + /// } ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct X402ExactEvmPayloadAuthorizationTo(::std::string::String); - impl ::std::ops::Deref for X402ExactEvmPayloadAuthorizationTo { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } - } - impl ::std::convert::From for ::std::string::String { - fn from(value: X402ExactEvmPayloadAuthorizationTo) -> Self { - value.0 - } + #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct WebhookEventResponse { + ///Timestamp when the event delivery attempt was created. + #[serde(rename = "createdAt")] + pub created_at: ::chrono::DateTime<::chrono::offset::Utc>, + ///Unique identifier for the webhook event. + #[serde(rename = "eventId")] + pub event_id: ::std::string::String, + ///The type of event that was delivered (e.g., "onchain.activity.detected"). + #[serde(rename = "eventTypeName")] + pub event_type_name: ::std::string::String, + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub response: ::std::option::Option, + ///Number of delivery retry attempts so far. + #[serde(rename = "retryCount")] + pub retry_count: i64, + ///Current delivery status of the event. + pub status: WebhookEventResponseStatus, + ///Timestamp when the event was successfully delivered. Only present if status is "succeeded". + #[serde( + rename = "succeededAt", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub succeeded_at: ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, } - impl ::std::convert::From<&X402ExactEvmPayloadAuthorizationTo> - for X402ExactEvmPayloadAuthorizationTo - { - fn from(value: &X402ExactEvmPayloadAuthorizationTo) -> Self { + impl ::std::convert::From<&WebhookEventResponse> for WebhookEventResponse { + fn from(value: &WebhookEventResponse) -> Self { value.clone() } } - impl ::std::str::FromStr for X402ExactEvmPayloadAuthorizationTo { - type Err = self::error::ConversionError; - fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() - }); - if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); - } - Ok(Self(value.to_string())) - } - } - impl ::std::convert::TryFrom<&str> for X402ExactEvmPayloadAuthorizationTo { - type Error = self::error::ConversionError; - fn try_from(value: &str) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<&::std::string::String> for X402ExactEvmPayloadAuthorizationTo { - type Error = self::error::ConversionError; - fn try_from( - value: &::std::string::String, - ) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<::std::string::String> for X402ExactEvmPayloadAuthorizationTo { - type Error = self::error::ConversionError; - fn try_from( - value: ::std::string::String, - ) -> ::std::result::Result { - value.parse() + impl WebhookEventResponse { + pub fn builder() -> builder::WebhookEventResponse { + Default::default() } } - impl<'de> ::serde::Deserialize<'de> for X402ExactEvmPayloadAuthorizationTo { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) + ///Details of the HTTP response received from the webhook target. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "Details of the HTTP response received from the webhook target.", + /// "examples": [ + /// { + /// "body": "ok", + /// "elapsedTimeMs": 142, + /// "httpCode": 200 + /// } + /// ], + /// "type": "object", + /// "properties": { + /// "body": { + /// "description": "Response body returned by the webhook target.", + /// "examples": [ + /// "ok" + /// ], + /// "type": "string" + /// }, + /// "elapsedTimeMs": { + /// "description": "Round-trip time of the webhook delivery in milliseconds.", + /// "examples": [ + /// 142 + /// ], + /// "type": "integer" + /// }, + /// "errorName": { + /// "description": "Error name if the delivery failed (e.g., timeout, connection_refused).", + /// "examples": [ + /// "timeout" + /// ], + /// "type": "string" + /// }, + /// "httpCode": { + /// "description": "HTTP status code returned by the webhook target.", + /// "examples": [ + /// 200 + /// ], + /// "type": "integer" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct WebhookEventResponseDetail { + ///Response body returned by the webhook target. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub body: ::std::option::Option<::std::string::String>, + ///Round-trip time of the webhook delivery in milliseconds. + #[serde( + rename = "elapsedTimeMs", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub elapsed_time_ms: ::std::option::Option, + ///Error name if the delivery failed (e.g., timeout, connection_refused). + #[serde( + rename = "errorName", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub error_name: ::std::option::Option<::std::string::String>, + ///HTTP status code returned by the webhook target. + #[serde( + rename = "httpCode", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub http_code: ::std::option::Option, + } + impl ::std::convert::From<&WebhookEventResponseDetail> for WebhookEventResponseDetail { + fn from(value: &WebhookEventResponseDetail) -> Self { + value.clone() } } - ///The EIP-712 hex-encoded signature of the ERC-3009 authorization message. Smart account signatures may be longer than 65 bytes. + impl ::std::default::Default for WebhookEventResponseDetail { + fn default() -> Self { + Self { + body: Default::default(), + elapsed_time_ms: Default::default(), + error_name: Default::default(), + http_code: Default::default(), + } + } + } + impl WebhookEventResponseDetail { + pub fn builder() -> builder::WebhookEventResponseDetail { + Default::default() + } + } + ///Current delivery status of the event. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The EIP-712 hex-encoded signature of the ERC-3009 authorization message. Smart account signatures may be longer than 65 bytes.", + /// "description": "Current delivery status of the event.", /// "examples": [ - /// "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" + /// "succeeded" /// ], /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{130,}$" + /// "enum": [ + /// "pending", + /// "processing", + /// "succeeded", + /// "failed", + /// "retrying" + /// ] ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct X402ExactEvmPayloadSignature(::std::string::String); - impl ::std::ops::Deref for X402ExactEvmPayloadSignature { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } + #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum WebhookEventResponseStatus { + #[serde(rename = "pending")] + Pending, + #[serde(rename = "processing")] + Processing, + #[serde(rename = "succeeded")] + Succeeded, + #[serde(rename = "failed")] + Failed, + #[serde(rename = "retrying")] + Retrying, } - impl ::std::convert::From for ::std::string::String { - fn from(value: X402ExactEvmPayloadSignature) -> Self { - value.0 + impl ::std::convert::From<&Self> for WebhookEventResponseStatus { + fn from(value: &WebhookEventResponseStatus) -> Self { + value.clone() } } - impl ::std::convert::From<&X402ExactEvmPayloadSignature> for X402ExactEvmPayloadSignature { - fn from(value: &X402ExactEvmPayloadSignature) -> Self { - value.clone() + impl ::std::fmt::Display for WebhookEventResponseStatus { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Pending => f.write_str("pending"), + Self::Processing => f.write_str("processing"), + Self::Succeeded => f.write_str("succeeded"), + Self::Failed => f.write_str("failed"), + Self::Retrying => f.write_str("retrying"), + } } } - impl ::std::str::FromStr for X402ExactEvmPayloadSignature { + impl ::std::str::FromStr for WebhookEventResponseStatus { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[0-9a-fA-F]{130,}$").unwrap() - }); - if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]{130,}$\"".into()); + match value { + "pending" => Ok(Self::Pending), + "processing" => Ok(Self::Processing), + "succeeded" => Ok(Self::Succeeded), + "failed" => Ok(Self::Failed), + "retrying" => Ok(Self::Retrying), + _ => Err("invalid value".into()), } - Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for X402ExactEvmPayloadSignature { + impl ::std::convert::TryFrom<&str> for WebhookEventResponseStatus { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for X402ExactEvmPayloadSignature { + impl ::std::convert::TryFrom<&::std::string::String> for WebhookEventResponseStatus { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -56109,7 +61784,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for X402ExactEvmPayloadSignature { + impl ::std::convert::TryFrom<::std::string::String> for WebhookEventResponseStatus { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -56117,499 +61792,477 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for X402ExactEvmPayloadSignature { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) - } - } - ///The x402 protocol exact scheme payload for EVM networks using Permit2. Permit2 is a universal token approval mechanism that works with any ERC-20 token, unlike ERC-3009 which requires token-level support. + ///`WebhookSubscriptionListResponse` /// ///
JSON schema /// /// ```json ///{ - /// "title": "x402ExactEvmPermit2Payload", - /// "description": "The x402 protocol exact scheme payload for EVM networks using Permit2. Permit2 is a universal token approval mechanism that works with any ERC-20 token, unlike ERC-3009 which requires token-level support.", - /// "examples": [ + /// "allOf": [ /// { - /// "permit2Authorization": { - /// "deadline": "1716150000", - /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "nonce": "12345678901234567890", - /// "permitted": { - /// "amount": "1000000", - /// "token": "0x036CbD53842c5426634e7929541eC2318f3dCF7e" - /// }, - /// "spender": "0x4020615294c913F045dc10f0a5cdEbd86c280001", - /// "witness": { - /// "extra": "0x", - /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "validAfter": "1716150000" - /// } - /// }, - /// "signature": "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" - /// } - /// ], - /// "type": "object", - /// "required": [ - /// "permit2Authorization", - /// "signature" - /// ], - /// "properties": { - /// "permit2Authorization": { - /// "description": "The authorization data for the Permit2 PermitWitnessTransferFrom message.", - /// "examples": [ - /// { - /// "deadline": "1716150000", - /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "nonce": "12345678901234567890", - /// "permitted": { - /// "amount": "1000000", - /// "token": "0x036CbD53842c5426634e7929541eC2318f3dCF7e" - /// }, - /// "spender": "0x4020615294c913F045dc10f0a5cdEbd86c280001", - /// "witness": { - /// "extra": "0x", - /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "validAfter": "1716150000" - /// } - /// } - /// ], + /// "description": "Response containing a list of webhook subscriptions.", /// "type": "object", /// "required": [ - /// "deadline", - /// "from", - /// "nonce", - /// "permitted", - /// "spender", - /// "witness" + /// "subscriptions" /// ], /// "properties": { - /// "deadline": { - /// "description": "The unix timestamp before which the permit is valid.", - /// "examples": [ - /// "1716150000" - /// ], - /// "type": "string" - /// }, - /// "from": { - /// "description": "The 0x-prefixed, checksum EVM address of the sender of the payment.", - /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" - /// }, - /// "nonce": { - /// "description": "The Permit2 nonce as a decimal string (uint256).", - /// "examples": [ - /// "12345678901234567890" - /// ], - /// "type": "string", - /// "pattern": "^[0-9]+$" - /// }, - /// "permitted": { - /// "description": "The token permissions for the transfer.", - /// "type": "object", - /// "required": [ - /// "amount", - /// "token" - /// ], - /// "properties": { - /// "amount": { - /// "description": "The amount to transfer in atomic units.", - /// "examples": [ - /// "1000000" - /// ], - /// "type": "string" - /// }, - /// "token": { - /// "description": "The 0x-prefixed, checksum EVM address of the token to transfer.", - /// "examples": [ - /// "0x036CbD53842c5426634e7929541eC2318f3dCF7e" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" - /// } - /// } - /// }, - /// "spender": { - /// "description": "The 0x-prefixed, checksum EVM address of the spender (x402 Permit2 proxy contract).", - /// "examples": [ - /// "0x4020615294c913F045dc10f0a5cdEbd86c280001" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" - /// }, - /// "witness": { - /// "description": "The witness data containing payment details.", - /// "type": "object", - /// "required": [ - /// "to", - /// "validAfter" - /// ], - /// "properties": { - /// "extra": { - /// "description": "Optional hex-encoded extra data.", - /// "examples": [ - /// "0x" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]*$" - /// }, - /// "to": { - /// "description": "The 0x-prefixed, checksum EVM address of the recipient.", - /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" - /// }, - /// "validAfter": { - /// "description": "The unix timestamp after which the payment is valid.", - /// "examples": [ - /// "1716150000" - /// ], - /// "type": "string" - /// } + /// "subscriptions": { + /// "description": "The list of webhook subscriptions.", + /// "type": "array", + /// "items": { + /// "$ref": "#/components/schemas/WebhookSubscriptionResponse" /// } /// } /// } /// }, - /// "signature": { - /// "description": "The EIP-712 hex-encoded signature of the Permit2 PermitWitnessTransferFrom message. Smart account signatures may be longer than 65 bytes.", - /// "examples": [ - /// "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{130,}$" + /// { + /// "$ref": "#/components/schemas/ListResponse" /// } - /// } + /// ] ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402ExactEvmPermit2Payload { - #[serde(rename = "permit2Authorization")] - pub permit2_authorization: X402ExactEvmPermit2PayloadPermit2Authorization, - ///The EIP-712 hex-encoded signature of the Permit2 PermitWitnessTransferFrom message. Smart account signatures may be longer than 65 bytes. - pub signature: X402ExactEvmPermit2PayloadSignature, + pub struct WebhookSubscriptionListResponse { + ///The token for the next page of items, if any. + #[serde( + rename = "nextPageToken", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub next_page_token: ::std::option::Option<::std::string::String>, + ///The list of webhook subscriptions. + pub subscriptions: ::std::vec::Vec, } - impl ::std::convert::From<&X402ExactEvmPermit2Payload> for X402ExactEvmPermit2Payload { - fn from(value: &X402ExactEvmPermit2Payload) -> Self { + impl ::std::convert::From<&WebhookSubscriptionListResponse> for WebhookSubscriptionListResponse { + fn from(value: &WebhookSubscriptionListResponse) -> Self { value.clone() } } - impl X402ExactEvmPermit2Payload { - pub fn builder() -> builder::X402ExactEvmPermit2Payload { + impl WebhookSubscriptionListResponse { + pub fn builder() -> builder::WebhookSubscriptionListResponse { Default::default() } } - ///The authorization data for the Permit2 PermitWitnessTransferFrom message. + /**Request to create a new webhook subscription with support for multi-label filtering. + */ /// ///
JSON schema /// /// ```json ///{ - /// "description": "The authorization data for the Permit2 PermitWitnessTransferFrom message.", - /// "examples": [ - /// { - /// "deadline": "1716150000", - /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "nonce": "12345678901234567890", - /// "permitted": { - /// "amount": "1000000", - /// "token": "0x036CbD53842c5426634e7929541eC2318f3dCF7e" - /// }, - /// "spender": "0x4020615294c913F045dc10f0a5cdEbd86c280001", - /// "witness": { - /// "extra": "0x", - /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "validAfter": "1716150000" - /// } - /// } - /// ], + /// "description": "Request to create a new webhook subscription with support for multi-label filtering.\n", /// "type": "object", /// "required": [ - /// "deadline", - /// "from", - /// "nonce", - /// "permitted", - /// "spender", - /// "witness" + /// "eventTypes", + /// "isEnabled", + /// "target" /// ], /// "properties": { - /// "deadline": { - /// "description": "The unix timestamp before which the permit is valid.", + /// "description": { + /// "description": "Description of the webhook subscription.", /// "examples": [ - /// "1716150000" + /// "Subscription for token transfer events" /// ], - /// "type": "string" + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/Description" + /// } + /// ] /// }, - /// "from": { - /// "description": "The 0x-prefixed, checksum EVM address of the sender of the payment.", + /// "eventTypes": { + /// "description": "Types of events to subscribe to. Event types follow a dot-separated format:\nservice.resource.verb (e.g., \"onchain.activity.detected\", \"wallet.activity.detected\", \"onramp.transaction.created\",\n\"acceptance.payment_session.authorization_succeeded\").\nThe subscription will only receive events matching these types AND the label filter(s).\n", /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// [ + /// "onchain.activity.detected" + /// ] /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// "type": "array", + /// "items": { + /// "type": "string" + /// } /// }, - /// "nonce": { - /// "description": "The Permit2 nonce as a decimal string (uint256).", + /// "isEnabled": { + /// "description": "Whether the subscription is enabled.", /// "examples": [ - /// "12345678901234567890" - /// ], - /// "type": "string", - /// "pattern": "^[0-9]+$" - /// }, - /// "permitted": { - /// "description": "The token permissions for the transfer.", - /// "type": "object", - /// "required": [ - /// "amount", - /// "token" + /// true /// ], - /// "properties": { - /// "amount": { - /// "description": "The amount to transfer in atomic units.", - /// "examples": [ - /// "1000000" - /// ], - /// "type": "string" - /// }, - /// "token": { - /// "description": "The 0x-prefixed, checksum EVM address of the token to transfer.", - /// "examples": [ - /// "0x036CbD53842c5426634e7929541eC2318f3dCF7e" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" - /// } - /// } + /// "type": "boolean" /// }, - /// "spender": { - /// "description": "The 0x-prefixed, checksum EVM address of the spender (x402 Permit2 proxy contract).", + /// "labels": { + /// "description": "Optional. Multi-label filters using total overlap logic. Total overlap means the subscription will only trigger when\nan event contains ALL the key-value pairs specified here. Additional labels on\nthe event are allowed and will not prevent matching. Omit to receive all events for the selected event types.\n\n**Note:** Currently, labels are supported for onchain webhooks only.\n\nSee [allowed labels for onchain webhooks](https://docs.cdp.coinbase.com/api-reference/v2/rest-api/webhooks/create-webhook-subscription#onchain-label-filtering).\n", /// "examples": [ - /// "0x4020615294c913F045dc10f0a5cdEbd86c280001" + /// { + /// "contract_address": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913", + /// "event_name": "Transfer", + /// "network": "base-mainnet" + /// } /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" - /// }, - /// "witness": { - /// "description": "The witness data containing payment details.", /// "type": "object", - /// "required": [ - /// "to", - /// "validAfter" - /// ], - /// "properties": { - /// "extra": { - /// "description": "Optional hex-encoded extra data.", - /// "examples": [ - /// "0x" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]*$" - /// }, - /// "to": { - /// "description": "The 0x-prefixed, checksum EVM address of the recipient.", - /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" - /// }, - /// "validAfter": { - /// "description": "The unix timestamp after which the payment is valid.", - /// "examples": [ - /// "1716150000" - /// ], - /// "type": "string" - /// } + /// "additionalProperties": { + /// "type": "string" /// } + /// }, + /// "metadata": { + /// "$ref": "#/components/schemas/Metadata" + /// }, + /// "target": { + /// "$ref": "#/components/schemas/WebhookTarget" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402ExactEvmPermit2PayloadPermit2Authorization { - ///The unix timestamp before which the permit is valid. - pub deadline: ::std::string::String, - ///The 0x-prefixed, checksum EVM address of the sender of the payment. - pub from: X402ExactEvmPermit2PayloadPermit2AuthorizationFrom, - ///The Permit2 nonce as a decimal string (uint256). - pub nonce: X402ExactEvmPermit2PayloadPermit2AuthorizationNonce, - pub permitted: X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted, - ///The 0x-prefixed, checksum EVM address of the spender (x402 Permit2 proxy contract). - pub spender: X402ExactEvmPermit2PayloadPermit2AuthorizationSpender, - pub witness: X402ExactEvmPermit2PayloadPermit2AuthorizationWitness, + pub struct WebhookSubscriptionRequest { + ///Description of the webhook subscription. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub description: ::std::option::Option, + /**Types of events to subscribe to. Event types follow a dot-separated format: + service.resource.verb (e.g., "onchain.activity.detected", "wallet.activity.detected", "onramp.transaction.created", + "acceptance.payment_session.authorization_succeeded"). + The subscription will only receive events matching these types AND the label filter(s). + */ + #[serde(rename = "eventTypes")] + pub event_types: ::std::vec::Vec<::std::string::String>, + ///Whether the subscription is enabled. + #[serde(rename = "isEnabled")] + pub is_enabled: bool, + /**Optional. Multi-label filters using total overlap logic. Total overlap means the subscription will only trigger when + an event contains ALL the key-value pairs specified here. Additional labels on + the event are allowed and will not prevent matching. Omit to receive all events for the selected event types. + + **Note:** Currently, labels are supported for onchain webhooks only. + + See [allowed labels for onchain webhooks](https://docs.cdp.coinbase.com/api-reference/v2/rest-api/webhooks/create-webhook-subscription#onchain-label-filtering). + */ + #[serde( + default, + skip_serializing_if = ":: std :: collections :: HashMap::is_empty" + )] + pub labels: ::std::collections::HashMap<::std::string::String, ::std::string::String>, + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub metadata: ::std::option::Option, + pub target: WebhookTarget, } - impl ::std::convert::From<&X402ExactEvmPermit2PayloadPermit2Authorization> - for X402ExactEvmPermit2PayloadPermit2Authorization - { - fn from(value: &X402ExactEvmPermit2PayloadPermit2Authorization) -> Self { + impl ::std::convert::From<&WebhookSubscriptionRequest> for WebhookSubscriptionRequest { + fn from(value: &WebhookSubscriptionRequest) -> Self { value.clone() } } - impl X402ExactEvmPermit2PayloadPermit2Authorization { - pub fn builder() -> builder::X402ExactEvmPermit2PayloadPermit2Authorization { + impl WebhookSubscriptionRequest { + pub fn builder() -> builder::WebhookSubscriptionRequest { Default::default() } } - ///The 0x-prefixed, checksum EVM address of the sender of the payment. + ///Response containing webhook subscription details. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The 0x-prefixed, checksum EVM address of the sender of the payment.", + /// "description": "Response containing webhook subscription details.", /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// { + /// "createdAt": "2025-11-12T09:19:52.051Z", + /// "description": "USDC Transfer events to specific address.", + /// "eventTypes": [ + /// "onchain.activity.detected" + /// ], + /// "isEnabled": true, + /// "labels": { + /// "contract_address": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913", + /// "event_name": "Transfer", + /// "network": "base-mainnet", + /// "transaction_to": "0xf5042e6ffac5a625d4e7848e0b01373d8eb9e222" + /// }, + /// "metadata": { + /// "secret": "a1b2c3d4-e5f6-7890-abcd-ef1234567890" + /// }, + /// "secret": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", + /// "subscriptionId": "123e4567-e89b-12d3-a456-426614174000", + /// "target": { + /// "url": "https://api.example.com/webhooks" + /// }, + /// "updatedAt": "2025-11-13T11:30:00.000Z" + /// } /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// "type": "object", + /// "required": [ + /// "createdAt", + /// "eventTypes", + /// "isEnabled", + /// "secret", + /// "subscriptionId", + /// "target" + /// ], + /// "properties": { + /// "createdAt": { + /// "description": "When the subscription was created.", + /// "examples": [ + /// "2025-01-15T10:30:00Z" + /// ], + /// "type": "string", + /// "format": "date-time" + /// }, + /// "description": { + /// "description": "Description of the webhook subscription.", + /// "examples": [ + /// "Subscription for token transfer events" + /// ], + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/Description" + /// } + /// ] + /// }, + /// "eventTypes": { + /// "description": "Types of events to subscribe to. Event types follow a dot-separated format:\nservice.resource.verb (e.g., \"onchain.activity.detected\", \"wallet.activity.detected\", \"onramp.transaction.created\",\n\"acceptance.payment_session.authorization_succeeded\").\n", + /// "examples": [ + /// [ + /// "onchain.activity.detected" + /// ] + /// ], + /// "type": "array", + /// "items": { + /// "type": "string" + /// } + /// }, + /// "isEnabled": { + /// "description": "Whether the subscription is enabled.", + /// "examples": [ + /// true + /// ], + /// "type": "boolean" + /// }, + /// "labels": { + /// "description": "Multi-label filters using total overlap logic. Total overlap means the subscription only triggers when events contain ALL these key-value pairs.\nPresent when subscription uses multi-label format.\n", + /// "examples": [ + /// { + /// "contract_address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + /// "env": "dev", + /// "team": "payments" + /// } + /// ], + /// "type": "object", + /// "additionalProperties": { + /// "type": "string" + /// } + /// }, + /// "metadata": { + /// "description": "Additional metadata for the subscription.", + /// "examples": [ + /// { + /// "secret": "123e4567-e89b-12d3-a456-426614174000" + /// } + /// ], + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/Metadata" + /// }, + /// { + /// "type": "object", + /// "properties": { + /// "secret": { + /// "description": "Use the root-level `secret` field instead. Maintained for backward compatibility only.", + /// "deprecated": true, + /// "examples": [ + /// "123e4567-e89b-12d3-a456-426614174000" + /// ], + /// "type": "string", + /// "format": "uuid" + /// } + /// } + /// } + /// ] + /// }, + /// "secret": { + /// "description": "Secret for webhook signature validation.", + /// "examples": [ + /// "123e4567-e89b-12d3-a456-426614174000" + /// ], + /// "type": "string", + /// "format": "uuid" + /// }, + /// "subscriptionId": { + /// "description": "Unique identifier for the subscription.", + /// "examples": [ + /// "123e4567-e89b-12d3-a456-426614174000" + /// ], + /// "type": "string", + /// "format": "uuid" + /// }, + /// "target": { + /// "$ref": "#/components/schemas/WebhookTarget" + /// }, + /// "updatedAt": { + /// "description": "When the subscription was last updated.", + /// "examples": [ + /// "2025-01-16T14:00:00Z" + /// ], + /// "type": "string", + /// "format": "date-time" + /// } + /// } ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct X402ExactEvmPermit2PayloadPermit2AuthorizationFrom(::std::string::String); - impl ::std::ops::Deref for X402ExactEvmPermit2PayloadPermit2AuthorizationFrom { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } - } - impl ::std::convert::From - for ::std::string::String - { - fn from(value: X402ExactEvmPermit2PayloadPermit2AuthorizationFrom) -> Self { - value.0 - } + #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct WebhookSubscriptionResponse { + ///When the subscription was created. + #[serde(rename = "createdAt")] + pub created_at: ::chrono::DateTime<::chrono::offset::Utc>, + ///Description of the webhook subscription. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub description: ::std::option::Option, + /**Types of events to subscribe to. Event types follow a dot-separated format: + service.resource.verb (e.g., "onchain.activity.detected", "wallet.activity.detected", "onramp.transaction.created", + "acceptance.payment_session.authorization_succeeded"). + */ + #[serde(rename = "eventTypes")] + pub event_types: ::std::vec::Vec<::std::string::String>, + ///Whether the subscription is enabled. + #[serde(rename = "isEnabled")] + pub is_enabled: bool, + /**Multi-label filters using total overlap logic. Total overlap means the subscription only triggers when events contain ALL these key-value pairs. + Present when subscription uses multi-label format. + */ + #[serde( + default, + skip_serializing_if = ":: std :: collections :: HashMap::is_empty" + )] + pub labels: ::std::collections::HashMap<::std::string::String, ::std::string::String>, + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub metadata: ::std::option::Option, + ///Secret for webhook signature validation. + pub secret: ::uuid::Uuid, + ///Unique identifier for the subscription. + #[serde(rename = "subscriptionId")] + pub subscription_id: ::uuid::Uuid, + pub target: WebhookTarget, + ///When the subscription was last updated. + #[serde( + rename = "updatedAt", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub updated_at: ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, } - impl ::std::convert::From<&X402ExactEvmPermit2PayloadPermit2AuthorizationFrom> - for X402ExactEvmPermit2PayloadPermit2AuthorizationFrom - { - fn from(value: &X402ExactEvmPermit2PayloadPermit2AuthorizationFrom) -> Self { + impl ::std::convert::From<&WebhookSubscriptionResponse> for WebhookSubscriptionResponse { + fn from(value: &WebhookSubscriptionResponse) -> Self { value.clone() } } - impl ::std::str::FromStr for X402ExactEvmPermit2PayloadPermit2AuthorizationFrom { - type Err = self::error::ConversionError; - fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() - }); - if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); - } - Ok(Self(value.to_string())) - } - } - impl ::std::convert::TryFrom<&str> for X402ExactEvmPermit2PayloadPermit2AuthorizationFrom { - type Error = self::error::ConversionError; - fn try_from(value: &str) -> ::std::result::Result { - value.parse() + impl WebhookSubscriptionResponse { + pub fn builder() -> builder::WebhookSubscriptionResponse { + Default::default() } } - impl ::std::convert::TryFrom<&::std::string::String> - for X402ExactEvmPermit2PayloadPermit2AuthorizationFrom - { - type Error = self::error::ConversionError; - fn try_from( - value: &::std::string::String, - ) -> ::std::result::Result { - value.parse() - } + ///Additional metadata for the subscription. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "Additional metadata for the subscription.", + /// "examples": [ + /// { + /// "secret": "123e4567-e89b-12d3-a456-426614174000" + /// } + /// ], + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/Metadata" + /// }, + /// { + /// "type": "object", + /// "properties": { + /// "secret": { + /// "description": "Use the root-level `secret` field instead. Maintained for backward compatibility only.", + /// "deprecated": true, + /// "examples": [ + /// "123e4567-e89b-12d3-a456-426614174000" + /// ], + /// "type": "string", + /// "format": "uuid" + /// } + /// } + /// } + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct WebhookSubscriptionResponseMetadata { + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub secret: ::std::option::Option<::uuid::Uuid>, + #[serde(flatten)] + pub extra: ::std::collections::HashMap< + ::std::string::String, + WebhookSubscriptionResponseMetadataExtraValue, + >, } - impl ::std::convert::TryFrom<::std::string::String> - for X402ExactEvmPermit2PayloadPermit2AuthorizationFrom + impl ::std::convert::From<&WebhookSubscriptionResponseMetadata> + for WebhookSubscriptionResponseMetadata { - type Error = self::error::ConversionError; - fn try_from( - value: ::std::string::String, - ) -> ::std::result::Result { - value.parse() + fn from(value: &WebhookSubscriptionResponseMetadata) -> Self { + value.clone() } } - impl<'de> ::serde::Deserialize<'de> for X402ExactEvmPermit2PayloadPermit2AuthorizationFrom { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) + impl WebhookSubscriptionResponseMetadata { + pub fn builder() -> builder::WebhookSubscriptionResponseMetadata { + Default::default() } } - ///The Permit2 nonce as a decimal string (uint256). + ///`WebhookSubscriptionResponseMetadataExtraValue` /// ///
JSON schema /// /// ```json ///{ - /// "description": "The Permit2 nonce as a decimal string (uint256).", - /// "examples": [ - /// "12345678901234567890" - /// ], /// "type": "string", - /// "pattern": "^[0-9]+$" + /// "maxLength": 500 ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct X402ExactEvmPermit2PayloadPermit2AuthorizationNonce(::std::string::String); - impl ::std::ops::Deref for X402ExactEvmPermit2PayloadPermit2AuthorizationNonce { + pub struct WebhookSubscriptionResponseMetadataExtraValue(::std::string::String); + impl ::std::ops::Deref for WebhookSubscriptionResponseMetadataExtraValue { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From - for ::std::string::String - { - fn from(value: X402ExactEvmPermit2PayloadPermit2AuthorizationNonce) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: WebhookSubscriptionResponseMetadataExtraValue) -> Self { value.0 } } - impl ::std::convert::From<&X402ExactEvmPermit2PayloadPermit2AuthorizationNonce> - for X402ExactEvmPermit2PayloadPermit2AuthorizationNonce + impl ::std::convert::From<&WebhookSubscriptionResponseMetadataExtraValue> + for WebhookSubscriptionResponseMetadataExtraValue { - fn from(value: &X402ExactEvmPermit2PayloadPermit2AuthorizationNonce) -> Self { + fn from(value: &WebhookSubscriptionResponseMetadataExtraValue) -> Self { value.clone() } } - impl ::std::str::FromStr for X402ExactEvmPermit2PayloadPermit2AuthorizationNonce { + impl ::std::str::FromStr for WebhookSubscriptionResponseMetadataExtraValue { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| ::regress::Regex::new("^[0-9]+$").unwrap()); - if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^[0-9]+$\"".into()); + if value.chars().count() > 500usize { + return Err("longer than 500 characters".into()); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for X402ExactEvmPermit2PayloadPermit2AuthorizationNonce { + impl ::std::convert::TryFrom<&str> for WebhookSubscriptionResponseMetadataExtraValue { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } impl ::std::convert::TryFrom<&::std::string::String> - for X402ExactEvmPermit2PayloadPermit2AuthorizationNonce + for WebhookSubscriptionResponseMetadataExtraValue { type Error = self::error::ConversionError; fn try_from( @@ -56619,7 +62272,7 @@ pub mod types { } } impl ::std::convert::TryFrom<::std::string::String> - for X402ExactEvmPermit2PayloadPermit2AuthorizationNonce + for WebhookSubscriptionResponseMetadataExtraValue { type Error = self::error::ConversionError; fn try_from( @@ -56628,7 +62281,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for X402ExactEvmPermit2PayloadPermit2AuthorizationNonce { + impl<'de> ::serde::Deserialize<'de> for WebhookSubscriptionResponseMetadataExtraValue { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -56640,535 +62293,647 @@ pub mod types { }) } } - ///The token permissions for the transfer. + /**Request to update an existing webhook subscription. + */ /// ///
JSON schema /// /// ```json ///{ - /// "description": "The token permissions for the transfer.", + /// "description": "Request to update an existing webhook subscription.\n", /// "type": "object", /// "required": [ - /// "amount", - /// "token" + /// "eventTypes", + /// "isEnabled", + /// "target" /// ], /// "properties": { - /// "amount": { - /// "description": "The amount to transfer in atomic units.", + /// "description": { + /// "description": "Description of the webhook subscription.", /// "examples": [ - /// "1000000" + /// "Updated subscription for token transfer events" /// ], - /// "type": "string" + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/Description" + /// } + /// ] /// }, - /// "token": { - /// "description": "The 0x-prefixed, checksum EVM address of the token to transfer.", + /// "eventTypes": { + /// "description": "Types of events to subscribe to. Event types follow a three-part dot-separated format:\nservice.resource.verb (e.g., \"onchain.activity.detected\", \"wallet.activity.detected\", \"onramp.transaction.created\").\n", /// "examples": [ - /// "0x036CbD53842c5426634e7929541eC2318f3dCF7e" + /// [ + /// "onchain.activity.detected" + /// ] /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// "type": "array", + /// "items": { + /// "type": "string" + /// } + /// }, + /// "isEnabled": { + /// "description": "Whether the subscription is enabled.", + /// "examples": [ + /// false + /// ], + /// "type": "boolean" + /// }, + /// "labels": { + /// "description": "Optional. Multi-label filters that trigger only when an event contains ALL of these key-value pairs.\n\n**Note:** Currently, labels are supported for onchain webhooks only.\n\nSee [allowed labels for onchain webhooks](https://docs.cdp.coinbase.com/api-reference/v2/rest-api/webhooks/create-webhook-subscription#onchain-label-filtering).\nOmit to receive all events for the selected event types.\n", + /// "examples": [ + /// { + /// "contract_address": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913", + /// "event_name": "Transfer", + /// "network": "base-mainnet" + /// } + /// ], + /// "type": "object", + /// "additionalProperties": { + /// "type": "string" + /// } + /// }, + /// "metadata": { + /// "$ref": "#/components/schemas/Metadata" + /// }, + /// "target": { + /// "$ref": "#/components/schemas/WebhookTarget" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted { - ///The amount to transfer in atomic units. - pub amount: ::std::string::String, - ///The 0x-prefixed, checksum EVM address of the token to transfer. - pub token: X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken, + pub struct WebhookSubscriptionUpdateRequest { + ///Description of the webhook subscription. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub description: ::std::option::Option, + /**Types of events to subscribe to. Event types follow a three-part dot-separated format: + service.resource.verb (e.g., "onchain.activity.detected", "wallet.activity.detected", "onramp.transaction.created"). + */ + #[serde(rename = "eventTypes")] + pub event_types: ::std::vec::Vec<::std::string::String>, + ///Whether the subscription is enabled. + #[serde(rename = "isEnabled")] + pub is_enabled: bool, + /**Optional. Multi-label filters that trigger only when an event contains ALL of these key-value pairs. + + **Note:** Currently, labels are supported for onchain webhooks only. + + See [allowed labels for onchain webhooks](https://docs.cdp.coinbase.com/api-reference/v2/rest-api/webhooks/create-webhook-subscription#onchain-label-filtering). + Omit to receive all events for the selected event types. + */ + #[serde( + default, + skip_serializing_if = ":: std :: collections :: HashMap::is_empty" + )] + pub labels: ::std::collections::HashMap<::std::string::String, ::std::string::String>, + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub metadata: ::std::option::Option, + pub target: WebhookTarget, } - impl ::std::convert::From<&X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted> - for X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted - { - fn from(value: &X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted) -> Self { + impl ::std::convert::From<&WebhookSubscriptionUpdateRequest> for WebhookSubscriptionUpdateRequest { + fn from(value: &WebhookSubscriptionUpdateRequest) -> Self { value.clone() } } - impl X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted { - pub fn builder() -> builder::X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted { + impl WebhookSubscriptionUpdateRequest { + pub fn builder() -> builder::WebhookSubscriptionUpdateRequest { Default::default() } } - ///The 0x-prefixed, checksum EVM address of the token to transfer. + /**Target configuration for webhook delivery. + Specifies the destination URL and any custom headers to include in webhook requests. + */ /// ///
JSON schema /// /// ```json ///{ - /// "description": "The 0x-prefixed, checksum EVM address of the token to transfer.", + /// "description": "Target configuration for webhook delivery.\nSpecifies the destination URL and any custom headers to include in webhook requests.\n", /// "examples": [ - /// "0x036CbD53842c5426634e7929541eC2318f3dCF7e" + /// { + /// "headers": { + /// "Authorization": "Bearer token123", + /// "Content-Type": "application/json" + /// }, + /// "url": "https://api.example.com/webhooks" + /// } /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" - ///} - /// ``` - ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken(::std::string::String); - impl ::std::ops::Deref for X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } - } - impl ::std::convert::From - for ::std::string::String - { - fn from(value: X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken) -> Self { - value.0 - } - } - impl ::std::convert::From<&X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken> - for X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken - { - fn from(value: &X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken) -> Self { - value.clone() - } - } - impl ::std::str::FromStr for X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken { - type Err = self::error::ConversionError; - fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() - }); - if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); - } - Ok(Self(value.to_string())) - } - } - impl ::std::convert::TryFrom<&str> - for X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken - { - type Error = self::error::ConversionError; - fn try_from(value: &str) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<&::std::string::String> - for X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken - { - type Error = self::error::ConversionError; - fn try_from( - value: &::std::string::String, - ) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<::std::string::String> - for X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken - { - type Error = self::error::ConversionError; - fn try_from( - value: ::std::string::String, - ) -> ::std::result::Result { - value.parse() - } - } - impl<'de> ::serde::Deserialize<'de> - for X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken - { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) - } - } - ///The 0x-prefixed, checksum EVM address of the spender (x402 Permit2 proxy contract). - /// - ///
JSON schema - /// - /// ```json - ///{ - /// "description": "The 0x-prefixed, checksum EVM address of the spender (x402 Permit2 proxy contract).", - /// "examples": [ - /// "0x4020615294c913F045dc10f0a5cdEbd86c280001" + /// "type": "object", + /// "required": [ + /// "url" /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// "properties": { + /// "headers": { + /// "description": "Additional headers to include in webhook requests.", + /// "examples": [ + /// { + /// "Authorization": "Bearer token123", + /// "Content-Type": "application/json" + /// } + /// ], + /// "type": "object", + /// "additionalProperties": { + /// "type": "string" + /// } + /// }, + /// "url": { + /// "description": "The webhook URL to deliver events to.", + /// "examples": [ + /// "https://api.example.com/webhooks" + /// ], + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/Url" + /// } + /// ] + /// } + /// } ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct X402ExactEvmPermit2PayloadPermit2AuthorizationSpender(::std::string::String); - impl ::std::ops::Deref for X402ExactEvmPermit2PayloadPermit2AuthorizationSpender { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } - } - impl ::std::convert::From - for ::std::string::String - { - fn from(value: X402ExactEvmPermit2PayloadPermit2AuthorizationSpender) -> Self { - value.0 - } + #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct WebhookTarget { + ///Additional headers to include in webhook requests. + #[serde( + default, + skip_serializing_if = ":: std :: collections :: HashMap::is_empty" + )] + pub headers: ::std::collections::HashMap<::std::string::String, ::std::string::String>, + ///The webhook URL to deliver events to. + pub url: Url, } - impl ::std::convert::From<&X402ExactEvmPermit2PayloadPermit2AuthorizationSpender> - for X402ExactEvmPermit2PayloadPermit2AuthorizationSpender - { - fn from(value: &X402ExactEvmPermit2PayloadPermit2AuthorizationSpender) -> Self { + impl ::std::convert::From<&WebhookTarget> for WebhookTarget { + fn from(value: &WebhookTarget) -> Self { value.clone() } } - impl ::std::str::FromStr for X402ExactEvmPermit2PayloadPermit2AuthorizationSpender { - type Err = self::error::ConversionError; - fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() - }); - if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); - } - Ok(Self(value.to_string())) - } - } - impl ::std::convert::TryFrom<&str> for X402ExactEvmPermit2PayloadPermit2AuthorizationSpender { - type Error = self::error::ConversionError; - fn try_from(value: &str) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<&::std::string::String> - for X402ExactEvmPermit2PayloadPermit2AuthorizationSpender - { - type Error = self::error::ConversionError; - fn try_from( - value: &::std::string::String, - ) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<::std::string::String> - for X402ExactEvmPermit2PayloadPermit2AuthorizationSpender - { - type Error = self::error::ConversionError; - fn try_from( - value: ::std::string::String, - ) -> ::std::result::Result { - value.parse() - } - } - impl<'de> ::serde::Deserialize<'de> for X402ExactEvmPermit2PayloadPermit2AuthorizationSpender { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) + impl WebhookTarget { + pub fn builder() -> builder::WebhookTarget { + Default::default() } } - ///The witness data containing payment details. + ///Response containing x402 resources associated with a merchant payment address. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The witness data containing payment details.", + /// "description": "Response containing x402 resources associated with a merchant payment address.", /// "type": "object", /// "required": [ - /// "to", - /// "validAfter" + /// "pagination", + /// "payTo", + /// "resources", + /// "x402Version" /// ], /// "properties": { - /// "extra": { - /// "description": "Optional hex-encoded extra data.", + /// "pagination": { + /// "description": "Pagination information for the response.", /// "examples": [ - /// "0x" + /// { + /// "limit": 20, + /// "offset": 0, + /// "total": 10 + /// } /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]*$" + /// "type": "object", + /// "properties": { + /// "limit": { + /// "description": "The number of resources returned per page.", + /// "examples": [ + /// 20 + /// ], + /// "type": "integer" + /// }, + /// "offset": { + /// "description": "The offset of the first resource returned.", + /// "examples": [ + /// 0 + /// ], + /// "type": "integer" + /// }, + /// "total": { + /// "description": "The total number of resources associated with the merchant's payTo address.", + /// "examples": [ + /// 10 + /// ], + /// "type": "integer" + /// } + /// } /// }, - /// "to": { - /// "description": "The 0x-prefixed, checksum EVM address of the recipient.", - /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" - /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// "payTo": { + /// "$ref": "#/components/schemas/BlockchainAddress" /// }, - /// "validAfter": { - /// "description": "The unix timestamp after which the payment is valid.", + /// "resources": { + /// "description": "List of discovered x402 resources associated with the merchant's payTo address.", /// "examples": [ - /// "1716150000" + /// [ + /// { + /// "accepts": [ + /// { + /// "amount": "1000000", + /// "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + /// "maxTimeoutSeconds": 60, + /// "network": "eip155:8453", + /// "payTo": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "scheme": "exact" + /// } + /// ], + /// "description": "Premium API access for data analysis.", + /// "extensions": { + /// "bazaar": { + /// "info": { + /// "input": { + /// "method": "POST", + /// "type": "http" + /// } + /// }, + /// "schema": {} + /// } + /// }, + /// "iconUrl": "https://res.cloudinary.com/bdb-prod/image/upload/...", + /// "lastUpdated": "2024-01-15T10:30:00Z", + /// "quality": { + /// "l30DaysTotalCalls": 42, + /// "l30DaysUniquePayers": 15, + /// "lastCalledAt": "2024-01-15T10:30:00Z" + /// }, + /// "resource": "https://api.example.com/premium/data", + /// "serviceName": "Premium Data API", + /// "tags": [ + /// "data", + /// "analytics" + /// ], + /// "type": "http", + /// "x402Version": 2 + /// } + /// ] /// ], - /// "type": "string" + /// "type": "array", + /// "items": { + /// "$ref": "#/components/schemas/x402DiscoveryResource" + /// } + /// }, + /// "x402Version": { + /// "$ref": "#/components/schemas/X402Version" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402ExactEvmPermit2PayloadPermit2AuthorizationWitness { - ///Optional hex-encoded extra data. - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub extra: - ::std::option::Option, - ///The 0x-prefixed, checksum EVM address of the recipient. - pub to: X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo, - ///The unix timestamp after which the payment is valid. - #[serde(rename = "validAfter")] - pub valid_after: ::std::string::String, + pub struct X402DiscoveryMerchantResponse { + pub pagination: X402DiscoveryMerchantResponsePagination, + #[serde(rename = "payTo")] + pub pay_to: BlockchainAddress, + ///List of discovered x402 resources associated with the merchant's payTo address. + pub resources: ::std::vec::Vec, + #[serde(rename = "x402Version")] + pub x402_version: X402Version, } - impl ::std::convert::From<&X402ExactEvmPermit2PayloadPermit2AuthorizationWitness> - for X402ExactEvmPermit2PayloadPermit2AuthorizationWitness - { - fn from(value: &X402ExactEvmPermit2PayloadPermit2AuthorizationWitness) -> Self { + impl ::std::convert::From<&X402DiscoveryMerchantResponse> for X402DiscoveryMerchantResponse { + fn from(value: &X402DiscoveryMerchantResponse) -> Self { value.clone() } } - impl X402ExactEvmPermit2PayloadPermit2AuthorizationWitness { - pub fn builder() -> builder::X402ExactEvmPermit2PayloadPermit2AuthorizationWitness { + impl X402DiscoveryMerchantResponse { + pub fn builder() -> builder::X402DiscoveryMerchantResponse { Default::default() } } - ///Optional hex-encoded extra data. + ///Pagination information for the response. /// ///
JSON schema /// /// ```json ///{ - /// "description": "Optional hex-encoded extra data.", + /// "description": "Pagination information for the response.", /// "examples": [ - /// "0x" + /// { + /// "limit": 20, + /// "offset": 0, + /// "total": 10 + /// } /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]*$" + /// "type": "object", + /// "properties": { + /// "limit": { + /// "description": "The number of resources returned per page.", + /// "examples": [ + /// 20 + /// ], + /// "type": "integer" + /// }, + /// "offset": { + /// "description": "The offset of the first resource returned.", + /// "examples": [ + /// 0 + /// ], + /// "type": "integer" + /// }, + /// "total": { + /// "description": "The total number of resources associated with the merchant's payTo address.", + /// "examples": [ + /// 10 + /// ], + /// "type": "integer" + /// } + /// } ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra(::std::string::String); - impl ::std::ops::Deref for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } - } - impl ::std::convert::From - for ::std::string::String - { - fn from(value: X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra) -> Self { - value.0 - } + #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct X402DiscoveryMerchantResponsePagination { + ///The number of resources returned per page. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub limit: ::std::option::Option, + ///The offset of the first resource returned. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub offset: ::std::option::Option, + ///The total number of resources associated with the merchant's payTo address. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub total: ::std::option::Option, } - impl ::std::convert::From<&X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra> - for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra + impl ::std::convert::From<&X402DiscoveryMerchantResponsePagination> + for X402DiscoveryMerchantResponsePagination { - fn from(value: &X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra) -> Self { + fn from(value: &X402DiscoveryMerchantResponsePagination) -> Self { value.clone() } } - impl ::std::str::FromStr for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra { - type Err = self::error::ConversionError; - fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| ::regress::Regex::new("^0x[0-9a-fA-F]*$").unwrap()); - if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]*$\"".into()); + impl ::std::default::Default for X402DiscoveryMerchantResponsePagination { + fn default() -> Self { + Self { + limit: Default::default(), + offset: Default::default(), + total: Default::default(), } - Ok(Self(value.to_string())) - } - } - impl ::std::convert::TryFrom<&str> for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra { - type Error = self::error::ConversionError; - fn try_from(value: &str) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<&::std::string::String> - for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra - { - type Error = self::error::ConversionError; - fn try_from( - value: &::std::string::String, - ) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<::std::string::String> - for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra - { - type Error = self::error::ConversionError; - fn try_from( - value: ::std::string::String, - ) -> ::std::result::Result { - value.parse() } } - impl<'de> ::serde::Deserialize<'de> for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) + impl X402DiscoveryMerchantResponsePagination { + pub fn builder() -> builder::X402DiscoveryMerchantResponsePagination { + Default::default() } } - ///The 0x-prefixed, checksum EVM address of the recipient. + ///A single discovered x402 resource. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The 0x-prefixed, checksum EVM address of the recipient.", - /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// "description": "A single discovered x402 resource.", + /// "type": "object", + /// "required": [ + /// "resource", + /// "type", + /// "x402Version" /// ], - /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{40}$" - ///} - /// ``` - ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo(::std::string::String); - impl ::std::ops::Deref for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } - } - impl ::std::convert::From - for ::std::string::String - { - fn from(value: X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo) -> Self { - value.0 - } - } - impl ::std::convert::From<&X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo> - for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo - { - fn from(value: &X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo) -> Self { - value.clone() - } - } - impl ::std::str::FromStr for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo { - type Err = self::error::ConversionError; - fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() - }); - if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); - } - Ok(Self(value.to_string())) - } - } - impl ::std::convert::TryFrom<&str> for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo { - type Error = self::error::ConversionError; - fn try_from(value: &str) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<&::std::string::String> - for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo - { - type Error = self::error::ConversionError; - fn try_from( - value: &::std::string::String, - ) -> ::std::result::Result { - value.parse() - } + /// "properties": { + /// "accepts": { + /// "description": "Payment requirements accepted by the resource.", + /// "examples": [ + /// [ + /// { + /// "amount": "1000000", + /// "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + /// "maxTimeoutSeconds": 60, + /// "network": "eip155:8453", + /// "payTo": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "scheme": "exact" + /// } + /// ] + /// ], + /// "type": "array", + /// "items": { + /// "$ref": "#/components/schemas/x402PaymentRequirements" + /// } + /// }, + /// "description": { + /// "description": "A human-readable description of the resource.", + /// "examples": [ + /// "Real-time weather forecast data" + /// ], + /// "type": "string" + /// }, + /// "extensions": { + /// "description": "Map of x402 protocol extensions supported by the resource, keyed by extension name.", + /// "examples": [ + /// { + /// "bazaar": { + /// "info": { + /// "input": { + /// "method": "GET", + /// "type": "http" + /// } + /// }, + /// "schema": {} + /// } + /// } + /// ], + /// "type": "object", + /// "additionalProperties": true + /// }, + /// "iconUrl": { + /// "description": "URL of a square icon representing the service this resource belongs to. Distinct from a\nbrand logo: this is intended for compact, list-view rendering (favicon-style) and is\nnormalized to a square aspect ratio at ingestion. The image is moderated and re-hosted by\nCoinbase, so the URL is stable and safe to render directly in clients. Omitted when the\nprovider did not supply an icon, when the supplied icon failed moderation, or when image\nprocessing was unavailable at ingestion time.\n", + /// "examples": [ + /// "https://res.cloudinary.com/bdb-prod/image/upload/..." + /// ], + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/Url" + /// } + /// ] + /// }, + /// "lastUpdated": { + /// "description": "Timestamp of the last update.", + /// "examples": [ + /// "2024-01-15T10:30:00Z" + /// ], + /// "type": "string", + /// "format": "date-time" + /// }, + /// "quality": { + /// "$ref": "#/components/schemas/x402ResourceQuality" + /// }, + /// "resource": { + /// "description": "The URL of the resource.", + /// "examples": [ + /// "https://api.example.com/weather/forecast" + /// ], + /// "type": "string" + /// }, + /// "serviceName": { + /// "description": "Provider-supplied display name of the service this resource belongs to. This is a free-form\nlabel for grouping and presentation only — it is not a stable identifier, and two resources\nsharing the same `serviceName` are not guaranteed to belong to the same logical service.\n", + /// "examples": [ + /// "Weather API" + /// ], + /// "type": "string" + /// }, + /// "tags": { + /// "description": "Provider-supplied, low-cardinality string labels associated with the resource for client-side\nfiltering and display. Values are free-form (no controlled vocabulary) and case-sensitive.\nOrder is not significant and duplicates are not expected.\n", + /// "examples": [ + /// [ + /// "weather", + /// "data" + /// ] + /// ], + /// "type": "array", + /// "items": { + /// "type": "string" + /// } + /// }, + /// "type": { + /// "description": "Communication protocol (e.g., \"http\", \"mcp\").", + /// "examples": [ + /// "http" + /// ], + /// "type": "string", + /// "enum": [ + /// "http", + /// "mcp" + /// ] + /// }, + /// "x402Version": { + /// "$ref": "#/components/schemas/X402Version" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct X402DiscoveryResource { + ///Payment requirements accepted by the resource. + #[serde(default, skip_serializing_if = "::std::vec::Vec::is_empty")] + pub accepts: ::std::vec::Vec, + ///A human-readable description of the resource. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub description: ::std::option::Option<::std::string::String>, + ///Map of x402 protocol extensions supported by the resource, keyed by extension name. + #[serde(default, skip_serializing_if = "::serde_json::Map::is_empty")] + pub extensions: ::serde_json::Map<::std::string::String, ::serde_json::Value>, + /**URL of a square icon representing the service this resource belongs to. Distinct from a + brand logo: this is intended for compact, list-view rendering (favicon-style) and is + normalized to a square aspect ratio at ingestion. The image is moderated and re-hosted by + Coinbase, so the URL is stable and safe to render directly in clients. Omitted when the + provider did not supply an icon, when the supplied icon failed moderation, or when image + processing was unavailable at ingestion time. + */ + #[serde( + rename = "iconUrl", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub icon_url: ::std::option::Option, + ///Timestamp of the last update. + #[serde( + rename = "lastUpdated", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub last_updated: ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub quality: ::std::option::Option, + ///The URL of the resource. + pub resource: ::std::string::String, + /**Provider-supplied display name of the service this resource belongs to. This is a free-form + label for grouping and presentation only — it is not a stable identifier, and two resources + sharing the same `serviceName` are not guaranteed to belong to the same logical service. + */ + #[serde( + rename = "serviceName", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub service_name: ::std::option::Option<::std::string::String>, + /**Provider-supplied, low-cardinality string labels associated with the resource for client-side + filtering and display. Values are free-form (no controlled vocabulary) and case-sensitive. + Order is not significant and duplicates are not expected. + */ + #[serde(default, skip_serializing_if = "::std::vec::Vec::is_empty")] + pub tags: ::std::vec::Vec<::std::string::String>, + ///Communication protocol (e.g., "http", "mcp"). + #[serde(rename = "type")] + pub type_: X402DiscoveryResourceType, + #[serde(rename = "x402Version")] + pub x402_version: X402Version, } - impl ::std::convert::TryFrom<::std::string::String> - for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo - { - type Error = self::error::ConversionError; - fn try_from( - value: ::std::string::String, - ) -> ::std::result::Result { - value.parse() + impl ::std::convert::From<&X402DiscoveryResource> for X402DiscoveryResource { + fn from(value: &X402DiscoveryResource) -> Self { + value.clone() } } - impl<'de> ::serde::Deserialize<'de> for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) + impl X402DiscoveryResource { + pub fn builder() -> builder::X402DiscoveryResource { + Default::default() } } - ///The EIP-712 hex-encoded signature of the Permit2 PermitWitnessTransferFrom message. Smart account signatures may be longer than 65 bytes. + ///Communication protocol (e.g., "http", "mcp"). /// ///
JSON schema /// /// ```json ///{ - /// "description": "The EIP-712 hex-encoded signature of the Permit2 PermitWitnessTransferFrom message. Smart account signatures may be longer than 65 bytes.", + /// "description": "Communication protocol (e.g., \"http\", \"mcp\").", /// "examples": [ - /// "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" + /// "http" /// ], /// "type": "string", - /// "pattern": "^0x[0-9a-fA-F]{130,}$" + /// "enum": [ + /// "http", + /// "mcp" + /// ] ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct X402ExactEvmPermit2PayloadSignature(::std::string::String); - impl ::std::ops::Deref for X402ExactEvmPermit2PayloadSignature { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } + #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum X402DiscoveryResourceType { + #[serde(rename = "http")] + Http, + #[serde(rename = "mcp")] + Mcp, } - impl ::std::convert::From for ::std::string::String { - fn from(value: X402ExactEvmPermit2PayloadSignature) -> Self { - value.0 + impl ::std::convert::From<&Self> for X402DiscoveryResourceType { + fn from(value: &X402DiscoveryResourceType) -> Self { + value.clone() } } - impl ::std::convert::From<&X402ExactEvmPermit2PayloadSignature> - for X402ExactEvmPermit2PayloadSignature - { - fn from(value: &X402ExactEvmPermit2PayloadSignature) -> Self { - value.clone() + impl ::std::fmt::Display for X402DiscoveryResourceType { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Http => f.write_str("http"), + Self::Mcp => f.write_str("mcp"), + } } } - impl ::std::str::FromStr for X402ExactEvmPermit2PayloadSignature { + impl ::std::str::FromStr for X402DiscoveryResourceType { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^0x[0-9a-fA-F]{130,}$").unwrap() - }); - if PATTERN.find(value).is_none() { - return Err("doesn't match pattern \"^0x[0-9a-fA-F]{130,}$\"".into()); + match value { + "http" => Ok(Self::Http), + "mcp" => Ok(Self::Mcp), + _ => Err("invalid value".into()), } - Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for X402ExactEvmPermit2PayloadSignature { + impl ::std::convert::TryFrom<&str> for X402DiscoveryResourceType { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for X402ExactEvmPermit2PayloadSignature { + impl ::std::convert::TryFrom<&::std::string::String> for X402DiscoveryResourceType { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -57176,7 +62941,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for X402ExactEvmPermit2PayloadSignature { + impl ::std::convert::TryFrom<::std::string::String> for X402DiscoveryResourceType { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -57184,313 +62949,486 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for X402ExactEvmPermit2PayloadSignature { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) - } - } - ///The x402 protocol exact scheme payload for Solana networks. For more details, please see [Solana Exact Scheme Details](https://github.com/coinbase/x402/blob/main/specs/schemes/exact/scheme_exact_svm.md). + ///Response containing discovered x402 resources. /// ///
JSON schema /// /// ```json ///{ - /// "title": "x402ExactSolanaPayload", - /// "description": "The x402 protocol exact scheme payload for Solana networks. For more details, please see [Solana Exact Scheme Details](https://github.com/coinbase/x402/blob/main/specs/schemes/exact/scheme_exact_svm.md).", - /// "examples": [ - /// { - /// "transaction": "AQABAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA=" - /// } - /// ], + /// "description": "Response containing discovered x402 resources.", /// "type": "object", /// "required": [ - /// "transaction" + /// "items", + /// "pagination", + /// "x402Version" /// ], /// "properties": { - /// "transaction": { - /// "description": "The base64-encoded Solana transaction.", + /// "items": { + /// "description": "List of discovered x402 resources.", /// "examples": [ - /// "AQABAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA=" + /// [ + /// { + /// "accepts": [ + /// { + /// "amount": "1000000", + /// "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + /// "maxTimeoutSeconds": 60, + /// "network": "eip155:8453", + /// "payTo": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "scheme": "exact" + /// } + /// ], + /// "description": "Real-time weather forecast data.", + /// "extensions": { + /// "bazaar": { + /// "info": { + /// "input": { + /// "method": "GET", + /// "type": "http" + /// } + /// }, + /// "schema": {} + /// } + /// }, + /// "iconUrl": "https://res.cloudinary.com/bdb-prod/image/upload/...", + /// "lastUpdated": "2024-01-15T10:30:00Z", + /// "quality": { + /// "l30DaysTotalCalls": 42, + /// "l30DaysUniquePayers": 15, + /// "lastCalledAt": "2024-01-15T10:30:00Z" + /// }, + /// "resource": "https://api.example.com/weather/forecast", + /// "serviceName": "Weather API", + /// "tags": [ + /// "weather", + /// "data" + /// ], + /// "type": "http", + /// "x402Version": 2 + /// } + /// ] /// ], - /// "type": "string" + /// "type": "array", + /// "items": { + /// "$ref": "#/components/schemas/x402DiscoveryResource" + /// } + /// }, + /// "pagination": { + /// "description": "Pagination information for the response.", + /// "examples": [ + /// { + /// "limit": 100, + /// "offset": 0, + /// "total": 1000 + /// } + /// ], + /// "type": "object", + /// "properties": { + /// "limit": { + /// "description": "The number of discovered x402 resources to return per page.", + /// "examples": [ + /// 100 + /// ], + /// "type": "integer" + /// }, + /// "offset": { + /// "description": "The offset of the first discovered x402 resource to return.", + /// "examples": [ + /// 0 + /// ], + /// "type": "integer" + /// }, + /// "total": { + /// "description": "The total number of discovered x402 resources.", + /// "examples": [ + /// 1000 + /// ], + /// "type": "integer" + /// } + /// } + /// }, + /// "x402Version": { + /// "$ref": "#/components/schemas/X402Version" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402ExactSolanaPayload { - ///The base64-encoded Solana transaction. - pub transaction: ::std::string::String, + pub struct X402DiscoveryResourcesResponse { + ///List of discovered x402 resources. + pub items: ::std::vec::Vec, + pub pagination: X402DiscoveryResourcesResponsePagination, + #[serde(rename = "x402Version")] + pub x402_version: X402Version, } - impl ::std::convert::From<&X402ExactSolanaPayload> for X402ExactSolanaPayload { - fn from(value: &X402ExactSolanaPayload) -> Self { + impl ::std::convert::From<&X402DiscoveryResourcesResponse> for X402DiscoveryResourcesResponse { + fn from(value: &X402DiscoveryResourcesResponse) -> Self { value.clone() } } - impl X402ExactSolanaPayload { - pub fn builder() -> builder::X402ExactSolanaPayload { + impl X402DiscoveryResourcesResponse { + pub fn builder() -> builder::X402DiscoveryResourcesResponse { Default::default() } } - ///JSON-RPC 2.0 error object. + ///Pagination information for the response. /// ///
JSON schema /// /// ```json ///{ - /// "description": "JSON-RPC 2.0 error object.", + /// "description": "Pagination information for the response.", /// "examples": [ /// { - /// "code": -32600, - /// "data": {}, - /// "message": "Invalid Request" + /// "limit": 100, + /// "offset": 0, + /// "total": 1000 /// } /// ], /// "type": "object", - /// "required": [ - /// "code", - /// "message" - /// ], /// "properties": { - /// "code": { - /// "description": "Error code.", + /// "limit": { + /// "description": "The number of discovered x402 resources to return per page.", /// "examples": [ - /// -32600 + /// 100 /// ], /// "type": "integer" /// }, - /// "data": { - /// "description": "Additional error data.", + /// "offset": { + /// "description": "The offset of the first discovered x402 resource to return.", /// "examples": [ - /// {} + /// 0 /// ], - /// "type": "object", - /// "additionalProperties": true + /// "type": "integer" /// }, - /// "message": { - /// "description": "Error message.", + /// "total": { + /// "description": "The total number of discovered x402 resources.", /// "examples": [ - /// "Invalid Request" + /// 1000 /// ], - /// "type": "string" + /// "type": "integer" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402McpError { - ///Error code. - pub code: i64, - ///Additional error data. - #[serde(default, skip_serializing_if = "::serde_json::Map::is_empty")] - pub data: ::serde_json::Map<::std::string::String, ::serde_json::Value>, - ///Error message. - pub message: ::std::string::String, + pub struct X402DiscoveryResourcesResponsePagination { + ///The number of discovered x402 resources to return per page. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub limit: ::std::option::Option, + ///The offset of the first discovered x402 resource to return. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub offset: ::std::option::Option, + ///The total number of discovered x402 resources. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub total: ::std::option::Option, } - impl ::std::convert::From<&X402McpError> for X402McpError { - fn from(value: &X402McpError) -> Self { + impl ::std::convert::From<&X402DiscoveryResourcesResponsePagination> + for X402DiscoveryResourcesResponsePagination + { + fn from(value: &X402DiscoveryResourcesResponsePagination) -> Self { value.clone() } } - impl X402McpError { - pub fn builder() -> builder::X402McpError { + impl ::std::default::Default for X402DiscoveryResourcesResponsePagination { + fn default() -> Self { + Self { + limit: Default::default(), + offset: Default::default(), + total: Default::default(), + } + } + } + impl X402DiscoveryResourcesResponsePagination { + pub fn builder() -> builder::X402DiscoveryResourcesResponsePagination { Default::default() } } - ///A JSON-RPC 2.0 request for the Model Context Protocol. + ///The x402 protocol exact scheme payload for EVM networks. The scheme is implemented using ERC-3009. For more details, please see [EVM Exact Scheme Details](https://github.com/coinbase/x402/blob/main/specs/schemes/exact/scheme_exact_evm.md). /// ///
JSON schema /// /// ```json ///{ - /// "description": "A JSON-RPC 2.0 request for the Model Context Protocol.", + /// "title": "x402ExactEvmPayload", + /// "description": "The x402 protocol exact scheme payload for EVM networks. The scheme is implemented using ERC-3009. For more details, please see [EVM Exact Scheme Details](https://github.com/coinbase/x402/blob/main/specs/schemes/exact/scheme_exact_evm.md).", + /// "examples": [ + /// { + /// "authorization": { + /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "nonce": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", + /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "validAfter": "1716150000", + /// "validBefore": "1716150000", + /// "value": "1000000000000000000" + /// }, + /// "signature": "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" + /// } + /// ], /// "type": "object", /// "required": [ - /// "jsonrpc", - /// "method" + /// "authorization", + /// "signature" /// ], /// "properties": { - /// "id": { - /// "description": "Request identifier.", + /// "authorization": { + /// "description": "The authorization data for the ERC-3009 authorization message.", /// "examples": [ - /// 1 - /// ], - /// "oneOf": [ - /// { - /// "type": "string" - /// }, /// { - /// "type": "integer" + /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "nonce": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", + /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "validAfter": "1716150000", + /// "validBefore": "1716150000", + /// "value": "1000000000000000000" /// } - /// ] - /// }, - /// "jsonrpc": { - /// "description": "JSON-RPC version, must be \"2.0\".", - /// "examples": [ - /// "2.0" - /// ], - /// "type": "string", - /// "enum": [ - /// "2.0" - /// ] - /// }, - /// "method": { - /// "description": "The MCP method to invoke.", - /// "examples": [ - /// "tools/list" /// ], - /// "type": "string" + /// "type": "object", + /// "required": [ + /// "from", + /// "nonce", + /// "to", + /// "validAfter", + /// "validBefore", + /// "value" + /// ], + /// "properties": { + /// "from": { + /// "description": "The 0x-prefixed, checksum EVM address of the sender of the payment.", + /// "examples": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// }, + /// "nonce": { + /// "description": "The hex-encoded nonce of the payment (bytes32).", + /// "examples": [ + /// "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{64}$" + /// }, + /// "to": { + /// "description": "The 0x-prefixed, checksum EVM address of the recipient of the payment.", + /// "examples": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// }, + /// "validAfter": { + /// "description": "The unix timestamp after which the payment is valid.", + /// "examples": [ + /// "1716150000" + /// ], + /// "type": "string" + /// }, + /// "validBefore": { + /// "description": "The unix timestamp before which the payment is valid.", + /// "examples": [ + /// "1716150000" + /// ], + /// "type": "string" + /// }, + /// "value": { + /// "description": "The value of the payment, in atomic units of the payment asset.", + /// "examples": [ + /// "1000000000000000000" + /// ], + /// "type": "string" + /// } + /// } /// }, - /// "params": { - /// "description": "Optional parameters for the method.", + /// "signature": { + /// "description": "The EIP-712 hex-encoded signature of the ERC-3009 authorization message. Smart account signatures may be longer than 65 bytes.", /// "examples": [ - /// {} + /// "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" /// ], - /// "type": "object", - /// "additionalProperties": true + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{130,}$" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402McpRequest { - ///Request identifier. - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub id: ::std::option::Option, - ///JSON-RPC version, must be "2.0". - pub jsonrpc: X402McpRequestJsonrpc, - ///The MCP method to invoke. - pub method: ::std::string::String, - ///Optional parameters for the method. - #[serde(default, skip_serializing_if = "::serde_json::Map::is_empty")] - pub params: ::serde_json::Map<::std::string::String, ::serde_json::Value>, + pub struct X402ExactEvmPayload { + pub authorization: X402ExactEvmPayloadAuthorization, + ///The EIP-712 hex-encoded signature of the ERC-3009 authorization message. Smart account signatures may be longer than 65 bytes. + pub signature: X402ExactEvmPayloadSignature, } - impl ::std::convert::From<&X402McpRequest> for X402McpRequest { - fn from(value: &X402McpRequest) -> Self { + impl ::std::convert::From<&X402ExactEvmPayload> for X402ExactEvmPayload { + fn from(value: &X402ExactEvmPayload) -> Self { value.clone() } } - impl X402McpRequest { - pub fn builder() -> builder::X402McpRequest { + impl X402ExactEvmPayload { + pub fn builder() -> builder::X402ExactEvmPayload { Default::default() } } - ///Request identifier. + ///The authorization data for the ERC-3009 authorization message. /// ///
JSON schema /// /// ```json ///{ - /// "description": "Request identifier.", + /// "description": "The authorization data for the ERC-3009 authorization message.", /// "examples": [ - /// 1 - /// ], - /// "oneOf": [ /// { + /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "nonce": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", + /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "validAfter": "1716150000", + /// "validBefore": "1716150000", + /// "value": "1000000000000000000" + /// } + /// ], + /// "type": "object", + /// "required": [ + /// "from", + /// "nonce", + /// "to", + /// "validAfter", + /// "validBefore", + /// "value" + /// ], + /// "properties": { + /// "from": { + /// "description": "The 0x-prefixed, checksum EVM address of the sender of the payment.", + /// "examples": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// }, + /// "nonce": { + /// "description": "The hex-encoded nonce of the payment (bytes32).", + /// "examples": [ + /// "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{64}$" + /// }, + /// "to": { + /// "description": "The 0x-prefixed, checksum EVM address of the recipient of the payment.", + /// "examples": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// }, + /// "validAfter": { + /// "description": "The unix timestamp after which the payment is valid.", + /// "examples": [ + /// "1716150000" + /// ], /// "type": "string" /// }, - /// { - /// "type": "integer" + /// "validBefore": { + /// "description": "The unix timestamp before which the payment is valid.", + /// "examples": [ + /// "1716150000" + /// ], + /// "type": "string" + /// }, + /// "value": { + /// "description": "The value of the payment, in atomic units of the payment asset.", + /// "examples": [ + /// "1000000000000000000" + /// ], + /// "type": "string" /// } - /// ] + /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - #[serde(untagged)] - pub enum X402McpRequestId { - Variant0(::std::string::String), - Variant1(i64), + pub struct X402ExactEvmPayloadAuthorization { + ///The 0x-prefixed, checksum EVM address of the sender of the payment. + pub from: X402ExactEvmPayloadAuthorizationFrom, + ///The hex-encoded nonce of the payment (bytes32). + pub nonce: X402ExactEvmPayloadAuthorizationNonce, + ///The 0x-prefixed, checksum EVM address of the recipient of the payment. + pub to: X402ExactEvmPayloadAuthorizationTo, + ///The unix timestamp after which the payment is valid. + #[serde(rename = "validAfter")] + pub valid_after: ::std::string::String, + ///The unix timestamp before which the payment is valid. + #[serde(rename = "validBefore")] + pub valid_before: ::std::string::String, + ///The value of the payment, in atomic units of the payment asset. + pub value: ::std::string::String, } - impl ::std::convert::From<&Self> for X402McpRequestId { - fn from(value: &X402McpRequestId) -> Self { + impl ::std::convert::From<&X402ExactEvmPayloadAuthorization> for X402ExactEvmPayloadAuthorization { + fn from(value: &X402ExactEvmPayloadAuthorization) -> Self { value.clone() } } - impl ::std::fmt::Display for X402McpRequestId { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - match self { - Self::Variant0(x) => x.fmt(f), - Self::Variant1(x) => x.fmt(f), - } - } - } - impl ::std::convert::From for X402McpRequestId { - fn from(value: i64) -> Self { - Self::Variant1(value) + impl X402ExactEvmPayloadAuthorization { + pub fn builder() -> builder::X402ExactEvmPayloadAuthorization { + Default::default() } } - ///JSON-RPC version, must be "2.0". + ///The 0x-prefixed, checksum EVM address of the sender of the payment. /// ///
JSON schema /// /// ```json ///{ - /// "description": "JSON-RPC version, must be \"2.0\".", + /// "description": "The 0x-prefixed, checksum EVM address of the sender of the payment.", /// "examples": [ - /// "2.0" + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" /// ], /// "type": "string", - /// "enum": [ - /// "2.0" - /// ] + /// "pattern": "^0x[0-9a-fA-F]{40}$" ///} /// ``` ///
- #[derive( - ::serde::Deserialize, - ::serde::Serialize, - Clone, - Copy, - Debug, - Eq, - Hash, - Ord, - PartialEq, - PartialOrd, - )] - pub enum X402McpRequestJsonrpc { - #[serde(rename = "2.0")] - X20, + #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct X402ExactEvmPayloadAuthorizationFrom(::std::string::String); + impl ::std::ops::Deref for X402ExactEvmPayloadAuthorizationFrom { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } } - impl ::std::convert::From<&Self> for X402McpRequestJsonrpc { - fn from(value: &X402McpRequestJsonrpc) -> Self { - value.clone() + impl ::std::convert::From for ::std::string::String { + fn from(value: X402ExactEvmPayloadAuthorizationFrom) -> Self { + value.0 } } - impl ::std::fmt::Display for X402McpRequestJsonrpc { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - match *self { - Self::X20 => f.write_str("2.0"), - } + impl ::std::convert::From<&X402ExactEvmPayloadAuthorizationFrom> + for X402ExactEvmPayloadAuthorizationFrom + { + fn from(value: &X402ExactEvmPayloadAuthorizationFrom) -> Self { + value.clone() } } - impl ::std::str::FromStr for X402McpRequestJsonrpc { + impl ::std::str::FromStr for X402ExactEvmPayloadAuthorizationFrom { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - match value { - "2.0" => Ok(Self::X20), - _ => Err("invalid value".into()), + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); } + Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for X402McpRequestJsonrpc { + impl ::std::convert::TryFrom<&str> for X402ExactEvmPayloadAuthorizationFrom { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for X402McpRequestJsonrpc { + impl ::std::convert::TryFrom<&::std::string::String> for X402ExactEvmPayloadAuthorizationFrom { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -57498,7 +63436,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for X402McpRequestJsonrpc { + impl ::std::convert::TryFrom<::std::string::String> for X402ExactEvmPayloadAuthorizationFrom { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -57506,191 +63444,157 @@ pub mod types { value.parse() } } - ///A JSON-RPC 2.0 response for the Model Context Protocol. + impl<'de> ::serde::Deserialize<'de> for X402ExactEvmPayloadAuthorizationFrom { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///The hex-encoded nonce of the payment (bytes32). /// ///
JSON schema /// /// ```json ///{ - /// "description": "A JSON-RPC 2.0 response for the Model Context Protocol.", - /// "type": "object", - /// "required": [ - /// "jsonrpc" + /// "description": "The hex-encoded nonce of the payment (bytes32).", + /// "examples": [ + /// "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" /// ], - /// "properties": { - /// "error": { - /// "$ref": "#/components/schemas/x402McpError" - /// }, - /// "id": { - /// "description": "Request identifier (matches the request ID, null for notifications).", - /// "examples": [ - /// 1 - /// ], - /// "oneOf": [ - /// { - /// "type": "null" - /// }, - /// { - /// "oneOf": [ - /// { - /// "type": "string" - /// }, - /// { - /// "type": "integer" - /// } - /// ] - /// } - /// ] - /// }, - /// "jsonrpc": { - /// "description": "JSON-RPC version.", - /// "examples": [ - /// "2.0" - /// ], - /// "type": "string", - /// "enum": [ - /// "2.0" - /// ] - /// }, - /// "result": { - /// "description": "The result of the method call (present on success).", - /// "examples": [ - /// { - /// "tools": [] - /// } - /// ], - /// "type": "object", - /// "additionalProperties": true - /// } - /// } + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{64}$" ///} /// ``` ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402McpResponse { - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub error: ::std::option::Option, - ///Request identifier (matches the request ID, null for notifications). - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub id: ::std::option::Option, - ///JSON-RPC version. - pub jsonrpc: X402McpResponseJsonrpc, - ///The result of the method call (present on success). - #[serde(default, skip_serializing_if = "::serde_json::Map::is_empty")] - pub result: ::serde_json::Map<::std::string::String, ::serde_json::Value>, + #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct X402ExactEvmPayloadAuthorizationNonce(::std::string::String); + impl ::std::ops::Deref for X402ExactEvmPayloadAuthorizationNonce { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } } - impl ::std::convert::From<&X402McpResponse> for X402McpResponse { - fn from(value: &X402McpResponse) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: X402ExactEvmPayloadAuthorizationNonce) -> Self { + value.0 + } + } + impl ::std::convert::From<&X402ExactEvmPayloadAuthorizationNonce> + for X402ExactEvmPayloadAuthorizationNonce + { + fn from(value: &X402ExactEvmPayloadAuthorizationNonce) -> Self { value.clone() } } - impl X402McpResponse { - pub fn builder() -> builder::X402McpResponse { - Default::default() + impl ::std::str::FromStr for X402ExactEvmPayloadAuthorizationNonce { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^0x[0-9a-fA-F]{64}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^0x[0-9a-fA-F]{64}$\"".into()); + } + Ok(Self(value.to_string())) } } - ///`X402McpResponseId` - /// - ///
JSON schema - /// - /// ```json - ///{ - /// "oneOf": [ - /// { - /// "type": "string" - /// }, - /// { - /// "type": "integer" - /// } - /// ] - ///} - /// ``` - ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - #[serde(untagged)] - pub enum X402McpResponseId { - Variant0(::std::string::String), - Variant1(i64), + impl ::std::convert::TryFrom<&str> for X402ExactEvmPayloadAuthorizationNonce { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } } - impl ::std::convert::From<&Self> for X402McpResponseId { - fn from(value: &X402McpResponseId) -> Self { - value.clone() + impl ::std::convert::TryFrom<&::std::string::String> for X402ExactEvmPayloadAuthorizationNonce { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() } } - impl ::std::fmt::Display for X402McpResponseId { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - match self { - Self::Variant0(x) => x.fmt(f), - Self::Variant1(x) => x.fmt(f), - } + impl ::std::convert::TryFrom<::std::string::String> for X402ExactEvmPayloadAuthorizationNonce { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() } } - impl ::std::convert::From for X402McpResponseId { - fn from(value: i64) -> Self { - Self::Variant1(value) + impl<'de> ::serde::Deserialize<'de> for X402ExactEvmPayloadAuthorizationNonce { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) } } - ///JSON-RPC version. + ///The 0x-prefixed, checksum EVM address of the recipient of the payment. /// ///
JSON schema /// /// ```json ///{ - /// "description": "JSON-RPC version.", + /// "description": "The 0x-prefixed, checksum EVM address of the recipient of the payment.", /// "examples": [ - /// "2.0" + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" /// ], /// "type": "string", - /// "enum": [ - /// "2.0" - /// ] + /// "pattern": "^0x[0-9a-fA-F]{40}$" ///} /// ``` ///
- #[derive( - ::serde::Deserialize, - ::serde::Serialize, - Clone, - Copy, - Debug, - Eq, - Hash, - Ord, - PartialEq, - PartialOrd, - )] - pub enum X402McpResponseJsonrpc { - #[serde(rename = "2.0")] - X20, + #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct X402ExactEvmPayloadAuthorizationTo(::std::string::String); + impl ::std::ops::Deref for X402ExactEvmPayloadAuthorizationTo { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } } - impl ::std::convert::From<&Self> for X402McpResponseJsonrpc { - fn from(value: &X402McpResponseJsonrpc) -> Self { - value.clone() + impl ::std::convert::From for ::std::string::String { + fn from(value: X402ExactEvmPayloadAuthorizationTo) -> Self { + value.0 } } - impl ::std::fmt::Display for X402McpResponseJsonrpc { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - match *self { - Self::X20 => f.write_str("2.0"), - } + impl ::std::convert::From<&X402ExactEvmPayloadAuthorizationTo> + for X402ExactEvmPayloadAuthorizationTo + { + fn from(value: &X402ExactEvmPayloadAuthorizationTo) -> Self { + value.clone() } } - impl ::std::str::FromStr for X402McpResponseJsonrpc { + impl ::std::str::FromStr for X402ExactEvmPayloadAuthorizationTo { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - match value { - "2.0" => Ok(Self::X20), - _ => Err("invalid value".into()), + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); } + Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for X402McpResponseJsonrpc { + impl ::std::convert::TryFrom<&str> for X402ExactEvmPayloadAuthorizationTo { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for X402McpResponseJsonrpc { + impl ::std::convert::TryFrom<&::std::string::String> for X402ExactEvmPayloadAuthorizationTo { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -57698,7 +63602,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for X402McpResponseJsonrpc { + impl ::std::convert::TryFrom<::std::string::String> for X402ExactEvmPayloadAuthorizationTo { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -57706,391 +63610,723 @@ pub mod types { value.parse() } } - /**The x402 protocol payment payload that the client attaches to x402-paid API requests to the resource server in the X-PAYMENT header. - For EVM networks, smart account signatures can be longer than 65 bytes.*/ - /// - ///
JSON schema - /// - /// ```json - ///{ - /// "description": "The x402 protocol payment payload that the client attaches to x402-paid API requests to the resource server in the X-PAYMENT header.\nFor EVM networks, smart account signatures can be longer than 65 bytes.", - /// "type": "object", - /// "oneOf": [ - /// { - /// "$ref": "#/components/schemas/x402V2PaymentPayload" - /// }, - /// { - /// "$ref": "#/components/schemas/x402V1PaymentPayload" - /// } - /// ] - ///} - /// ``` - ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - #[serde(untagged)] - pub enum X402PaymentPayload { - #[serde(rename = "X402V2PaymentPayload")] - X402v2PaymentPayload(X402V2PaymentPayload), - #[serde(rename = "X402V1PaymentPayload")] - X402v1PaymentPayload(X402V1PaymentPayload), - } - impl ::std::convert::From<&Self> for X402PaymentPayload { - fn from(value: &X402PaymentPayload) -> Self { - value.clone() - } - } - impl ::std::convert::From for X402PaymentPayload { - fn from(value: X402V2PaymentPayload) -> Self { - Self::X402v2PaymentPayload(value) - } - } - impl ::std::convert::From for X402PaymentPayload { - fn from(value: X402V1PaymentPayload) -> Self { - Self::X402v1PaymentPayload(value) + impl<'de> ::serde::Deserialize<'de> for X402ExactEvmPayloadAuthorizationTo { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) } } - ///The x402 protocol payment requirements that the resource server expects the client's payment payload to meet. + ///The EIP-712 hex-encoded signature of the ERC-3009 authorization message. Smart account signatures may be longer than 65 bytes. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The x402 protocol payment requirements that the resource server expects the client's payment payload to meet.", - /// "type": "object", - /// "oneOf": [ - /// { - /// "$ref": "#/components/schemas/x402V2PaymentRequirements" - /// }, - /// { - /// "$ref": "#/components/schemas/x402V1PaymentRequirements" - /// } - /// ] + /// "description": "The EIP-712 hex-encoded signature of the ERC-3009 authorization message. Smart account signatures may be longer than 65 bytes.", + /// "examples": [ + /// "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{130,}$" ///} /// ``` ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - #[serde(untagged)] - pub enum X402PaymentRequirements { - #[serde(rename = "X402V2PaymentRequirements")] - X402v2PaymentRequirements(X402V2PaymentRequirements), - #[serde(rename = "X402V1PaymentRequirements")] - X402v1PaymentRequirements(X402V1PaymentRequirements), + #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct X402ExactEvmPayloadSignature(::std::string::String); + impl ::std::ops::Deref for X402ExactEvmPayloadSignature { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } } - impl ::std::convert::From<&Self> for X402PaymentRequirements { - fn from(value: &X402PaymentRequirements) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: X402ExactEvmPayloadSignature) -> Self { + value.0 + } + } + impl ::std::convert::From<&X402ExactEvmPayloadSignature> for X402ExactEvmPayloadSignature { + fn from(value: &X402ExactEvmPayloadSignature) -> Self { value.clone() } } - impl ::std::convert::From for X402PaymentRequirements { - fn from(value: X402V2PaymentRequirements) -> Self { - Self::X402v2PaymentRequirements(value) + impl ::std::str::FromStr for X402ExactEvmPayloadSignature { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^0x[0-9a-fA-F]{130,}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^0x[0-9a-fA-F]{130,}$\"".into()); + } + Ok(Self(value.to_string())) } } - impl ::std::convert::From for X402PaymentRequirements { - fn from(value: X402V1PaymentRequirements) -> Self { - Self::X402v1PaymentRequirements(value) + impl ::std::convert::TryFrom<&str> for X402ExactEvmPayloadSignature { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() } } - ///Describes the resource being accessed in x402 protocol. + impl ::std::convert::TryFrom<&::std::string::String> for X402ExactEvmPayloadSignature { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for X402ExactEvmPayloadSignature { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for X402ExactEvmPayloadSignature { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///The x402 protocol exact scheme payload for EVM networks using Permit2. Permit2 is a universal token approval mechanism that works with any ERC-20 token, unlike ERC-3009 which requires token-level support. /// ///
JSON schema /// /// ```json ///{ - /// "description": "Describes the resource being accessed in x402 protocol.", + /// "title": "x402ExactEvmPermit2Payload", + /// "description": "The x402 protocol exact scheme payload for EVM networks using Permit2. Permit2 is a universal token approval mechanism that works with any ERC-20 token, unlike ERC-3009 which requires token-level support.", + /// "examples": [ + /// { + /// "permit2Authorization": { + /// "deadline": "1716150000", + /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "nonce": "12345678901234567890", + /// "permitted": { + /// "amount": "1000000", + /// "token": "0x036CbD53842c5426634e7929541eC2318f3dCF7e" + /// }, + /// "spender": "0x4020615294c913F045dc10f0a5cdEbd86c280001", + /// "witness": { + /// "extra": "0x", + /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "validAfter": "1716150000" + /// } + /// }, + /// "signature": "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" + /// } + /// ], /// "type": "object", + /// "required": [ + /// "permit2Authorization", + /// "signature" + /// ], /// "properties": { - /// "description": { - /// "description": "A human-readable description of the resource.", + /// "permit2Authorization": { + /// "description": "The authorization data for the Permit2 PermitWitnessTransferFrom message.", /// "examples": [ - /// "Premium API access for data analysis" - /// ], - /// "allOf": [ /// { - /// "$ref": "#/components/schemas/Description" + /// "deadline": "1716150000", + /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "nonce": "12345678901234567890", + /// "permitted": { + /// "amount": "1000000", + /// "token": "0x036CbD53842c5426634e7929541eC2318f3dCF7e" + /// }, + /// "spender": "0x4020615294c913F045dc10f0a5cdEbd86c280001", + /// "witness": { + /// "extra": "0x", + /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "validAfter": "1716150000" + /// } /// } - /// ] - /// }, - /// "mimeType": { - /// "description": "The MIME type of the resource response.", - /// "examples": [ - /// "application/json" /// ], - /// "type": "string" + /// "type": "object", + /// "required": [ + /// "deadline", + /// "from", + /// "nonce", + /// "permitted", + /// "spender", + /// "witness" + /// ], + /// "properties": { + /// "deadline": { + /// "description": "The unix timestamp before which the permit is valid.", + /// "examples": [ + /// "1716150000" + /// ], + /// "type": "string" + /// }, + /// "from": { + /// "description": "The 0x-prefixed, checksum EVM address of the sender of the payment.", + /// "examples": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// }, + /// "nonce": { + /// "description": "The Permit2 nonce as a decimal string (uint256).", + /// "examples": [ + /// "12345678901234567890" + /// ], + /// "type": "string", + /// "pattern": "^[0-9]+$" + /// }, + /// "permitted": { + /// "description": "The token permissions for the transfer.", + /// "type": "object", + /// "required": [ + /// "amount", + /// "token" + /// ], + /// "properties": { + /// "amount": { + /// "description": "The amount to transfer in atomic units.", + /// "examples": [ + /// "1000000" + /// ], + /// "type": "string" + /// }, + /// "token": { + /// "description": "The 0x-prefixed, checksum EVM address of the token to transfer.", + /// "examples": [ + /// "0x036CbD53842c5426634e7929541eC2318f3dCF7e" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// } + /// } + /// }, + /// "spender": { + /// "description": "The 0x-prefixed, checksum EVM address of the spender (x402 Permit2 proxy contract).", + /// "examples": [ + /// "0x4020615294c913F045dc10f0a5cdEbd86c280001" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// }, + /// "witness": { + /// "description": "The witness data containing payment details.", + /// "type": "object", + /// "required": [ + /// "to", + /// "validAfter" + /// ], + /// "properties": { + /// "extra": { + /// "description": "Optional hex-encoded extra data.", + /// "examples": [ + /// "0x" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]*$" + /// }, + /// "to": { + /// "description": "The 0x-prefixed, checksum EVM address of the recipient.", + /// "examples": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// }, + /// "validAfter": { + /// "description": "The unix timestamp after which the payment is valid.", + /// "examples": [ + /// "1716150000" + /// ], + /// "type": "string" + /// } + /// } + /// } + /// } /// }, - /// "url": { - /// "description": "The URL of the resource.", + /// "signature": { + /// "description": "The EIP-712 hex-encoded signature of the Permit2 PermitWitnessTransferFrom message. Smart account signatures may be longer than 65 bytes.", /// "examples": [ - /// "https://api.example.com/premium/resource/123" + /// "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" /// ], - /// "type": "string" + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{130,}$" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402ResourceInfo { - ///A human-readable description of the resource. - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub description: ::std::option::Option, - ///The MIME type of the resource response. - #[serde( - rename = "mimeType", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub mime_type: ::std::option::Option<::std::string::String>, - ///The URL of the resource. - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub url: ::std::option::Option<::std::string::String>, + pub struct X402ExactEvmPermit2Payload { + #[serde(rename = "permit2Authorization")] + pub permit2_authorization: X402ExactEvmPermit2PayloadPermit2Authorization, + ///The EIP-712 hex-encoded signature of the Permit2 PermitWitnessTransferFrom message. Smart account signatures may be longer than 65 bytes. + pub signature: X402ExactEvmPermit2PayloadSignature, } - impl ::std::convert::From<&X402ResourceInfo> for X402ResourceInfo { - fn from(value: &X402ResourceInfo) -> Self { + impl ::std::convert::From<&X402ExactEvmPermit2Payload> for X402ExactEvmPermit2Payload { + fn from(value: &X402ExactEvmPermit2Payload) -> Self { value.clone() } } - impl ::std::default::Default for X402ResourceInfo { - fn default() -> Self { - Self { - description: Default::default(), - mime_type: Default::default(), - url: Default::default(), - } - } - } - impl X402ResourceInfo { - pub fn builder() -> builder::X402ResourceInfo { + impl X402ExactEvmPermit2Payload { + pub fn builder() -> builder::X402ExactEvmPermit2Payload { Default::default() } } - ///Quality metrics for a discovered x402 resource. + ///The authorization data for the Permit2 PermitWitnessTransferFrom message. /// ///
JSON schema /// /// ```json ///{ - /// "description": "Quality metrics for a discovered x402 resource.", + /// "description": "The authorization data for the Permit2 PermitWitnessTransferFrom message.", /// "examples": [ /// { - /// "l30DaysTotalCalls": 42, - /// "l30DaysUniquePayers": 15, - /// "lastCalledAt": "2024-01-15T10:30:00Z" + /// "deadline": "1716150000", + /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "nonce": "12345678901234567890", + /// "permitted": { + /// "amount": "1000000", + /// "token": "0x036CbD53842c5426634e7929541eC2318f3dCF7e" + /// }, + /// "spender": "0x4020615294c913F045dc10f0a5cdEbd86c280001", + /// "witness": { + /// "extra": "0x", + /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "validAfter": "1716150000" + /// } /// } /// ], /// "type": "object", + /// "required": [ + /// "deadline", + /// "from", + /// "nonce", + /// "permitted", + /// "spender", + /// "witness" + /// ], /// "properties": { - /// "l30DaysTotalCalls": { - /// "description": "Total number of paid calls to a resource in the last 30 days.", + /// "deadline": { + /// "description": "The unix timestamp before which the permit is valid.", /// "examples": [ - /// 42 + /// "1716150000" /// ], - /// "type": "integer" + /// "type": "string" /// }, - /// "l30DaysUniquePayers": { - /// "description": "Number of unique payers to a resource in the last 30 days.", + /// "from": { + /// "description": "The 0x-prefixed, checksum EVM address of the sender of the payment.", /// "examples": [ - /// 15 + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" /// ], - /// "type": "integer" + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{40}$" /// }, - /// "lastCalledAt": { - /// "description": "Timestamp of the most recent paid call to a resource.", + /// "nonce": { + /// "description": "The Permit2 nonce as a decimal string (uint256).", /// "examples": [ - /// "2024-01-15T10:30:00Z" + /// "12345678901234567890" /// ], /// "type": "string", - /// "format": "date-time" + /// "pattern": "^[0-9]+$" + /// }, + /// "permitted": { + /// "description": "The token permissions for the transfer.", + /// "type": "object", + /// "required": [ + /// "amount", + /// "token" + /// ], + /// "properties": { + /// "amount": { + /// "description": "The amount to transfer in atomic units.", + /// "examples": [ + /// "1000000" + /// ], + /// "type": "string" + /// }, + /// "token": { + /// "description": "The 0x-prefixed, checksum EVM address of the token to transfer.", + /// "examples": [ + /// "0x036CbD53842c5426634e7929541eC2318f3dCF7e" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// } + /// } + /// }, + /// "spender": { + /// "description": "The 0x-prefixed, checksum EVM address of the spender (x402 Permit2 proxy contract).", + /// "examples": [ + /// "0x4020615294c913F045dc10f0a5cdEbd86c280001" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// }, + /// "witness": { + /// "description": "The witness data containing payment details.", + /// "type": "object", + /// "required": [ + /// "to", + /// "validAfter" + /// ], + /// "properties": { + /// "extra": { + /// "description": "Optional hex-encoded extra data.", + /// "examples": [ + /// "0x" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]*$" + /// }, + /// "to": { + /// "description": "The 0x-prefixed, checksum EVM address of the recipient.", + /// "examples": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{40}$" + /// }, + /// "validAfter": { + /// "description": "The unix timestamp after which the payment is valid.", + /// "examples": [ + /// "1716150000" + /// ], + /// "type": "string" + /// } + /// } /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402ResourceQuality { - ///Total number of paid calls to a resource in the last 30 days. - #[serde( - rename = "l30DaysTotalCalls", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub l30_days_total_calls: ::std::option::Option, - ///Number of unique payers to a resource in the last 30 days. - #[serde( - rename = "l30DaysUniquePayers", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub l30_days_unique_payers: ::std::option::Option, - ///Timestamp of the most recent paid call to a resource. - #[serde( - rename = "lastCalledAt", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub last_called_at: ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + pub struct X402ExactEvmPermit2PayloadPermit2Authorization { + ///The unix timestamp before which the permit is valid. + pub deadline: ::std::string::String, + ///The 0x-prefixed, checksum EVM address of the sender of the payment. + pub from: X402ExactEvmPermit2PayloadPermit2AuthorizationFrom, + ///The Permit2 nonce as a decimal string (uint256). + pub nonce: X402ExactEvmPermit2PayloadPermit2AuthorizationNonce, + pub permitted: X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted, + ///The 0x-prefixed, checksum EVM address of the spender (x402 Permit2 proxy contract). + pub spender: X402ExactEvmPermit2PayloadPermit2AuthorizationSpender, + pub witness: X402ExactEvmPermit2PayloadPermit2AuthorizationWitness, } - impl ::std::convert::From<&X402ResourceQuality> for X402ResourceQuality { - fn from(value: &X402ResourceQuality) -> Self { + impl ::std::convert::From<&X402ExactEvmPermit2PayloadPermit2Authorization> + for X402ExactEvmPermit2PayloadPermit2Authorization + { + fn from(value: &X402ExactEvmPermit2PayloadPermit2Authorization) -> Self { value.clone() } } - impl ::std::default::Default for X402ResourceQuality { - fn default() -> Self { - Self { - l30_days_total_calls: Default::default(), - l30_days_unique_payers: Default::default(), - last_called_at: Default::default(), - } - } - } - impl X402ResourceQuality { - pub fn builder() -> builder::X402ResourceQuality { + impl X402ExactEvmPermit2PayloadPermit2Authorization { + pub fn builder() -> builder::X402ExactEvmPermit2PayloadPermit2Authorization { Default::default() } } - ///Response from a search for x402 resources. + ///The 0x-prefixed, checksum EVM address of the sender of the payment. /// ///
JSON schema /// /// ```json ///{ - /// "description": "Response from a search for x402 resources.", + /// "description": "The 0x-prefixed, checksum EVM address of the sender of the payment.", + /// "examples": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{40}$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct X402ExactEvmPermit2PayloadPermit2AuthorizationFrom(::std::string::String); + impl ::std::ops::Deref for X402ExactEvmPermit2PayloadPermit2AuthorizationFrom { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From + for ::std::string::String + { + fn from(value: X402ExactEvmPermit2PayloadPermit2AuthorizationFrom) -> Self { + value.0 + } + } + impl ::std::convert::From<&X402ExactEvmPermit2PayloadPermit2AuthorizationFrom> + for X402ExactEvmPermit2PayloadPermit2AuthorizationFrom + { + fn from(value: &X402ExactEvmPermit2PayloadPermit2AuthorizationFrom) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for X402ExactEvmPermit2PayloadPermit2AuthorizationFrom { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for X402ExactEvmPermit2PayloadPermit2AuthorizationFrom { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> + for X402ExactEvmPermit2PayloadPermit2AuthorizationFrom + { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> + for X402ExactEvmPermit2PayloadPermit2AuthorizationFrom + { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for X402ExactEvmPermit2PayloadPermit2AuthorizationFrom { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///The Permit2 nonce as a decimal string (uint256). + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The Permit2 nonce as a decimal string (uint256).", + /// "examples": [ + /// "12345678901234567890" + /// ], + /// "type": "string", + /// "pattern": "^[0-9]+$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct X402ExactEvmPermit2PayloadPermit2AuthorizationNonce(::std::string::String); + impl ::std::ops::Deref for X402ExactEvmPermit2PayloadPermit2AuthorizationNonce { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From + for ::std::string::String + { + fn from(value: X402ExactEvmPermit2PayloadPermit2AuthorizationNonce) -> Self { + value.0 + } + } + impl ::std::convert::From<&X402ExactEvmPermit2PayloadPermit2AuthorizationNonce> + for X402ExactEvmPermit2PayloadPermit2AuthorizationNonce + { + fn from(value: &X402ExactEvmPermit2PayloadPermit2AuthorizationNonce) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for X402ExactEvmPermit2PayloadPermit2AuthorizationNonce { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| ::regress::Regex::new("^[0-9]+$").unwrap()); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^[0-9]+$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for X402ExactEvmPermit2PayloadPermit2AuthorizationNonce { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> + for X402ExactEvmPermit2PayloadPermit2AuthorizationNonce + { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> + for X402ExactEvmPermit2PayloadPermit2AuthorizationNonce + { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for X402ExactEvmPermit2PayloadPermit2AuthorizationNonce { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///The token permissions for the transfer. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The token permissions for the transfer.", /// "type": "object", /// "required": [ - /// "partialResults", - /// "resources", - /// "x402Version" + /// "amount", + /// "token" /// ], /// "properties": { - /// "partialResults": { - /// "description": "Indicates whether the result set was truncated because there were more results than the requested limit.", - /// "examples": [ - /// false - /// ], - /// "type": "boolean" - /// }, - /// "resources": { - /// "description": "List of x402 resources matching the search query and filters.", + /// "amount": { + /// "description": "The amount to transfer in atomic units.", /// "examples": [ - /// [] + /// "1000000" /// ], - /// "type": "array", - /// "items": { - /// "$ref": "#/components/schemas/x402DiscoveryResource" - /// } + /// "type": "string" /// }, - /// "searchMethod": { - /// "description": "The search method used to retrieve the results (e.g., \"text\" or \"vector\").", + /// "token": { + /// "description": "The 0x-prefixed, checksum EVM address of the token to transfer.", /// "examples": [ - /// "text" + /// "0x036CbD53842c5426634e7929541eC2318f3dCF7e" /// ], /// "type": "string", - /// "enum": [ - /// "text", - /// "vector" - /// ] - /// }, - /// "x402Version": { - /// "$ref": "#/components/schemas/X402Version" + /// "pattern": "^0x[0-9a-fA-F]{40}$" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402SearchResourcesResponse { - ///Indicates whether the result set was truncated because there were more results than the requested limit. - #[serde(rename = "partialResults")] - pub partial_results: bool, - ///List of x402 resources matching the search query and filters. - pub resources: ::std::vec::Vec, - ///The search method used to retrieve the results (e.g., "text" or "vector"). - #[serde( - rename = "searchMethod", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub search_method: ::std::option::Option, - #[serde(rename = "x402Version")] - pub x402_version: X402Version, + pub struct X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted { + ///The amount to transfer in atomic units. + pub amount: ::std::string::String, + ///The 0x-prefixed, checksum EVM address of the token to transfer. + pub token: X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken, } - impl ::std::convert::From<&X402SearchResourcesResponse> for X402SearchResourcesResponse { - fn from(value: &X402SearchResourcesResponse) -> Self { + impl ::std::convert::From<&X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted> + for X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted + { + fn from(value: &X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted) -> Self { value.clone() } } - impl X402SearchResourcesResponse { - pub fn builder() -> builder::X402SearchResourcesResponse { + impl X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted { + pub fn builder() -> builder::X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted { Default::default() } } - ///The search method used to retrieve the results (e.g., "text" or "vector"). + ///The 0x-prefixed, checksum EVM address of the token to transfer. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The search method used to retrieve the results (e.g., \"text\" or \"vector\").", + /// "description": "The 0x-prefixed, checksum EVM address of the token to transfer.", /// "examples": [ - /// "text" + /// "0x036CbD53842c5426634e7929541eC2318f3dCF7e" /// ], /// "type": "string", - /// "enum": [ - /// "text", - /// "vector" - /// ] + /// "pattern": "^0x[0-9a-fA-F]{40}$" ///} /// ``` ///
- #[derive( - ::serde::Deserialize, - ::serde::Serialize, - Clone, - Copy, - Debug, - Eq, - Hash, - Ord, - PartialEq, - PartialOrd, - )] - pub enum X402SearchResourcesResponseSearchMethod { - #[serde(rename = "text")] - Text, - #[serde(rename = "vector")] - Vector, + #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken(::std::string::String); + impl ::std::ops::Deref for X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } } - impl ::std::convert::From<&Self> for X402SearchResourcesResponseSearchMethod { - fn from(value: &X402SearchResourcesResponseSearchMethod) -> Self { - value.clone() + impl ::std::convert::From + for ::std::string::String + { + fn from(value: X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken) -> Self { + value.0 } } - impl ::std::fmt::Display for X402SearchResourcesResponseSearchMethod { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - match *self { - Self::Text => f.write_str("text"), - Self::Vector => f.write_str("vector"), - } + impl ::std::convert::From<&X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken> + for X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken + { + fn from(value: &X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken) -> Self { + value.clone() } } - impl ::std::str::FromStr for X402SearchResourcesResponseSearchMethod { + impl ::std::str::FromStr for X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - match value { - "text" => Ok(Self::Text), - "vector" => Ok(Self::Vector), - _ => Err("invalid value".into()), + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); } + Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for X402SearchResourcesResponseSearchMethod { + impl ::std::convert::TryFrom<&str> + for X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken + { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for X402SearchResourcesResponseSearchMethod { + impl ::std::convert::TryFrom<&::std::string::String> + for X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken + { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -58098,7 +64334,9 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for X402SearchResourcesResponseSearchMethod { + impl ::std::convert::TryFrom<::std::string::String> + for X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken + { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -58106,532 +64344,80 @@ pub mod types { value.parse() } } - ///The reason the payment settlement errored on the x402 protocol. + impl<'de> ::serde::Deserialize<'de> + for X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken + { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///The 0x-prefixed, checksum EVM address of the spender (x402 Permit2 proxy contract). /// ///
JSON schema /// /// ```json ///{ - /// "description": "The reason the payment settlement errored on the x402 protocol.", + /// "description": "The 0x-prefixed, checksum EVM address of the spender (x402 Permit2 proxy contract).", /// "examples": [ - /// "insufficient_funds" + /// "0x4020615294c913F045dc10f0a5cdEbd86c280001" /// ], /// "type": "string", - /// "enum": [ - /// "insufficient_funds", - /// "invalid_scheme", - /// "invalid_network", - /// "invalid_x402_version", - /// "invalid_payment_requirements", - /// "invalid_payload", - /// "invalid_exact_evm_payload_authorization_value", - /// "invalid_exact_evm_payload_authorization_value_too_low", - /// "invalid_exact_evm_payload_authorization_valid_after", - /// "invalid_exact_evm_payload_authorization_valid_before", - /// "invalid_exact_evm_payload_authorization_typed_data_message", - /// "invalid_exact_evm_payload_authorization_from_address_kyt", - /// "invalid_exact_evm_payload_authorization_to_address_kyt", - /// "invalid_exact_evm_payload_signature", - /// "invalid_exact_evm_payload_signature_address", - /// "invalid_exact_evm_permit2_payload_allowance_required", - /// "invalid_exact_evm_permit2_payload_signature", - /// "invalid_exact_evm_permit2_payload_deadline", - /// "invalid_exact_evm_permit2_payload_valid_after", - /// "invalid_exact_evm_permit2_payload_spender", - /// "invalid_exact_evm_permit2_payload_recipient", - /// "invalid_exact_evm_permit2_payload_amount", - /// "invalid_exact_svm_payload_transaction", - /// "invalid_exact_svm_payload_transaction_amount_mismatch", - /// "invalid_exact_svm_payload_transaction_create_ata_instruction", - /// "invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_payee", - /// "invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_asset", - /// "invalid_exact_svm_payload_transaction_instructions", - /// "invalid_exact_svm_payload_transaction_instructions_length", - /// "invalid_exact_svm_payload_transaction_instructions_compute_limit_instruction", - /// "invalid_exact_svm_payload_transaction_instructions_compute_price_instruction", - /// "invalid_exact_svm_payload_transaction_instructions_compute_price_instruction_too_high", - /// "invalid_exact_svm_payload_transaction_instruction_not_spl_token_transfer_checked", - /// "invalid_exact_svm_payload_transaction_instruction_not_token_2022_transfer_checked", - /// "invalid_exact_svm_payload_transaction_not_a_transfer_instruction", - /// "invalid_exact_svm_payload_transaction_cannot_derive_receiver_ata", - /// "invalid_exact_svm_payload_transaction_receiver_ata_not_found", - /// "invalid_exact_svm_payload_transaction_sender_ata_not_found", - /// "invalid_exact_svm_payload_transaction_simulation_failed", - /// "invalid_exact_svm_payload_transaction_transfer_to_incorrect_ata", - /// "invalid_exact_svm_payload_transaction_fee_payer_included_in_instruction_accounts", - /// "invalid_exact_svm_payload_transaction_fee_payer_transferring_funds", - /// "settle_exact_evm_transaction_confirmation_timed_out", - /// "settle_exact_node_failure", - /// "settle_exact_failed_onchain", - /// "settle_exact_svm_block_height_exceeded", - /// "settle_exact_svm_transaction_confirmation_timed_out", - /// "unknown_error" - /// ] + /// "pattern": "^0x[0-9a-fA-F]{40}$" ///} /// ``` ///
- #[derive( - ::serde::Deserialize, - ::serde::Serialize, - Clone, - Copy, - Debug, - Eq, - Hash, - Ord, - PartialEq, - PartialOrd, - )] - pub enum X402SettleErrorReason { - #[serde(rename = "insufficient_funds")] - InsufficientFunds, - #[serde(rename = "invalid_scheme")] - InvalidScheme, - #[serde(rename = "invalid_network")] - InvalidNetwork, - #[serde(rename = "invalid_x402_version")] - InvalidX402Version, - #[serde(rename = "invalid_payment_requirements")] - InvalidPaymentRequirements, - #[serde(rename = "invalid_payload")] - InvalidPayload, - #[serde(rename = "invalid_exact_evm_payload_authorization_value")] - InvalidExactEvmPayloadAuthorizationValue, - #[serde(rename = "invalid_exact_evm_payload_authorization_value_too_low")] - InvalidExactEvmPayloadAuthorizationValueTooLow, - #[serde(rename = "invalid_exact_evm_payload_authorization_valid_after")] - InvalidExactEvmPayloadAuthorizationValidAfter, - #[serde(rename = "invalid_exact_evm_payload_authorization_valid_before")] - InvalidExactEvmPayloadAuthorizationValidBefore, - #[serde(rename = "invalid_exact_evm_payload_authorization_typed_data_message")] - InvalidExactEvmPayloadAuthorizationTypedDataMessage, - #[serde(rename = "invalid_exact_evm_payload_authorization_from_address_kyt")] - InvalidExactEvmPayloadAuthorizationFromAddressKyt, - #[serde(rename = "invalid_exact_evm_payload_authorization_to_address_kyt")] - InvalidExactEvmPayloadAuthorizationToAddressKyt, - #[serde(rename = "invalid_exact_evm_payload_signature")] - InvalidExactEvmPayloadSignature, - #[serde(rename = "invalid_exact_evm_payload_signature_address")] - InvalidExactEvmPayloadSignatureAddress, - #[serde(rename = "invalid_exact_evm_permit2_payload_allowance_required")] - InvalidExactEvmPermit2PayloadAllowanceRequired, - #[serde(rename = "invalid_exact_evm_permit2_payload_signature")] - InvalidExactEvmPermit2PayloadSignature, - #[serde(rename = "invalid_exact_evm_permit2_payload_deadline")] - InvalidExactEvmPermit2PayloadDeadline, - #[serde(rename = "invalid_exact_evm_permit2_payload_valid_after")] - InvalidExactEvmPermit2PayloadValidAfter, - #[serde(rename = "invalid_exact_evm_permit2_payload_spender")] - InvalidExactEvmPermit2PayloadSpender, - #[serde(rename = "invalid_exact_evm_permit2_payload_recipient")] - InvalidExactEvmPermit2PayloadRecipient, - #[serde(rename = "invalid_exact_evm_permit2_payload_amount")] - InvalidExactEvmPermit2PayloadAmount, - #[serde(rename = "invalid_exact_svm_payload_transaction")] - InvalidExactSvmPayloadTransaction, - #[serde(rename = "invalid_exact_svm_payload_transaction_amount_mismatch")] - InvalidExactSvmPayloadTransactionAmountMismatch, - #[serde(rename = "invalid_exact_svm_payload_transaction_create_ata_instruction")] - InvalidExactSvmPayloadTransactionCreateAtaInstruction, - #[serde( - rename = "invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_payee" - )] - InvalidExactSvmPayloadTransactionCreateAtaInstructionIncorrectPayee, - #[serde( - rename = "invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_asset" - )] - InvalidExactSvmPayloadTransactionCreateAtaInstructionIncorrectAsset, - #[serde(rename = "invalid_exact_svm_payload_transaction_instructions")] - InvalidExactSvmPayloadTransactionInstructions, - #[serde(rename = "invalid_exact_svm_payload_transaction_instructions_length")] - InvalidExactSvmPayloadTransactionInstructionsLength, - #[serde( - rename = "invalid_exact_svm_payload_transaction_instructions_compute_limit_instruction" - )] - InvalidExactSvmPayloadTransactionInstructionsComputeLimitInstruction, - #[serde( - rename = "invalid_exact_svm_payload_transaction_instructions_compute_price_instruction" - )] - InvalidExactSvmPayloadTransactionInstructionsComputePriceInstruction, - #[serde( - rename = "invalid_exact_svm_payload_transaction_instructions_compute_price_instruction_too_high" - )] - InvalidExactSvmPayloadTransactionInstructionsComputePriceInstructionTooHigh, - #[serde( - rename = "invalid_exact_svm_payload_transaction_instruction_not_spl_token_transfer_checked" - )] - InvalidExactSvmPayloadTransactionInstructionNotSplTokenTransferChecked, - #[serde( - rename = "invalid_exact_svm_payload_transaction_instruction_not_token_2022_transfer_checked" - )] - InvalidExactSvmPayloadTransactionInstructionNotToken2022TransferChecked, - #[serde(rename = "invalid_exact_svm_payload_transaction_not_a_transfer_instruction")] - InvalidExactSvmPayloadTransactionNotATransferInstruction, - #[serde(rename = "invalid_exact_svm_payload_transaction_cannot_derive_receiver_ata")] - InvalidExactSvmPayloadTransactionCannotDeriveReceiverAta, - #[serde(rename = "invalid_exact_svm_payload_transaction_receiver_ata_not_found")] - InvalidExactSvmPayloadTransactionReceiverAtaNotFound, - #[serde(rename = "invalid_exact_svm_payload_transaction_sender_ata_not_found")] - InvalidExactSvmPayloadTransactionSenderAtaNotFound, - #[serde(rename = "invalid_exact_svm_payload_transaction_simulation_failed")] - InvalidExactSvmPayloadTransactionSimulationFailed, - #[serde(rename = "invalid_exact_svm_payload_transaction_transfer_to_incorrect_ata")] - InvalidExactSvmPayloadTransactionTransferToIncorrectAta, - #[serde( - rename = "invalid_exact_svm_payload_transaction_fee_payer_included_in_instruction_accounts" - )] - InvalidExactSvmPayloadTransactionFeePayerIncludedInInstructionAccounts, - #[serde(rename = "invalid_exact_svm_payload_transaction_fee_payer_transferring_funds")] - InvalidExactSvmPayloadTransactionFeePayerTransferringFunds, - #[serde(rename = "settle_exact_evm_transaction_confirmation_timed_out")] - SettleExactEvmTransactionConfirmationTimedOut, - #[serde(rename = "settle_exact_node_failure")] - SettleExactNodeFailure, - #[serde(rename = "settle_exact_failed_onchain")] - SettleExactFailedOnchain, - #[serde(rename = "settle_exact_svm_block_height_exceeded")] - SettleExactSvmBlockHeightExceeded, - #[serde(rename = "settle_exact_svm_transaction_confirmation_timed_out")] - SettleExactSvmTransactionConfirmationTimedOut, - #[serde(rename = "unknown_error")] - UnknownError, + #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct X402ExactEvmPermit2PayloadPermit2AuthorizationSpender(::std::string::String); + impl ::std::ops::Deref for X402ExactEvmPermit2PayloadPermit2AuthorizationSpender { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } } - impl ::std::convert::From<&Self> for X402SettleErrorReason { - fn from(value: &X402SettleErrorReason) -> Self { - value.clone() + impl ::std::convert::From + for ::std::string::String + { + fn from(value: X402ExactEvmPermit2PayloadPermit2AuthorizationSpender) -> Self { + value.0 } } - impl ::std::fmt::Display for X402SettleErrorReason { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - match *self { - Self::InsufficientFunds => f.write_str("insufficient_funds"), - Self::InvalidScheme => f.write_str("invalid_scheme"), - Self::InvalidNetwork => f.write_str("invalid_network"), - Self::InvalidX402Version => f.write_str("invalid_x402_version"), - Self::InvalidPaymentRequirements => { - f.write_str("invalid_payment_requirements") - } - Self::InvalidPayload => f.write_str("invalid_payload"), - Self::InvalidExactEvmPayloadAuthorizationValue => { - f.write_str("invalid_exact_evm_payload_authorization_value") - } - Self::InvalidExactEvmPayloadAuthorizationValueTooLow => { - f.write_str("invalid_exact_evm_payload_authorization_value_too_low") - } - Self::InvalidExactEvmPayloadAuthorizationValidAfter => { - f.write_str("invalid_exact_evm_payload_authorization_valid_after") - } - Self::InvalidExactEvmPayloadAuthorizationValidBefore => { - f.write_str("invalid_exact_evm_payload_authorization_valid_before") - } - Self::InvalidExactEvmPayloadAuthorizationTypedDataMessage => { - f.write_str( - "invalid_exact_evm_payload_authorization_typed_data_message", - ) - } - Self::InvalidExactEvmPayloadAuthorizationFromAddressKyt => { - f.write_str( - "invalid_exact_evm_payload_authorization_from_address_kyt", - ) - } - Self::InvalidExactEvmPayloadAuthorizationToAddressKyt => { - f.write_str("invalid_exact_evm_payload_authorization_to_address_kyt") - } - Self::InvalidExactEvmPayloadSignature => { - f.write_str("invalid_exact_evm_payload_signature") - } - Self::InvalidExactEvmPayloadSignatureAddress => { - f.write_str("invalid_exact_evm_payload_signature_address") - } - Self::InvalidExactEvmPermit2PayloadAllowanceRequired => { - f.write_str("invalid_exact_evm_permit2_payload_allowance_required") - } - Self::InvalidExactEvmPermit2PayloadSignature => { - f.write_str("invalid_exact_evm_permit2_payload_signature") - } - Self::InvalidExactEvmPermit2PayloadDeadline => { - f.write_str("invalid_exact_evm_permit2_payload_deadline") - } - Self::InvalidExactEvmPermit2PayloadValidAfter => { - f.write_str("invalid_exact_evm_permit2_payload_valid_after") - } - Self::InvalidExactEvmPermit2PayloadSpender => { - f.write_str("invalid_exact_evm_permit2_payload_spender") - } - Self::InvalidExactEvmPermit2PayloadRecipient => { - f.write_str("invalid_exact_evm_permit2_payload_recipient") - } - Self::InvalidExactEvmPermit2PayloadAmount => { - f.write_str("invalid_exact_evm_permit2_payload_amount") - } - Self::InvalidExactSvmPayloadTransaction => { - f.write_str("invalid_exact_svm_payload_transaction") - } - Self::InvalidExactSvmPayloadTransactionAmountMismatch => { - f.write_str("invalid_exact_svm_payload_transaction_amount_mismatch") - } - Self::InvalidExactSvmPayloadTransactionCreateAtaInstruction => { - f.write_str( - "invalid_exact_svm_payload_transaction_create_ata_instruction", - ) - } - Self::InvalidExactSvmPayloadTransactionCreateAtaInstructionIncorrectPayee => { - f.write_str( - "invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_payee", - ) - } - Self::InvalidExactSvmPayloadTransactionCreateAtaInstructionIncorrectAsset => { - f.write_str( - "invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_asset", - ) - } - Self::InvalidExactSvmPayloadTransactionInstructions => { - f.write_str("invalid_exact_svm_payload_transaction_instructions") - } - Self::InvalidExactSvmPayloadTransactionInstructionsLength => { - f.write_str( - "invalid_exact_svm_payload_transaction_instructions_length", - ) - } - Self::InvalidExactSvmPayloadTransactionInstructionsComputeLimitInstruction => { - f.write_str( - "invalid_exact_svm_payload_transaction_instructions_compute_limit_instruction", - ) - } - Self::InvalidExactSvmPayloadTransactionInstructionsComputePriceInstruction => { - f.write_str( - "invalid_exact_svm_payload_transaction_instructions_compute_price_instruction", - ) - } - Self::InvalidExactSvmPayloadTransactionInstructionsComputePriceInstructionTooHigh => { - f.write_str( - "invalid_exact_svm_payload_transaction_instructions_compute_price_instruction_too_high", - ) - } - Self::InvalidExactSvmPayloadTransactionInstructionNotSplTokenTransferChecked => { - f.write_str( - "invalid_exact_svm_payload_transaction_instruction_not_spl_token_transfer_checked", - ) - } - Self::InvalidExactSvmPayloadTransactionInstructionNotToken2022TransferChecked => { - f.write_str( - "invalid_exact_svm_payload_transaction_instruction_not_token_2022_transfer_checked", - ) - } - Self::InvalidExactSvmPayloadTransactionNotATransferInstruction => { - f.write_str( - "invalid_exact_svm_payload_transaction_not_a_transfer_instruction", - ) - } - Self::InvalidExactSvmPayloadTransactionCannotDeriveReceiverAta => { - f.write_str( - "invalid_exact_svm_payload_transaction_cannot_derive_receiver_ata", - ) - } - Self::InvalidExactSvmPayloadTransactionReceiverAtaNotFound => { - f.write_str( - "invalid_exact_svm_payload_transaction_receiver_ata_not_found", - ) - } - Self::InvalidExactSvmPayloadTransactionSenderAtaNotFound => { - f.write_str( - "invalid_exact_svm_payload_transaction_sender_ata_not_found", - ) - } - Self::InvalidExactSvmPayloadTransactionSimulationFailed => { - f.write_str( - "invalid_exact_svm_payload_transaction_simulation_failed", - ) - } - Self::InvalidExactSvmPayloadTransactionTransferToIncorrectAta => { - f.write_str( - "invalid_exact_svm_payload_transaction_transfer_to_incorrect_ata", - ) - } - Self::InvalidExactSvmPayloadTransactionFeePayerIncludedInInstructionAccounts => { - f.write_str( - "invalid_exact_svm_payload_transaction_fee_payer_included_in_instruction_accounts", - ) - } - Self::InvalidExactSvmPayloadTransactionFeePayerTransferringFunds => { - f.write_str( - "invalid_exact_svm_payload_transaction_fee_payer_transferring_funds", - ) - } - Self::SettleExactEvmTransactionConfirmationTimedOut => { - f.write_str("settle_exact_evm_transaction_confirmation_timed_out") - } - Self::SettleExactNodeFailure => f.write_str("settle_exact_node_failure"), - Self::SettleExactFailedOnchain => { - f.write_str("settle_exact_failed_onchain") - } - Self::SettleExactSvmBlockHeightExceeded => { - f.write_str("settle_exact_svm_block_height_exceeded") - } - Self::SettleExactSvmTransactionConfirmationTimedOut => { - f.write_str("settle_exact_svm_transaction_confirmation_timed_out") - } - Self::UnknownError => f.write_str("unknown_error"), - } + impl ::std::convert::From<&X402ExactEvmPermit2PayloadPermit2AuthorizationSpender> + for X402ExactEvmPermit2PayloadPermit2AuthorizationSpender + { + fn from(value: &X402ExactEvmPermit2PayloadPermit2AuthorizationSpender) -> Self { + value.clone() } } - impl ::std::str::FromStr for X402SettleErrorReason { + impl ::std::str::FromStr for X402ExactEvmPermit2PayloadPermit2AuthorizationSpender { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { - match value { - "insufficient_funds" => Ok(Self::InsufficientFunds), - "invalid_scheme" => Ok(Self::InvalidScheme), - "invalid_network" => Ok(Self::InvalidNetwork), - "invalid_x402_version" => Ok(Self::InvalidX402Version), - "invalid_payment_requirements" => Ok(Self::InvalidPaymentRequirements), - "invalid_payload" => Ok(Self::InvalidPayload), - "invalid_exact_evm_payload_authorization_value" => { - Ok(Self::InvalidExactEvmPayloadAuthorizationValue) - } - "invalid_exact_evm_payload_authorization_value_too_low" => { - Ok(Self::InvalidExactEvmPayloadAuthorizationValueTooLow) - } - "invalid_exact_evm_payload_authorization_valid_after" => { - Ok(Self::InvalidExactEvmPayloadAuthorizationValidAfter) - } - "invalid_exact_evm_payload_authorization_valid_before" => { - Ok(Self::InvalidExactEvmPayloadAuthorizationValidBefore) - } - "invalid_exact_evm_payload_authorization_typed_data_message" => { - Ok(Self::InvalidExactEvmPayloadAuthorizationTypedDataMessage) - } - "invalid_exact_evm_payload_authorization_from_address_kyt" => { - Ok(Self::InvalidExactEvmPayloadAuthorizationFromAddressKyt) - } - "invalid_exact_evm_payload_authorization_to_address_kyt" => { - Ok(Self::InvalidExactEvmPayloadAuthorizationToAddressKyt) - } - "invalid_exact_evm_payload_signature" => { - Ok(Self::InvalidExactEvmPayloadSignature) - } - "invalid_exact_evm_payload_signature_address" => { - Ok(Self::InvalidExactEvmPayloadSignatureAddress) - } - "invalid_exact_evm_permit2_payload_allowance_required" => { - Ok(Self::InvalidExactEvmPermit2PayloadAllowanceRequired) - } - "invalid_exact_evm_permit2_payload_signature" => { - Ok(Self::InvalidExactEvmPermit2PayloadSignature) - } - "invalid_exact_evm_permit2_payload_deadline" => { - Ok(Self::InvalidExactEvmPermit2PayloadDeadline) - } - "invalid_exact_evm_permit2_payload_valid_after" => { - Ok(Self::InvalidExactEvmPermit2PayloadValidAfter) - } - "invalid_exact_evm_permit2_payload_spender" => { - Ok(Self::InvalidExactEvmPermit2PayloadSpender) - } - "invalid_exact_evm_permit2_payload_recipient" => { - Ok(Self::InvalidExactEvmPermit2PayloadRecipient) - } - "invalid_exact_evm_permit2_payload_amount" => { - Ok(Self::InvalidExactEvmPermit2PayloadAmount) - } - "invalid_exact_svm_payload_transaction" => { - Ok(Self::InvalidExactSvmPayloadTransaction) - } - "invalid_exact_svm_payload_transaction_amount_mismatch" => { - Ok(Self::InvalidExactSvmPayloadTransactionAmountMismatch) - } - "invalid_exact_svm_payload_transaction_create_ata_instruction" => { - Ok(Self::InvalidExactSvmPayloadTransactionCreateAtaInstruction) - } - "invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_payee" => { - Ok( - Self::InvalidExactSvmPayloadTransactionCreateAtaInstructionIncorrectPayee, - ) - } - "invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_asset" => { - Ok( - Self::InvalidExactSvmPayloadTransactionCreateAtaInstructionIncorrectAsset, - ) - } - "invalid_exact_svm_payload_transaction_instructions" => { - Ok(Self::InvalidExactSvmPayloadTransactionInstructions) - } - "invalid_exact_svm_payload_transaction_instructions_length" => { - Ok(Self::InvalidExactSvmPayloadTransactionInstructionsLength) - } - "invalid_exact_svm_payload_transaction_instructions_compute_limit_instruction" => { - Ok( - Self::InvalidExactSvmPayloadTransactionInstructionsComputeLimitInstruction, - ) - } - "invalid_exact_svm_payload_transaction_instructions_compute_price_instruction" => { - Ok( - Self::InvalidExactSvmPayloadTransactionInstructionsComputePriceInstruction, - ) - } - "invalid_exact_svm_payload_transaction_instructions_compute_price_instruction_too_high" => { - Ok( - Self::InvalidExactSvmPayloadTransactionInstructionsComputePriceInstructionTooHigh, - ) - } - "invalid_exact_svm_payload_transaction_instruction_not_spl_token_transfer_checked" => { - Ok( - Self::InvalidExactSvmPayloadTransactionInstructionNotSplTokenTransferChecked, - ) - } - "invalid_exact_svm_payload_transaction_instruction_not_token_2022_transfer_checked" => { - Ok( - Self::InvalidExactSvmPayloadTransactionInstructionNotToken2022TransferChecked, - ) - } - "invalid_exact_svm_payload_transaction_not_a_transfer_instruction" => { - Ok(Self::InvalidExactSvmPayloadTransactionNotATransferInstruction) - } - "invalid_exact_svm_payload_transaction_cannot_derive_receiver_ata" => { - Ok(Self::InvalidExactSvmPayloadTransactionCannotDeriveReceiverAta) - } - "invalid_exact_svm_payload_transaction_receiver_ata_not_found" => { - Ok(Self::InvalidExactSvmPayloadTransactionReceiverAtaNotFound) - } - "invalid_exact_svm_payload_transaction_sender_ata_not_found" => { - Ok(Self::InvalidExactSvmPayloadTransactionSenderAtaNotFound) - } - "invalid_exact_svm_payload_transaction_simulation_failed" => { - Ok(Self::InvalidExactSvmPayloadTransactionSimulationFailed) - } - "invalid_exact_svm_payload_transaction_transfer_to_incorrect_ata" => { - Ok(Self::InvalidExactSvmPayloadTransactionTransferToIncorrectAta) - } - "invalid_exact_svm_payload_transaction_fee_payer_included_in_instruction_accounts" => { - Ok( - Self::InvalidExactSvmPayloadTransactionFeePayerIncludedInInstructionAccounts, - ) - } - "invalid_exact_svm_payload_transaction_fee_payer_transferring_funds" => { - Ok(Self::InvalidExactSvmPayloadTransactionFeePayerTransferringFunds) - } - "settle_exact_evm_transaction_confirmation_timed_out" => { - Ok(Self::SettleExactEvmTransactionConfirmationTimedOut) - } - "settle_exact_node_failure" => Ok(Self::SettleExactNodeFailure), - "settle_exact_failed_onchain" => Ok(Self::SettleExactFailedOnchain), - "settle_exact_svm_block_height_exceeded" => { - Ok(Self::SettleExactSvmBlockHeightExceeded) - } - "settle_exact_svm_transaction_confirmation_timed_out" => { - Ok(Self::SettleExactSvmTransactionConfirmationTimedOut) - } - "unknown_error" => Ok(Self::UnknownError), - _ => Err("invalid value".into()), + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); } + Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for X402SettleErrorReason { + impl ::std::convert::TryFrom<&str> for X402ExactEvmPermit2PayloadPermit2AuthorizationSpender { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for X402SettleErrorReason { + impl ::std::convert::TryFrom<&::std::string::String> + for X402ExactEvmPermit2PayloadPermit2AuthorizationSpender + { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -58639,7 +64425,9 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for X402SettleErrorReason { + impl ::std::convert::TryFrom<::std::string::String> + for X402ExactEvmPermit2PayloadPermit2AuthorizationSpender + { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -58647,171 +64435,140 @@ pub mod types { value.parse() } } - ///The result when x402 payment settlement fails. + impl<'de> ::serde::Deserialize<'de> for X402ExactEvmPermit2PayloadPermit2AuthorizationSpender { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///The witness data containing payment details. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The result when x402 payment settlement fails.", - /// "examples": [ - /// { - /// "errorReason": "insufficient_funds", - /// "payer": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "success": false - /// } - /// ], + /// "description": "The witness data containing payment details.", /// "type": "object", /// "required": [ - /// "errorReason", - /// "success" + /// "to", + /// "validAfter" /// ], /// "properties": { - /// "errorMessage": { - /// "description": "The message describing the error reason.", - /// "examples": [ - /// "Insufficient funds" - /// ], - /// "type": "string" - /// }, - /// "errorReason": { - /// "$ref": "#/components/schemas/x402SettleErrorReason" - /// }, - /// "network": { - /// "description": "The network where the settlement occurred.", + /// "extra": { + /// "description": "Optional hex-encoded extra data.", /// "examples": [ - /// "base" + /// "0x" /// ], - /// "type": "string" + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]*$" /// }, - /// "payer": { - /// "description": "The onchain address of the client that is paying for the resource.\n\nFor EVM networks, the payer will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, the payer will be a base58-encoded Solana address.", + /// "to": { + /// "description": "The 0x-prefixed, checksum EVM address of the recipient.", /// "examples": [ /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" /// ], /// "type": "string", - /// "pattern": "^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$" - /// }, - /// "success": { - /// "description": "Indicates whether the payment settlement is successful.", - /// "examples": [ - /// false - /// ], - /// "type": "boolean" + /// "pattern": "^0x[0-9a-fA-F]{40}$" /// }, - /// "transaction": { - /// "description": "The transaction of the settlement.\nFor EVM networks, the transaction will be a 0x-prefixed, EVM transaction hash.\nFor Solana-based networks, the transaction will be a base58-encoded Solana signature.", + /// "validAfter": { + /// "description": "The unix timestamp after which the payment is valid.", /// "examples": [ - /// "0x89c91c789e57059b17285e7ba1716a1f5ff4c5dace0ea5a5135f26158d0421b9" + /// "1716150000" /// ], - /// "type": "string", - /// "pattern": "^(0x[a-fA-F0-9]{64}|[1-9A-HJ-NP-Za-km-z]{87,88})$" + /// "type": "string" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402SettlePaymentRejection { - ///The message describing the error reason. - #[serde( - rename = "errorMessage", - default, - skip_serializing_if = "::std::option::Option::is_none" - )] - pub error_message: ::std::option::Option<::std::string::String>, - #[serde(rename = "errorReason")] - pub error_reason: X402SettleErrorReason, - ///The network where the settlement occurred. - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub network: ::std::option::Option<::std::string::String>, - /**The onchain address of the client that is paying for the resource. - - For EVM networks, the payer will be a 0x-prefixed, checksum EVM address. - - For Solana-based networks, the payer will be a base58-encoded Solana address.*/ - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub payer: ::std::option::Option, - ///Indicates whether the payment settlement is successful. - pub success: bool, - /**The transaction of the settlement. - For EVM networks, the transaction will be a 0x-prefixed, EVM transaction hash. - For Solana-based networks, the transaction will be a base58-encoded Solana signature.*/ + pub struct X402ExactEvmPermit2PayloadPermit2AuthorizationWitness { + ///Optional hex-encoded extra data. #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub transaction: ::std::option::Option, + pub extra: + ::std::option::Option, + ///The 0x-prefixed, checksum EVM address of the recipient. + pub to: X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo, + ///The unix timestamp after which the payment is valid. + #[serde(rename = "validAfter")] + pub valid_after: ::std::string::String, } - impl ::std::convert::From<&X402SettlePaymentRejection> for X402SettlePaymentRejection { - fn from(value: &X402SettlePaymentRejection) -> Self { + impl ::std::convert::From<&X402ExactEvmPermit2PayloadPermit2AuthorizationWitness> + for X402ExactEvmPermit2PayloadPermit2AuthorizationWitness + { + fn from(value: &X402ExactEvmPermit2PayloadPermit2AuthorizationWitness) -> Self { value.clone() } } - impl X402SettlePaymentRejection { - pub fn builder() -> builder::X402SettlePaymentRejection { + impl X402ExactEvmPermit2PayloadPermit2AuthorizationWitness { + pub fn builder() -> builder::X402ExactEvmPermit2PayloadPermit2AuthorizationWitness { Default::default() } } - /**The onchain address of the client that is paying for the resource. - - For EVM networks, the payer will be a 0x-prefixed, checksum EVM address. - - For Solana-based networks, the payer will be a base58-encoded Solana address.*/ + ///Optional hex-encoded extra data. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The onchain address of the client that is paying for the resource.\n\nFor EVM networks, the payer will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, the payer will be a base58-encoded Solana address.", + /// "description": "Optional hex-encoded extra data.", /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// "0x" /// ], /// "type": "string", - /// "pattern": "^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$" + /// "pattern": "^0x[0-9a-fA-F]*$" ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct X402SettlePaymentRejectionPayer(::std::string::String); - impl ::std::ops::Deref for X402SettlePaymentRejectionPayer { + pub struct X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra(::std::string::String); + impl ::std::ops::Deref for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: X402SettlePaymentRejectionPayer) -> Self { + impl ::std::convert::From + for ::std::string::String + { + fn from(value: X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra) -> Self { value.0 } } - impl ::std::convert::From<&X402SettlePaymentRejectionPayer> for X402SettlePaymentRejectionPayer { - fn from(value: &X402SettlePaymentRejectionPayer) -> Self { + impl ::std::convert::From<&X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra> + for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra + { + fn from(value: &X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra) -> Self { value.clone() } } - impl ::std::str::FromStr for X402SettlePaymentRejectionPayer { + impl ::std::str::FromStr for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$") - .unwrap() - }); + ::std::sync::LazyLock::new(|| ::regress::Regex::new("^0x[0-9a-fA-F]*$").unwrap()); if PATTERN.find(value).is_none() { - return Err( - "doesn't match pattern \"^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$\"" - .into(), - ); + return Err("doesn't match pattern \"^0x[0-9a-fA-F]*$\"".into()); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for X402SettlePaymentRejectionPayer { + impl ::std::convert::TryFrom<&str> for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for X402SettlePaymentRejectionPayer { + impl ::std::convert::TryFrom<&::std::string::String> + for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra + { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -58819,7 +64576,9 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for X402SettlePaymentRejectionPayer { + impl ::std::convert::TryFrom<::std::string::String> + for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra + { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -58827,7 +64586,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for X402SettlePaymentRejectionPayer { + impl<'de> ::serde::Deserialize<'de> for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -58839,68 +64598,66 @@ pub mod types { }) } } - /**The transaction of the settlement. - For EVM networks, the transaction will be a 0x-prefixed, EVM transaction hash. - For Solana-based networks, the transaction will be a base58-encoded Solana signature.*/ + ///The 0x-prefixed, checksum EVM address of the recipient. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The transaction of the settlement.\nFor EVM networks, the transaction will be a 0x-prefixed, EVM transaction hash.\nFor Solana-based networks, the transaction will be a base58-encoded Solana signature.", + /// "description": "The 0x-prefixed, checksum EVM address of the recipient.", /// "examples": [ - /// "0x89c91c789e57059b17285e7ba1716a1f5ff4c5dace0ea5a5135f26158d0421b9" + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" /// ], /// "type": "string", - /// "pattern": "^(0x[a-fA-F0-9]{64}|[1-9A-HJ-NP-Za-km-z]{87,88})$" + /// "pattern": "^0x[0-9a-fA-F]{40}$" ///} /// ``` ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct X402SettlePaymentRejectionTransaction(::std::string::String); - impl ::std::ops::Deref for X402SettlePaymentRejectionTransaction { + pub struct X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo(::std::string::String); + impl ::std::ops::Deref for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: X402SettlePaymentRejectionTransaction) -> Self { + impl ::std::convert::From + for ::std::string::String + { + fn from(value: X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo) -> Self { value.0 } } - impl ::std::convert::From<&X402SettlePaymentRejectionTransaction> - for X402SettlePaymentRejectionTransaction + impl ::std::convert::From<&X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo> + for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo { - fn from(value: &X402SettlePaymentRejectionTransaction) -> Self { + fn from(value: &X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo) -> Self { value.clone() } } - impl ::std::str::FromStr for X402SettlePaymentRejectionTransaction { + impl ::std::str::FromStr for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^(0x[a-fA-F0-9]{64}|[1-9A-HJ-NP-Za-km-z]{87,88})$") - .unwrap() + ::regress::Regex::new("^0x[0-9a-fA-F]{40}$").unwrap() }); if PATTERN.find(value).is_none() { - return Err( - "doesn't match pattern \"^(0x[a-fA-F0-9]{64}|[1-9A-HJ-NP-Za-km-z]{87,88})$\"" - .into(), - ); + return Err("doesn't match pattern \"^0x[0-9a-fA-F]{40}$\"".into()); } Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for X402SettlePaymentRejectionTransaction { + impl ::std::convert::TryFrom<&str> for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for X402SettlePaymentRejectionTransaction { + impl ::std::convert::TryFrom<&::std::string::String> + for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo + { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -58908,7 +64665,9 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for X402SettlePaymentRejectionTransaction { + impl ::std::convert::TryFrom<::std::string::String> + for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo + { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -58916,7 +64675,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for X402SettlePaymentRejectionTransaction { + impl<'de> ::serde::Deserialize<'de> for X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -58928,121 +64687,336 @@ pub mod types { }) } } - ///The supported payment kind for the x402 protocol. A kind is comprised of a scheme and a network, which together uniquely identify a way to move money on the x402 protocol. For more details, please see [x402 Schemes](https://github.com/coinbase/x402?tab=readme-ov-file#schemes). + ///The EIP-712 hex-encoded signature of the Permit2 PermitWitnessTransferFrom message. Smart account signatures may be longer than 65 bytes. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The supported payment kind for the x402 protocol. A kind is comprised of a scheme and a network, which together uniquely identify a way to move money on the x402 protocol. For more details, please see [x402 Schemes](https://github.com/coinbase/x402?tab=readme-ov-file#schemes).", + /// "description": "The EIP-712 hex-encoded signature of the Permit2 PermitWitnessTransferFrom message. Smart account signatures may be longer than 65 bytes.", + /// "examples": [ + /// "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" + /// ], + /// "type": "string", + /// "pattern": "^0x[0-9a-fA-F]{130,}$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct X402ExactEvmPermit2PayloadSignature(::std::string::String); + impl ::std::ops::Deref for X402ExactEvmPermit2PayloadSignature { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: X402ExactEvmPermit2PayloadSignature) -> Self { + value.0 + } + } + impl ::std::convert::From<&X402ExactEvmPermit2PayloadSignature> + for X402ExactEvmPermit2PayloadSignature + { + fn from(value: &X402ExactEvmPermit2PayloadSignature) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for X402ExactEvmPermit2PayloadSignature { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^0x[0-9a-fA-F]{130,}$").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^0x[0-9a-fA-F]{130,}$\"".into()); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for X402ExactEvmPermit2PayloadSignature { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for X402ExactEvmPermit2PayloadSignature { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for X402ExactEvmPermit2PayloadSignature { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for X402ExactEvmPermit2PayloadSignature { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///The x402 protocol exact scheme payload for Solana networks. For more details, please see [Solana Exact Scheme Details](https://github.com/coinbase/x402/blob/main/specs/schemes/exact/scheme_exact_svm.md). + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "title": "x402ExactSolanaPayload", + /// "description": "The x402 protocol exact scheme payload for Solana networks. For more details, please see [Solana Exact Scheme Details](https://github.com/coinbase/x402/blob/main/specs/schemes/exact/scheme_exact_svm.md).", + /// "examples": [ + /// { + /// "transaction": "AQABAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA=" + /// } + /// ], /// "type": "object", /// "required": [ - /// "network", - /// "scheme", - /// "x402Version" + /// "transaction" /// ], /// "properties": { - /// "extra": { - /// "description": "The optional additional scheme-specific payment info.", + /// "transaction": { + /// "description": "The base64-encoded Solana transaction.", /// "examples": [ - /// { - /// "feePayer": "HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT" - /// } + /// "AQABAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8CBgMBAQAAAAIBAwQAAAAABgIAAAAAAAYDBQEBAAAGBAgAAAAABgUAAAAA6AMAAAAAAAAGBgUBAQEBBgcEAQAAAAYICgMBAQIDBgkCBgAAAAYKAwABAQEGCwMGAQEBBgwDAAABAQAAAAA=" + /// ], + /// "type": "string" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct X402ExactSolanaPayload { + ///The base64-encoded Solana transaction. + pub transaction: ::std::string::String, + } + impl ::std::convert::From<&X402ExactSolanaPayload> for X402ExactSolanaPayload { + fn from(value: &X402ExactSolanaPayload) -> Self { + value.clone() + } + } + impl X402ExactSolanaPayload { + pub fn builder() -> builder::X402ExactSolanaPayload { + Default::default() + } + } + ///JSON-RPC 2.0 error object. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "JSON-RPC 2.0 error object.", + /// "examples": [ + /// { + /// "code": -32600, + /// "data": {}, + /// "message": "Invalid Request" + /// } + /// ], + /// "type": "object", + /// "required": [ + /// "code", + /// "message" + /// ], + /// "properties": { + /// "code": { + /// "description": "Error code.", + /// "examples": [ + /// -32600 + /// ], + /// "type": "integer" + /// }, + /// "data": { + /// "description": "Additional error data.", + /// "examples": [ + /// {} /// ], /// "type": "object", /// "additionalProperties": true /// }, - /// "network": { - /// "description": "The network of the blockchain.", + /// "message": { + /// "description": "Error message.", /// "examples": [ - /// "base" + /// "Invalid Request" /// ], - /// "type": "string", - /// "enum": [ - /// "base-sepolia", - /// "base", - /// "solana-devnet", - /// "solana", - /// "polygon", - /// "eip155:8453", - /// "eip155:84532", - /// "eip155:137", - /// "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp", - /// "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", - /// "avalanche", - /// "arbitrum", - /// "arbitrum-sepolia", - /// "world", - /// "world-sepolia" + /// "type": "string" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct X402McpError { + ///Error code. + pub code: i64, + ///Additional error data. + #[serde(default, skip_serializing_if = "::serde_json::Map::is_empty")] + pub data: ::serde_json::Map<::std::string::String, ::serde_json::Value>, + ///Error message. + pub message: ::std::string::String, + } + impl ::std::convert::From<&X402McpError> for X402McpError { + fn from(value: &X402McpError) -> Self { + value.clone() + } + } + impl X402McpError { + pub fn builder() -> builder::X402McpError { + Default::default() + } + } + ///A JSON-RPC 2.0 request for the Model Context Protocol. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "A JSON-RPC 2.0 request for the Model Context Protocol.", + /// "type": "object", + /// "required": [ + /// "jsonrpc", + /// "method" + /// ], + /// "properties": { + /// "id": { + /// "description": "Request identifier.", + /// "examples": [ + /// 1 + /// ], + /// "oneOf": [ + /// { + /// "type": "string" + /// }, + /// { + /// "type": "integer" + /// } /// ] /// }, - /// "scheme": { - /// "description": "The scheme of the payment protocol.", + /// "jsonrpc": { + /// "description": "JSON-RPC version, must be \"2.0\".", /// "examples": [ - /// "exact" + /// "2.0" /// ], /// "type": "string", /// "enum": [ - /// "exact", - /// "upto" + /// "2.0" /// ] /// }, - /// "x402Version": { - /// "$ref": "#/components/schemas/X402Version" + /// "method": { + /// "description": "The MCP method to invoke.", + /// "examples": [ + /// "tools/list" + /// ], + /// "type": "string" + /// }, + /// "params": { + /// "description": "Optional parameters for the method.", + /// "examples": [ + /// {} + /// ], + /// "type": "object", + /// "additionalProperties": true /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402SupportedPaymentKind { - ///The optional additional scheme-specific payment info. + pub struct X402McpRequest { + ///Request identifier. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub id: ::std::option::Option, + ///JSON-RPC version, must be "2.0". + pub jsonrpc: X402McpRequestJsonrpc, + ///The MCP method to invoke. + pub method: ::std::string::String, + ///Optional parameters for the method. #[serde(default, skip_serializing_if = "::serde_json::Map::is_empty")] - pub extra: ::serde_json::Map<::std::string::String, ::serde_json::Value>, - ///The network of the blockchain. - pub network: X402SupportedPaymentKindNetwork, - ///The scheme of the payment protocol. - pub scheme: X402SupportedPaymentKindScheme, - #[serde(rename = "x402Version")] - pub x402_version: X402Version, + pub params: ::serde_json::Map<::std::string::String, ::serde_json::Value>, } - impl ::std::convert::From<&X402SupportedPaymentKind> for X402SupportedPaymentKind { - fn from(value: &X402SupportedPaymentKind) -> Self { + impl ::std::convert::From<&X402McpRequest> for X402McpRequest { + fn from(value: &X402McpRequest) -> Self { value.clone() } } - impl X402SupportedPaymentKind { - pub fn builder() -> builder::X402SupportedPaymentKind { + impl X402McpRequest { + pub fn builder() -> builder::X402McpRequest { Default::default() } } - ///The network of the blockchain. + ///Request identifier. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The network of the blockchain.", + /// "description": "Request identifier.", /// "examples": [ - /// "base" + /// 1 + /// ], + /// "oneOf": [ + /// { + /// "type": "string" + /// }, + /// { + /// "type": "integer" + /// } + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + #[serde(untagged)] + pub enum X402McpRequestId { + Variant0(::std::string::String), + Variant1(i64), + } + impl ::std::convert::From<&Self> for X402McpRequestId { + fn from(value: &X402McpRequestId) -> Self { + value.clone() + } + } + impl ::std::fmt::Display for X402McpRequestId { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match self { + Self::Variant0(x) => x.fmt(f), + Self::Variant1(x) => x.fmt(f), + } + } + } + impl ::std::convert::From for X402McpRequestId { + fn from(value: i64) -> Self { + Self::Variant1(value) + } + } + ///JSON-RPC version, must be "2.0". + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "JSON-RPC version, must be \"2.0\".", + /// "examples": [ + /// "2.0" /// ], /// "type": "string", /// "enum": [ - /// "base-sepolia", - /// "base", - /// "solana-devnet", - /// "solana", - /// "polygon", - /// "eip155:8453", - /// "eip155:84532", - /// "eip155:137", - /// "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp", - /// "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", - /// "avalanche", - /// "arbitrum", - /// "arbitrum-sepolia", - /// "world", - /// "world-sepolia" + /// "2.0" /// ] ///} /// ``` @@ -59059,102 +65033,38 @@ pub mod types { PartialEq, PartialOrd, )] - pub enum X402SupportedPaymentKindNetwork { - #[serde(rename = "base-sepolia")] - BaseSepolia, - #[serde(rename = "base")] - Base, - #[serde(rename = "solana-devnet")] - SolanaDevnet, - #[serde(rename = "solana")] - Solana, - #[serde(rename = "polygon")] - Polygon, - #[serde(rename = "eip155:8453")] - Eip1558453, - #[serde(rename = "eip155:84532")] - Eip15584532, - #[serde(rename = "eip155:137")] - Eip155137, - #[serde(rename = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp")] - Solana5eykt4UsFv8P8nJdTrEpY1vzqKqZKvdp, - #[serde(rename = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1")] - SolanaEtWtrabZaYq6iMfeYKouRu166Vu2xqa1, - #[serde(rename = "avalanche")] - Avalanche, - #[serde(rename = "arbitrum")] - Arbitrum, - #[serde(rename = "arbitrum-sepolia")] - ArbitrumSepolia, - #[serde(rename = "world")] - World, - #[serde(rename = "world-sepolia")] - WorldSepolia, + pub enum X402McpRequestJsonrpc { + #[serde(rename = "2.0")] + X20, } - impl ::std::convert::From<&Self> for X402SupportedPaymentKindNetwork { - fn from(value: &X402SupportedPaymentKindNetwork) -> Self { + impl ::std::convert::From<&Self> for X402McpRequestJsonrpc { + fn from(value: &X402McpRequestJsonrpc) -> Self { value.clone() } } - impl ::std::fmt::Display for X402SupportedPaymentKindNetwork { + impl ::std::fmt::Display for X402McpRequestJsonrpc { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match *self { - Self::BaseSepolia => f.write_str("base-sepolia"), - Self::Base => f.write_str("base"), - Self::SolanaDevnet => f.write_str("solana-devnet"), - Self::Solana => f.write_str("solana"), - Self::Polygon => f.write_str("polygon"), - Self::Eip1558453 => f.write_str("eip155:8453"), - Self::Eip15584532 => f.write_str("eip155:84532"), - Self::Eip155137 => f.write_str("eip155:137"), - Self::Solana5eykt4UsFv8P8nJdTrEpY1vzqKqZKvdp => { - f.write_str("solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp") - } - Self::SolanaEtWtrabZaYq6iMfeYKouRu166Vu2xqa1 => { - f.write_str("solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1") - } - Self::Avalanche => f.write_str("avalanche"), - Self::Arbitrum => f.write_str("arbitrum"), - Self::ArbitrumSepolia => f.write_str("arbitrum-sepolia"), - Self::World => f.write_str("world"), - Self::WorldSepolia => f.write_str("world-sepolia"), + Self::X20 => f.write_str("2.0"), } } } - impl ::std::str::FromStr for X402SupportedPaymentKindNetwork { + impl ::std::str::FromStr for X402McpRequestJsonrpc { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { match value { - "base-sepolia" => Ok(Self::BaseSepolia), - "base" => Ok(Self::Base), - "solana-devnet" => Ok(Self::SolanaDevnet), - "solana" => Ok(Self::Solana), - "polygon" => Ok(Self::Polygon), - "eip155:8453" => Ok(Self::Eip1558453), - "eip155:84532" => Ok(Self::Eip15584532), - "eip155:137" => Ok(Self::Eip155137), - "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp" => { - Ok(Self::Solana5eykt4UsFv8P8nJdTrEpY1vzqKqZKvdp) - } - "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1" => { - Ok(Self::SolanaEtWtrabZaYq6iMfeYKouRu166Vu2xqa1) - } - "avalanche" => Ok(Self::Avalanche), - "arbitrum" => Ok(Self::Arbitrum), - "arbitrum-sepolia" => Ok(Self::ArbitrumSepolia), - "world" => Ok(Self::World), - "world-sepolia" => Ok(Self::WorldSepolia), + "2.0" => Ok(Self::X20), _ => Err("invalid value".into()), } } } - impl ::std::convert::TryFrom<&str> for X402SupportedPaymentKindNetwork { + impl ::std::convert::TryFrom<&str> for X402McpRequestJsonrpc { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for X402SupportedPaymentKindNetwork { + impl ::std::convert::TryFrom<&::std::string::String> for X402McpRequestJsonrpc { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -59162,7 +65072,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for X402SupportedPaymentKindNetwork { + impl ::std::convert::TryFrom<::std::string::String> for X402McpRequestJsonrpc { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -59170,20 +65080,143 @@ pub mod types { value.parse() } } - ///The scheme of the payment protocol. + ///A JSON-RPC 2.0 response for the Model Context Protocol. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The scheme of the payment protocol.", - /// "examples": [ - /// "exact" + /// "description": "A JSON-RPC 2.0 response for the Model Context Protocol.", + /// "type": "object", + /// "required": [ + /// "jsonrpc" + /// ], + /// "properties": { + /// "error": { + /// "$ref": "#/components/schemas/x402McpError" + /// }, + /// "id": { + /// "description": "Request identifier (matches the request ID, null for notifications).", + /// "examples": [ + /// 1 + /// ], + /// "oneOf": [ + /// { + /// "type": "null" + /// }, + /// { + /// "oneOf": [ + /// { + /// "type": "string" + /// }, + /// { + /// "type": "integer" + /// } + /// ] + /// } + /// ] + /// }, + /// "jsonrpc": { + /// "description": "JSON-RPC version.", + /// "examples": [ + /// "2.0" + /// ], + /// "type": "string", + /// "enum": [ + /// "2.0" + /// ] + /// }, + /// "result": { + /// "description": "The result of the method call (present on success).", + /// "examples": [ + /// { + /// "tools": [] + /// } + /// ], + /// "type": "object", + /// "additionalProperties": true + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct X402McpResponse { + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub error: ::std::option::Option, + ///Request identifier (matches the request ID, null for notifications). + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub id: ::std::option::Option, + ///JSON-RPC version. + pub jsonrpc: X402McpResponseJsonrpc, + ///The result of the method call (present on success). + #[serde(default, skip_serializing_if = "::serde_json::Map::is_empty")] + pub result: ::serde_json::Map<::std::string::String, ::serde_json::Value>, + } + impl ::std::convert::From<&X402McpResponse> for X402McpResponse { + fn from(value: &X402McpResponse) -> Self { + value.clone() + } + } + impl X402McpResponse { + pub fn builder() -> builder::X402McpResponse { + Default::default() + } + } + ///`X402McpResponseId` + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "oneOf": [ + /// { + /// "type": "string" + /// }, + /// { + /// "type": "integer" + /// } + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + #[serde(untagged)] + pub enum X402McpResponseId { + Variant0(::std::string::String), + Variant1(i64), + } + impl ::std::convert::From<&Self> for X402McpResponseId { + fn from(value: &X402McpResponseId) -> Self { + value.clone() + } + } + impl ::std::fmt::Display for X402McpResponseId { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match self { + Self::Variant0(x) => x.fmt(f), + Self::Variant1(x) => x.fmt(f), + } + } + } + impl ::std::convert::From for X402McpResponseId { + fn from(value: i64) -> Self { + Self::Variant1(value) + } + } + ///JSON-RPC version. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "JSON-RPC version.", + /// "examples": [ + /// "2.0" /// ], /// "type": "string", /// "enum": [ - /// "exact", - /// "upto" + /// "2.0" /// ] ///} /// ``` @@ -59200,42 +65233,38 @@ pub mod types { PartialEq, PartialOrd, )] - pub enum X402SupportedPaymentKindScheme { - #[serde(rename = "exact")] - Exact, - #[serde(rename = "upto")] - Upto, + pub enum X402McpResponseJsonrpc { + #[serde(rename = "2.0")] + X20, } - impl ::std::convert::From<&Self> for X402SupportedPaymentKindScheme { - fn from(value: &X402SupportedPaymentKindScheme) -> Self { + impl ::std::convert::From<&Self> for X402McpResponseJsonrpc { + fn from(value: &X402McpResponseJsonrpc) -> Self { value.clone() } } - impl ::std::fmt::Display for X402SupportedPaymentKindScheme { + impl ::std::fmt::Display for X402McpResponseJsonrpc { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match *self { - Self::Exact => f.write_str("exact"), - Self::Upto => f.write_str("upto"), + Self::X20 => f.write_str("2.0"), } } } - impl ::std::str::FromStr for X402SupportedPaymentKindScheme { + impl ::std::str::FromStr for X402McpResponseJsonrpc { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { match value { - "exact" => Ok(Self::Exact), - "upto" => Ok(Self::Upto), + "2.0" => Ok(Self::X20), _ => Err("invalid value".into()), } } } - impl ::std::convert::TryFrom<&str> for X402SupportedPaymentKindScheme { + impl ::std::convert::TryFrom<&str> for X402McpResponseJsonrpc { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for X402SupportedPaymentKindScheme { + impl ::std::convert::TryFrom<&::std::string::String> for X402McpResponseJsonrpc { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -59243,7 +65272,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for X402SupportedPaymentKindScheme { + impl ::std::convert::TryFrom<::std::string::String> for X402McpResponseJsonrpc { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -59251,117 +65280,47 @@ pub mod types { value.parse() } } - ///The x402 protocol payment payload that the client attaches to x402-paid API requests to the resource server in the X-PAYMENT header. + /**The x402 protocol payment payload that the client attaches to x402-paid API requests to the resource server in the X-PAYMENT header. + For EVM networks, smart account signatures can be longer than 65 bytes.*/ /// ///
JSON schema /// /// ```json ///{ - /// "description": "The x402 protocol payment payload that the client attaches to x402-paid API requests to the resource server in the X-PAYMENT header.", - /// "examples": [ - /// { - /// "network": "base", - /// "payload": { - /// "authorization": { - /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "nonce": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", - /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "validAfter": "1716150000", - /// "validBefore": "1716150000", - /// "value": "1000000000000000000" - /// }, - /// "signature": "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" - /// }, - /// "scheme": "exact", - /// "x402Version": 1 - /// } - /// ], + /// "description": "The x402 protocol payment payload that the client attaches to x402-paid API requests to the resource server in the X-PAYMENT header.\nFor EVM networks, smart account signatures can be longer than 65 bytes.", /// "type": "object", - /// "required": [ - /// "network", - /// "payload", - /// "scheme", - /// "x402Version" - /// ], - /// "properties": { - /// "network": { - /// "description": "The network of the blockchain to send payment on.", - /// "examples": [ - /// "base" - /// ], - /// "type": "string", - /// "enum": [ - /// "base-sepolia", - /// "base", - /// "solana-devnet", - /// "solana", - /// "polygon" - /// ] - /// }, - /// "payload": { - /// "description": "The payload of the payment depending on the x402Version, scheme, and network.", - /// "examples": [ - /// { - /// "authorization": { - /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "nonce": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", - /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "validAfter": "1716150000", - /// "validBefore": "1716150000", - /// "value": "1000000000000000000" - /// }, - /// "signature": "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" - /// } - /// ], - /// "type": "object", - /// "oneOf": [ - /// { - /// "$ref": "#/components/schemas/x402ExactEvmPayload" - /// }, - /// { - /// "$ref": "#/components/schemas/x402ExactEvmPermit2Payload" - /// }, - /// { - /// "$ref": "#/components/schemas/x402ExactSolanaPayload" - /// } - /// ] - /// }, - /// "scheme": { - /// "description": "The scheme of the payment protocol to use. Currently, the only supported scheme is `exact`.", - /// "examples": [ - /// "exact" - /// ], - /// "type": "string", - /// "enum": [ - /// "exact" - /// ] + /// "oneOf": [ + /// { + /// "$ref": "#/components/schemas/x402V2PaymentPayload" /// }, - /// "x402Version": { - /// "$ref": "#/components/schemas/X402Version" + /// { + /// "$ref": "#/components/schemas/x402V1PaymentPayload" /// } - /// } + /// ] ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402V1PaymentPayload { - ///The network of the blockchain to send payment on. - pub network: X402v1PaymentPayloadNetwork, - ///The payload of the payment depending on the x402Version, scheme, and network. - pub payload: X402v1PaymentPayloadPayload, - ///The scheme of the payment protocol to use. Currently, the only supported scheme is `exact`. - pub scheme: X402v1PaymentPayloadScheme, - #[serde(rename = "x402Version")] - pub x402_version: X402Version, + #[serde(untagged)] + pub enum X402PaymentPayload { + #[serde(rename = "X402V2PaymentPayload")] + X402v2PaymentPayload(X402V2PaymentPayload), + #[serde(rename = "X402V1PaymentPayload")] + X402v1PaymentPayload(X402V1PaymentPayload), } - impl ::std::convert::From<&X402V1PaymentPayload> for X402V1PaymentPayload { - fn from(value: &X402V1PaymentPayload) -> Self { + impl ::std::convert::From<&Self> for X402PaymentPayload { + fn from(value: &X402PaymentPayload) -> Self { value.clone() } } - impl X402V1PaymentPayload { - pub fn builder() -> builder::X402V1PaymentPayload { - Default::default() + impl ::std::convert::From for X402PaymentPayload { + fn from(value: X402V2PaymentPayload) -> Self { + Self::X402v2PaymentPayload(value) + } + } + impl ::std::convert::From for X402PaymentPayload { + fn from(value: X402V1PaymentPayload) -> Self { + Self::X402v1PaymentPayload(value) } } ///The x402 protocol payment requirements that the resource server expects the client's payment payload to meet. @@ -59372,26 +65331,49 @@ pub mod types { ///{ /// "description": "The x402 protocol payment requirements that the resource server expects the client's payment payload to meet.", /// "type": "object", - /// "required": [ - /// "asset", - /// "description", - /// "maxAmountRequired", - /// "maxTimeoutSeconds", - /// "mimeType", - /// "network", - /// "payTo", - /// "resource", - /// "scheme" - /// ], - /// "properties": { - /// "asset": { - /// "description": "The asset to pay with.\n\nFor EVM networks, the asset will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, the asset will be a base58-encoded Solana address.", - /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" - /// ], - /// "type": "string", - /// "pattern": "^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$" + /// "oneOf": [ + /// { + /// "$ref": "#/components/schemas/x402V2PaymentRequirements" /// }, + /// { + /// "$ref": "#/components/schemas/x402V1PaymentRequirements" + /// } + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + #[serde(untagged)] + pub enum X402PaymentRequirements { + #[serde(rename = "X402V2PaymentRequirements")] + X402v2PaymentRequirements(X402V2PaymentRequirements), + #[serde(rename = "X402V1PaymentRequirements")] + X402v1PaymentRequirements(X402V1PaymentRequirements), + } + impl ::std::convert::From<&Self> for X402PaymentRequirements { + fn from(value: &X402PaymentRequirements) -> Self { + value.clone() + } + } + impl ::std::convert::From for X402PaymentRequirements { + fn from(value: X402V2PaymentRequirements) -> Self { + Self::X402v2PaymentRequirements(value) + } + } + impl ::std::convert::From for X402PaymentRequirements { + fn from(value: X402V1PaymentRequirements) -> Self { + Self::X402v1PaymentRequirements(value) + } + } + ///Describes the resource being accessed in x402 protocol. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "Describes the resource being accessed in x402 protocol.", + /// "type": "object", + /// "properties": { /// "description": { /// "description": "A human-readable description of the resource.", /// "examples": [ @@ -59403,30 +65385,6 @@ pub mod types { /// } /// ] /// }, - /// "extra": { - /// "description": "The optional additional scheme-specific payment info.", - /// "examples": [ - /// { - /// "gasLimit": "1000000" - /// } - /// ], - /// "type": "object", - /// "additionalProperties": true - /// }, - /// "maxAmountRequired": { - /// "description": "The maximum amount required to pay for the resource in atomic units of the payment asset.", - /// "examples": [ - /// "1000000" - /// ], - /// "type": "string" - /// }, - /// "maxTimeoutSeconds": { - /// "description": "The maximum time in seconds for the resource server to respond.", - /// "examples": [ - /// 10 - /// ], - /// "type": "integer" - /// }, /// "mimeType": { /// "description": "The MIME type of the resource response.", /// "examples": [ @@ -59434,366 +65392,341 @@ pub mod types { /// ], /// "type": "string" /// }, - /// "network": { - /// "description": "The network of the blockchain to send payment on.", - /// "examples": [ - /// "base" - /// ], - /// "type": "string", - /// "enum": [ - /// "base-sepolia", - /// "base", - /// "solana-devnet", - /// "solana", - /// "polygon" - /// ] - /// }, - /// "outputSchema": { - /// "description": "The optional JSON schema describing the resource output.", - /// "examples": [ - /// { - /// "data": "string" - /// } - /// ], - /// "type": "object", - /// "additionalProperties": true - /// }, - /// "payTo": { - /// "description": "The destination to pay value to.\n\nFor EVM networks, payTo will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, payTo will be a base58-encoded Solana address.", - /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" - /// ], - /// "type": "string", - /// "pattern": "^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$" - /// }, - /// "resource": { - /// "description": "The URL of the resource to pay for.", + /// "url": { + /// "description": "The URL of the resource.", /// "examples": [ /// "https://api.example.com/premium/resource/123" /// ], /// "type": "string" - /// }, - /// "scheme": { - /// "description": "The scheme of the payment protocol to use. Currently, the only supported scheme is `exact`.", - /// "examples": [ - /// "exact" - /// ], - /// "type": "string", - /// "enum": [ - /// "exact" - /// ] /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402V1PaymentRequirements { - /**The asset to pay with. - - For EVM networks, the asset will be a 0x-prefixed, checksum EVM address. - - For Solana-based networks, the asset will be a base58-encoded Solana address.*/ - pub asset: X402v1PaymentRequirementsAsset, + pub struct X402ResourceInfo { ///A human-readable description of the resource. - pub description: Description, - ///The optional additional scheme-specific payment info. - #[serde(default, skip_serializing_if = "::serde_json::Map::is_empty")] - pub extra: ::serde_json::Map<::std::string::String, ::serde_json::Value>, - ///The maximum amount required to pay for the resource in atomic units of the payment asset. - #[serde(rename = "maxAmountRequired")] - pub max_amount_required: ::std::string::String, - ///The maximum time in seconds for the resource server to respond. - #[serde(rename = "maxTimeoutSeconds")] - pub max_timeout_seconds: i64, + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub description: ::std::option::Option, ///The MIME type of the resource response. - #[serde(rename = "mimeType")] - pub mime_type: ::std::string::String, - ///The network of the blockchain to send payment on. - pub network: X402v1PaymentRequirementsNetwork, - ///The optional JSON schema describing the resource output. #[serde( - rename = "outputSchema", + rename = "mimeType", default, - skip_serializing_if = "::serde_json::Map::is_empty" + skip_serializing_if = "::std::option::Option::is_none" )] - pub output_schema: ::serde_json::Map<::std::string::String, ::serde_json::Value>, - /**The destination to pay value to. - - For EVM networks, payTo will be a 0x-prefixed, checksum EVM address. - - For Solana-based networks, payTo will be a base58-encoded Solana address.*/ - #[serde(rename = "payTo")] - pub pay_to: X402v1PaymentRequirementsPayTo, - ///The URL of the resource to pay for. - pub resource: ::std::string::String, - ///The scheme of the payment protocol to use. Currently, the only supported scheme is `exact`. - pub scheme: X402v1PaymentRequirementsScheme, + pub mime_type: ::std::option::Option<::std::string::String>, + ///The URL of the resource. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub url: ::std::option::Option<::std::string::String>, } - impl ::std::convert::From<&X402V1PaymentRequirements> for X402V1PaymentRequirements { - fn from(value: &X402V1PaymentRequirements) -> Self { + impl ::std::convert::From<&X402ResourceInfo> for X402ResourceInfo { + fn from(value: &X402ResourceInfo) -> Self { value.clone() } } - impl X402V1PaymentRequirements { - pub fn builder() -> builder::X402V1PaymentRequirements { + impl ::std::default::Default for X402ResourceInfo { + fn default() -> Self { + Self { + description: Default::default(), + mime_type: Default::default(), + url: Default::default(), + } + } + } + impl X402ResourceInfo { + pub fn builder() -> builder::X402ResourceInfo { Default::default() } } - ///The x402 protocol payment payload that the client attaches to x402-paid API requests to the resource server in the X-PAYMENT header. + ///Quality metrics for a discovered x402 resource. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The x402 protocol payment payload that the client attaches to x402-paid API requests to the resource server in the X-PAYMENT header.", + /// "description": "Quality metrics for a discovered x402 resource.", /// "examples": [ /// { - /// "accepted": { - /// "amount": "1000", - /// "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", - /// "extra": { - /// "name": "USDC", - /// "version": "2" - /// }, - /// "maxTimeoutSeconds": 60, - /// "network": "eip155:84532", - /// "payTo": "0x122F8Fcaf2152420445Aa424E1D8C0306935B5c9", - /// "scheme": "exact" - /// }, - /// "payload": { - /// "authorization": { - /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "nonce": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", - /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "validAfter": "1716150000", - /// "validBefore": "1716150000", - /// "value": "1000000000000000000" - /// }, - /// "signature": "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" - /// }, - /// "resource": { - /// "description": "Premium API access for data analysis.", - /// "mimeType": "application/json", - /// "url": "https://api.example.com/premium/resource/123" - /// }, - /// "x402Version": 2 + /// "l30DaysTotalCalls": 42, + /// "l30DaysUniquePayers": 15, + /// "lastCalledAt": "2024-01-15T10:30:00Z" /// } /// ], /// "type": "object", - /// "required": [ - /// "accepted", - /// "payload", - /// "x402Version" - /// ], /// "properties": { - /// "accepted": { - /// "$ref": "#/components/schemas/x402V2PaymentRequirements" - /// }, - /// "extensions": { - /// "description": "Optional protocol extensions.", + /// "l30DaysTotalCalls": { + /// "description": "Total number of paid calls to a resource in the last 30 days.", /// "examples": [ - /// { - /// "bazaar": { - /// "info": { - /// "input": { - /// "method": "GET", - /// "type": "http" - /// } - /// }, - /// "schema": {} - /// } - /// } + /// 42 /// ], - /// "type": "object", - /// "additionalProperties": true + /// "type": "integer" /// }, - /// "payload": { - /// "description": "The payload of the payment depending on the x402Version, scheme, and network.", + /// "l30DaysUniquePayers": { + /// "description": "Number of unique payers to a resource in the last 30 days.", /// "examples": [ - /// { - /// "authorization": { - /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "nonce": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", - /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "validAfter": "1716150000", - /// "validBefore": "1716150000", - /// "value": "1000000000000000000" - /// }, - /// "signature": "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" - /// } + /// 15 /// ], - /// "type": "object", - /// "oneOf": [ - /// { - /// "$ref": "#/components/schemas/x402ExactEvmPayload" - /// }, - /// { - /// "$ref": "#/components/schemas/x402ExactEvmPermit2Payload" - /// }, - /// { - /// "$ref": "#/components/schemas/x402ExactSolanaPayload" - /// } - /// ] - /// }, - /// "resource": { - /// "$ref": "#/components/schemas/x402ResourceInfo" + /// "type": "integer" /// }, - /// "x402Version": { - /// "$ref": "#/components/schemas/X402Version" + /// "lastCalledAt": { + /// "description": "Timestamp of the most recent paid call to a resource.", + /// "examples": [ + /// "2024-01-15T10:30:00Z" + /// ], + /// "type": "string", + /// "format": "date-time" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402V2PaymentPayload { - pub accepted: X402V2PaymentRequirements, - ///Optional protocol extensions. - #[serde(default, skip_serializing_if = "::serde_json::Map::is_empty")] - pub extensions: ::serde_json::Map<::std::string::String, ::serde_json::Value>, - ///The payload of the payment depending on the x402Version, scheme, and network. - pub payload: X402v2PaymentPayloadPayload, - #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub resource: ::std::option::Option, - #[serde(rename = "x402Version")] - pub x402_version: X402Version, + pub struct X402ResourceQuality { + ///Total number of paid calls to a resource in the last 30 days. + #[serde( + rename = "l30DaysTotalCalls", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub l30_days_total_calls: ::std::option::Option, + ///Number of unique payers to a resource in the last 30 days. + #[serde( + rename = "l30DaysUniquePayers", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub l30_days_unique_payers: ::std::option::Option, + ///Timestamp of the most recent paid call to a resource. + #[serde( + rename = "lastCalledAt", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub last_called_at: ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, } - impl ::std::convert::From<&X402V2PaymentPayload> for X402V2PaymentPayload { - fn from(value: &X402V2PaymentPayload) -> Self { + impl ::std::convert::From<&X402ResourceQuality> for X402ResourceQuality { + fn from(value: &X402ResourceQuality) -> Self { value.clone() } } - impl X402V2PaymentPayload { - pub fn builder() -> builder::X402V2PaymentPayload { + impl ::std::default::Default for X402ResourceQuality { + fn default() -> Self { + Self { + l30_days_total_calls: Default::default(), + l30_days_unique_payers: Default::default(), + last_called_at: Default::default(), + } + } + } + impl X402ResourceQuality { + pub fn builder() -> builder::X402ResourceQuality { Default::default() } } - ///The x402 protocol payment requirements that the resource server expects the client's payment payload to meet. + ///Response from a search for x402 resources. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The x402 protocol payment requirements that the resource server expects the client's payment payload to meet.", + /// "description": "Response from a search for x402 resources.", /// "type": "object", /// "required": [ - /// "amount", - /// "asset", - /// "maxTimeoutSeconds", - /// "network", - /// "payTo", - /// "scheme" + /// "partialResults", + /// "resources", + /// "x402Version" /// ], /// "properties": { - /// "amount": { - /// "description": "The amount to pay for the resource in atomic units of the payment asset.", - /// "examples": [ - /// "1000000" - /// ], - /// "type": "string" - /// }, - /// "asset": { - /// "description": "The asset to pay with.\n\nFor EVM networks, the asset will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, the asset will be a base58-encoded Solana address.", - /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" - /// ], - /// "type": "string", - /// "pattern": "^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$" - /// }, - /// "extra": { - /// "description": "The optional additional scheme-specific payment info.", - /// "examples": [ - /// { - /// "name": "USDC", - /// "version": "2" - /// } - /// ], - /// "type": "object", - /// "additionalProperties": true - /// }, - /// "maxTimeoutSeconds": { - /// "description": "The maximum time in seconds for the resource server to respond.", - /// "examples": [ - /// 10 - /// ], - /// "type": "integer" - /// }, - /// "network": { - /// "description": "The network of the blockchain to send payment on in caip2 format.", + /// "partialResults": { + /// "description": "Indicates whether the result set was truncated because there were more results than the requested limit.", /// "examples": [ - /// "eip155:1" + /// false /// ], - /// "type": "string" + /// "type": "boolean" /// }, - /// "payTo": { - /// "description": "The destination to pay value to.\n\nFor EVM networks, payTo will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, payTo will be a base58-encoded Solana address.", + /// "resources": { + /// "description": "List of x402 resources matching the search query and filters.", /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// [ + /// { + /// "accepts": [ + /// { + /// "amount": "1000000", + /// "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + /// "maxTimeoutSeconds": 60, + /// "network": "eip155:8453", + /// "payTo": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "scheme": "exact" + /// } + /// ], + /// "description": "Real-time weather forecast data.", + /// "extensions": { + /// "bazaar": { + /// "info": { + /// "input": { + /// "method": "GET", + /// "type": "http" + /// } + /// }, + /// "schema": {} + /// } + /// }, + /// "iconUrl": "https://res.cloudinary.com/bdb-prod/image/upload/...", + /// "lastUpdated": "2024-01-15T10:30:00Z", + /// "quality": { + /// "l30DaysTotalCalls": 42, + /// "l30DaysUniquePayers": 15, + /// "lastCalledAt": "2024-01-15T10:30:00Z" + /// }, + /// "resource": "https://api.example.com/weather/forecast", + /// "serviceName": "Weather API", + /// "tags": [ + /// "weather", + /// "data" + /// ], + /// "type": "http", + /// "x402Version": 2 + /// } + /// ] /// ], - /// "type": "string", - /// "pattern": "^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$" + /// "type": "array", + /// "items": { + /// "$ref": "#/components/schemas/x402DiscoveryResource" + /// } /// }, - /// "scheme": { - /// "description": "The scheme of the payment protocol to use. Supported schemes are `exact` and `upto`.", + /// "searchMethod": { + /// "description": "The search method used to retrieve the results (e.g., \"text\" or \"vector\").", /// "examples": [ - /// "exact" + /// "text" /// ], /// "type": "string", /// "enum": [ - /// "exact", - /// "upto" + /// "text", + /// "vector" /// ] + /// }, + /// "x402Version": { + /// "$ref": "#/components/schemas/X402Version" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402V2PaymentRequirements { - ///The amount to pay for the resource in atomic units of the payment asset. - pub amount: ::std::string::String, - /**The asset to pay with. - - For EVM networks, the asset will be a 0x-prefixed, checksum EVM address. - - For Solana-based networks, the asset will be a base58-encoded Solana address.*/ - pub asset: X402v2PaymentRequirementsAsset, - ///The optional additional scheme-specific payment info. - #[serde(default, skip_serializing_if = "::serde_json::Map::is_empty")] - pub extra: ::serde_json::Map<::std::string::String, ::serde_json::Value>, - ///The maximum time in seconds for the resource server to respond. - #[serde(rename = "maxTimeoutSeconds")] - pub max_timeout_seconds: i64, - ///The network of the blockchain to send payment on in caip2 format. - pub network: ::std::string::String, - /**The destination to pay value to. - - For EVM networks, payTo will be a 0x-prefixed, checksum EVM address. - - For Solana-based networks, payTo will be a base58-encoded Solana address.*/ - #[serde(rename = "payTo")] - pub pay_to: X402v2PaymentRequirementsPayTo, - ///The scheme of the payment protocol to use. Supported schemes are `exact` and `upto`. - pub scheme: X402v2PaymentRequirementsScheme, + pub struct X402SearchResourcesResponse { + ///Indicates whether the result set was truncated because there were more results than the requested limit. + #[serde(rename = "partialResults")] + pub partial_results: bool, + ///List of x402 resources matching the search query and filters. + pub resources: ::std::vec::Vec, + ///The search method used to retrieve the results (e.g., "text" or "vector"). + #[serde( + rename = "searchMethod", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub search_method: ::std::option::Option, + #[serde(rename = "x402Version")] + pub x402_version: X402Version, } - impl ::std::convert::From<&X402V2PaymentRequirements> for X402V2PaymentRequirements { - fn from(value: &X402V2PaymentRequirements) -> Self { + impl ::std::convert::From<&X402SearchResourcesResponse> for X402SearchResourcesResponse { + fn from(value: &X402SearchResourcesResponse) -> Self { value.clone() } } - impl X402V2PaymentRequirements { - pub fn builder() -> builder::X402V2PaymentRequirements { + impl X402SearchResourcesResponse { + pub fn builder() -> builder::X402SearchResourcesResponse { Default::default() } } - ///The reason the payment is invalid on the x402 protocol. + ///The search method used to retrieve the results (e.g., "text" or "vector"). /// ///
JSON schema /// /// ```json ///{ - /// "description": "The reason the payment is invalid on the x402 protocol.", + /// "description": "The search method used to retrieve the results (e.g., \"text\" or \"vector\").", + /// "examples": [ + /// "text" + /// ], + /// "type": "string", + /// "enum": [ + /// "text", + /// "vector" + /// ] + ///} + /// ``` + ///
+ #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum X402SearchResourcesResponseSearchMethod { + #[serde(rename = "text")] + Text, + #[serde(rename = "vector")] + Vector, + } + impl ::std::convert::From<&Self> for X402SearchResourcesResponseSearchMethod { + fn from(value: &X402SearchResourcesResponseSearchMethod) -> Self { + value.clone() + } + } + impl ::std::fmt::Display for X402SearchResourcesResponseSearchMethod { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Text => f.write_str("text"), + Self::Vector => f.write_str("vector"), + } + } + } + impl ::std::str::FromStr for X402SearchResourcesResponseSearchMethod { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "text" => Ok(Self::Text), + "vector" => Ok(Self::Vector), + _ => Err("invalid value".into()), + } + } + } + impl ::std::convert::TryFrom<&str> for X402SearchResourcesResponseSearchMethod { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for X402SearchResourcesResponseSearchMethod { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for X402SearchResourcesResponseSearchMethod { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + ///The reason the payment settlement errored on the x402 protocol. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The reason the payment settlement errored on the x402 protocol.", /// "examples": [ /// "insufficient_funds" /// ], @@ -59841,6 +65774,11 @@ pub mod types { /// "invalid_exact_svm_payload_transaction_transfer_to_incorrect_ata", /// "invalid_exact_svm_payload_transaction_fee_payer_included_in_instruction_accounts", /// "invalid_exact_svm_payload_transaction_fee_payer_transferring_funds", + /// "settle_exact_evm_transaction_confirmation_timed_out", + /// "settle_exact_node_failure", + /// "settle_exact_failed_onchain", + /// "settle_exact_svm_block_height_exceeded", + /// "settle_exact_svm_transaction_confirmation_timed_out", /// "unknown_error" /// ] ///} @@ -59858,7 +65796,7 @@ pub mod types { PartialEq, PartialOrd, )] - pub enum X402VerifyInvalidReason { + pub enum X402SettleErrorReason { #[serde(rename = "insufficient_funds")] InsufficientFunds, #[serde(rename = "invalid_scheme")] @@ -59959,15 +65897,25 @@ pub mod types { InvalidExactSvmPayloadTransactionFeePayerIncludedInInstructionAccounts, #[serde(rename = "invalid_exact_svm_payload_transaction_fee_payer_transferring_funds")] InvalidExactSvmPayloadTransactionFeePayerTransferringFunds, + #[serde(rename = "settle_exact_evm_transaction_confirmation_timed_out")] + SettleExactEvmTransactionConfirmationTimedOut, + #[serde(rename = "settle_exact_node_failure")] + SettleExactNodeFailure, + #[serde(rename = "settle_exact_failed_onchain")] + SettleExactFailedOnchain, + #[serde(rename = "settle_exact_svm_block_height_exceeded")] + SettleExactSvmBlockHeightExceeded, + #[serde(rename = "settle_exact_svm_transaction_confirmation_timed_out")] + SettleExactSvmTransactionConfirmationTimedOut, #[serde(rename = "unknown_error")] UnknownError, } - impl ::std::convert::From<&Self> for X402VerifyInvalidReason { - fn from(value: &X402VerifyInvalidReason) -> Self { + impl ::std::convert::From<&Self> for X402SettleErrorReason { + fn from(value: &X402SettleErrorReason) -> Self { value.clone() } } - impl ::std::fmt::Display for X402VerifyInvalidReason { + impl ::std::fmt::Display for X402SettleErrorReason { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match *self { Self::InsufficientFunds => f.write_str("insufficient_funds"), @@ -60124,11 +66072,24 @@ pub mod types { "invalid_exact_svm_payload_transaction_fee_payer_transferring_funds", ) } + Self::SettleExactEvmTransactionConfirmationTimedOut => { + f.write_str("settle_exact_evm_transaction_confirmation_timed_out") + } + Self::SettleExactNodeFailure => f.write_str("settle_exact_node_failure"), + Self::SettleExactFailedOnchain => { + f.write_str("settle_exact_failed_onchain") + } + Self::SettleExactSvmBlockHeightExceeded => { + f.write_str("settle_exact_svm_block_height_exceeded") + } + Self::SettleExactSvmTransactionConfirmationTimedOut => { + f.write_str("settle_exact_svm_transaction_confirmation_timed_out") + } Self::UnknownError => f.write_str("unknown_error"), } } } - impl ::std::str::FromStr for X402VerifyInvalidReason { + impl ::std::str::FromStr for X402SettleErrorReason { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { match value { @@ -60262,18 +66223,29 @@ pub mod types { "invalid_exact_svm_payload_transaction_fee_payer_transferring_funds" => { Ok(Self::InvalidExactSvmPayloadTransactionFeePayerTransferringFunds) } + "settle_exact_evm_transaction_confirmation_timed_out" => { + Ok(Self::SettleExactEvmTransactionConfirmationTimedOut) + } + "settle_exact_node_failure" => Ok(Self::SettleExactNodeFailure), + "settle_exact_failed_onchain" => Ok(Self::SettleExactFailedOnchain), + "settle_exact_svm_block_height_exceeded" => { + Ok(Self::SettleExactSvmBlockHeightExceeded) + } + "settle_exact_svm_transaction_confirmation_timed_out" => { + Ok(Self::SettleExactSvmTransactionConfirmationTimedOut) + } "unknown_error" => Ok(Self::UnknownError), _ => Err("invalid value".into()), } } } - impl ::std::convert::TryFrom<&str> for X402VerifyInvalidReason { + impl ::std::convert::TryFrom<&str> for X402SettleErrorReason { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for X402VerifyInvalidReason { + impl ::std::convert::TryFrom<&::std::string::String> for X402SettleErrorReason { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -60281,7 +66253,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for X402VerifyInvalidReason { + impl ::std::convert::TryFrom<::std::string::String> for X402SettleErrorReason { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -60289,43 +66261,42 @@ pub mod types { value.parse() } } - ///The result when x402 payment verification fails. + ///The result when x402 payment settlement fails. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The result when x402 payment verification fails.", + /// "description": "The result when x402 payment settlement fails.", /// "examples": [ /// { - /// "invalidMessage": "Insufficient funds", - /// "invalidReason": "insufficient_funds", - /// "isValid": false, - /// "payer": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// "errorReason": "insufficient_funds", + /// "payer": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "success": false /// } /// ], /// "type": "object", /// "required": [ - /// "invalidReason", - /// "isValid" + /// "errorReason", + /// "success" /// ], /// "properties": { - /// "invalidMessage": { - /// "description": "The message describing the invalid reason.", + /// "errorMessage": { + /// "description": "The message describing the error reason.", /// "examples": [ /// "Insufficient funds" /// ], /// "type": "string" /// }, - /// "invalidReason": { - /// "$ref": "#/components/schemas/x402VerifyInvalidReason" + /// "errorReason": { + /// "$ref": "#/components/schemas/x402SettleErrorReason" /// }, - /// "isValid": { - /// "description": "Indicates whether the payment is valid.", + /// "network": { + /// "description": "The network where the settlement occurred.", /// "examples": [ - /// false + /// "base" /// ], - /// "type": "boolean" + /// "type": "string" /// }, /// "payer": { /// "description": "The onchain address of the client that is paying for the resource.\n\nFor EVM networks, the payer will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, the payer will be a base58-encoded Solana address.", @@ -60334,40 +66305,62 @@ pub mod types { /// ], /// "type": "string", /// "pattern": "^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$" + /// }, + /// "success": { + /// "description": "Indicates whether the payment settlement is successful.", + /// "examples": [ + /// false + /// ], + /// "type": "boolean" + /// }, + /// "transaction": { + /// "description": "The transaction of the settlement.\nFor EVM networks, the transaction will be a 0x-prefixed, EVM transaction hash.\nFor Solana-based networks, the transaction will be a base58-encoded Solana signature.", + /// "examples": [ + /// "0x89c91c789e57059b17285e7ba1716a1f5ff4c5dace0ea5a5135f26158d0421b9" + /// ], + /// "type": "string", + /// "pattern": "^(0x[a-fA-F0-9]{64}|[1-9A-HJ-NP-Za-km-z]{87,88})$" /// } /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - pub struct X402VerifyPaymentRejection { - ///The message describing the invalid reason. + pub struct X402SettlePaymentRejection { + ///The message describing the error reason. #[serde( - rename = "invalidMessage", + rename = "errorMessage", default, skip_serializing_if = "::std::option::Option::is_none" )] - pub invalid_message: ::std::option::Option<::std::string::String>, - #[serde(rename = "invalidReason")] - pub invalid_reason: X402VerifyInvalidReason, - ///Indicates whether the payment is valid. - #[serde(rename = "isValid")] - pub is_valid: bool, + pub error_message: ::std::option::Option<::std::string::String>, + #[serde(rename = "errorReason")] + pub error_reason: X402SettleErrorReason, + ///The network where the settlement occurred. + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub network: ::std::option::Option<::std::string::String>, /**The onchain address of the client that is paying for the resource. For EVM networks, the payer will be a 0x-prefixed, checksum EVM address. For Solana-based networks, the payer will be a base58-encoded Solana address.*/ #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] - pub payer: ::std::option::Option, + pub payer: ::std::option::Option, + ///Indicates whether the payment settlement is successful. + pub success: bool, + /**The transaction of the settlement. + For EVM networks, the transaction will be a 0x-prefixed, EVM transaction hash. + For Solana-based networks, the transaction will be a base58-encoded Solana signature.*/ + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub transaction: ::std::option::Option, } - impl ::std::convert::From<&X402VerifyPaymentRejection> for X402VerifyPaymentRejection { - fn from(value: &X402VerifyPaymentRejection) -> Self { + impl ::std::convert::From<&X402SettlePaymentRejection> for X402SettlePaymentRejection { + fn from(value: &X402SettlePaymentRejection) -> Self { value.clone() } } - impl X402VerifyPaymentRejection { - pub fn builder() -> builder::X402VerifyPaymentRejection { + impl X402SettlePaymentRejection { + pub fn builder() -> builder::X402SettlePaymentRejection { Default::default() } } @@ -60392,24 +66385,24 @@ pub mod types { ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct X402VerifyPaymentRejectionPayer(::std::string::String); - impl ::std::ops::Deref for X402VerifyPaymentRejectionPayer { + pub struct X402SettlePaymentRejectionPayer(::std::string::String); + impl ::std::ops::Deref for X402SettlePaymentRejectionPayer { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: X402VerifyPaymentRejectionPayer) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: X402SettlePaymentRejectionPayer) -> Self { value.0 } } - impl ::std::convert::From<&X402VerifyPaymentRejectionPayer> for X402VerifyPaymentRejectionPayer { - fn from(value: &X402VerifyPaymentRejectionPayer) -> Self { + impl ::std::convert::From<&X402SettlePaymentRejectionPayer> for X402SettlePaymentRejectionPayer { + fn from(value: &X402SettlePaymentRejectionPayer) -> Self { value.clone() } } - impl ::std::str::FromStr for X402VerifyPaymentRejectionPayer { + impl ::std::str::FromStr for X402SettlePaymentRejectionPayer { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = @@ -60426,13 +66419,13 @@ pub mod types { Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for X402VerifyPaymentRejectionPayer { + impl ::std::convert::TryFrom<&str> for X402SettlePaymentRejectionPayer { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for X402VerifyPaymentRejectionPayer { + impl ::std::convert::TryFrom<&::std::string::String> for X402SettlePaymentRejectionPayer { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -60440,7 +66433,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for X402VerifyPaymentRejectionPayer { + impl ::std::convert::TryFrom<::std::string::String> for X402SettlePaymentRejectionPayer { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -60448,7 +66441,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for X402VerifyPaymentRejectionPayer { + impl<'de> ::serde::Deserialize<'de> for X402SettlePaymentRejectionPayer { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -60460,69 +66453,190 @@ pub mod types { }) } } - ///The version of the x402 protocol. + /**The transaction of the settlement. + For EVM networks, the transaction will be a 0x-prefixed, EVM transaction hash. + For Solana-based networks, the transaction will be a base58-encoded Solana signature.*/ /// ///
JSON schema /// /// ```json ///{ - /// "description": "The version of the x402 protocol.", + /// "description": "The transaction of the settlement.\nFor EVM networks, the transaction will be a 0x-prefixed, EVM transaction hash.\nFor Solana-based networks, the transaction will be a base58-encoded Solana signature.", /// "examples": [ - /// 2 + /// "0x89c91c789e57059b17285e7ba1716a1f5ff4c5dace0ea5a5135f26158d0421b9" /// ], - /// "type": "integer", - /// "enum": [ - /// 1, - /// 2 - /// ] + /// "type": "string", + /// "pattern": "^(0x[a-fA-F0-9]{64}|[1-9A-HJ-NP-Za-km-z]{87,88})$" ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug)] + #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct X402Version(i64); - impl ::std::ops::Deref for X402Version { - type Target = i64; - fn deref(&self) -> &i64 { + pub struct X402SettlePaymentRejectionTransaction(::std::string::String); + impl ::std::ops::Deref for X402SettlePaymentRejectionTransaction { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for i64 { - fn from(value: X402Version) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: X402SettlePaymentRejectionTransaction) -> Self { value.0 } } - impl ::std::convert::From<&X402Version> for X402Version { - fn from(value: &X402Version) -> Self { + impl ::std::convert::From<&X402SettlePaymentRejectionTransaction> + for X402SettlePaymentRejectionTransaction + { + fn from(value: &X402SettlePaymentRejectionTransaction) -> Self { value.clone() } } - impl ::std::convert::TryFrom for X402Version { - type Error = self::error::ConversionError; - fn try_from(value: i64) -> ::std::result::Result { - if ![1_i64, 2_i64].contains(&value) { - Err("invalid value".into()) - } else { - Ok(Self(value)) + impl ::std::str::FromStr for X402SettlePaymentRejectionTransaction { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^(0x[a-fA-F0-9]{64}|[1-9A-HJ-NP-Za-km-z]{87,88})$") + .unwrap() + }); + if PATTERN.find(value).is_none() { + return Err( + "doesn't match pattern \"^(0x[a-fA-F0-9]{64}|[1-9A-HJ-NP-Za-km-z]{87,88})$\"" + .into(), + ); } + Ok(Self(value.to_string())) } } - impl<'de> ::serde::Deserialize<'de> for X402Version { + impl ::std::convert::TryFrom<&str> for X402SettlePaymentRejectionTransaction { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for X402SettlePaymentRejectionTransaction { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for X402SettlePaymentRejectionTransaction { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for X402SettlePaymentRejectionTransaction { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, { - Self::try_from(::deserialize(deserializer)?) - .map_err(|e| ::custom(e.to_string())) + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) } } - ///The network of the blockchain to send payment on. + ///The supported payment kind for the x402 protocol. A kind is comprised of a scheme and a network, which together uniquely identify a way to move money on the x402 protocol. For more details, please see [x402 Schemes](https://github.com/coinbase/x402?tab=readme-ov-file#schemes). /// ///
JSON schema /// /// ```json ///{ - /// "description": "The network of the blockchain to send payment on.", + /// "description": "The supported payment kind for the x402 protocol. A kind is comprised of a scheme and a network, which together uniquely identify a way to move money on the x402 protocol. For more details, please see [x402 Schemes](https://github.com/coinbase/x402?tab=readme-ov-file#schemes).", + /// "type": "object", + /// "required": [ + /// "network", + /// "scheme", + /// "x402Version" + /// ], + /// "properties": { + /// "extra": { + /// "description": "The optional additional scheme-specific payment info.", + /// "examples": [ + /// { + /// "feePayer": "HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT" + /// } + /// ], + /// "type": "object", + /// "additionalProperties": true + /// }, + /// "network": { + /// "description": "The network of the blockchain.", + /// "examples": [ + /// "base" + /// ], + /// "type": "string", + /// "enum": [ + /// "base-sepolia", + /// "base", + /// "solana-devnet", + /// "solana", + /// "polygon", + /// "eip155:8453", + /// "eip155:84532", + /// "eip155:137", + /// "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp", + /// "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", + /// "avalanche", + /// "arbitrum", + /// "arbitrum-sepolia", + /// "world", + /// "world-sepolia" + /// ] + /// }, + /// "scheme": { + /// "description": "The scheme of the payment protocol.", + /// "examples": [ + /// "exact" + /// ], + /// "type": "string", + /// "enum": [ + /// "exact", + /// "upto" + /// ] + /// }, + /// "x402Version": { + /// "$ref": "#/components/schemas/X402Version" + /// } + /// } + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct X402SupportedPaymentKind { + ///The optional additional scheme-specific payment info. + #[serde(default, skip_serializing_if = "::serde_json::Map::is_empty")] + pub extra: ::serde_json::Map<::std::string::String, ::serde_json::Value>, + ///The network of the blockchain. + pub network: X402SupportedPaymentKindNetwork, + ///The scheme of the payment protocol. + pub scheme: X402SupportedPaymentKindScheme, + #[serde(rename = "x402Version")] + pub x402_version: X402Version, + } + impl ::std::convert::From<&X402SupportedPaymentKind> for X402SupportedPaymentKind { + fn from(value: &X402SupportedPaymentKind) -> Self { + value.clone() + } + } + impl X402SupportedPaymentKind { + pub fn builder() -> builder::X402SupportedPaymentKind { + Default::default() + } + } + ///The network of the blockchain. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The network of the blockchain.", /// "examples": [ /// "base" /// ], @@ -60532,7 +66646,17 @@ pub mod types { /// "base", /// "solana-devnet", /// "solana", - /// "polygon" + /// "polygon", + /// "eip155:8453", + /// "eip155:84532", + /// "eip155:137", + /// "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp", + /// "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", + /// "avalanche", + /// "arbitrum", + /// "arbitrum-sepolia", + /// "world", + /// "world-sepolia" /// ] ///} /// ``` @@ -60549,7 +66673,7 @@ pub mod types { PartialEq, PartialOrd, )] - pub enum X402v1PaymentPayloadNetwork { + pub enum X402SupportedPaymentKindNetwork { #[serde(rename = "base-sepolia")] BaseSepolia, #[serde(rename = "base")] @@ -60560,13 +66684,33 @@ pub mod types { Solana, #[serde(rename = "polygon")] Polygon, + #[serde(rename = "eip155:8453")] + Eip1558453, + #[serde(rename = "eip155:84532")] + Eip15584532, + #[serde(rename = "eip155:137")] + Eip155137, + #[serde(rename = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp")] + Solana5eykt4UsFv8P8nJdTrEpY1vzqKqZKvdp, + #[serde(rename = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1")] + SolanaEtWtrabZaYq6iMfeYKouRu166Vu2xqa1, + #[serde(rename = "avalanche")] + Avalanche, + #[serde(rename = "arbitrum")] + Arbitrum, + #[serde(rename = "arbitrum-sepolia")] + ArbitrumSepolia, + #[serde(rename = "world")] + World, + #[serde(rename = "world-sepolia")] + WorldSepolia, } - impl ::std::convert::From<&Self> for X402v1PaymentPayloadNetwork { - fn from(value: &X402v1PaymentPayloadNetwork) -> Self { + impl ::std::convert::From<&Self> for X402SupportedPaymentKindNetwork { + fn from(value: &X402SupportedPaymentKindNetwork) -> Self { value.clone() } } - impl ::std::fmt::Display for X402v1PaymentPayloadNetwork { + impl ::std::fmt::Display for X402SupportedPaymentKindNetwork { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match *self { Self::BaseSepolia => f.write_str("base-sepolia"), @@ -60574,10 +66718,24 @@ pub mod types { Self::SolanaDevnet => f.write_str("solana-devnet"), Self::Solana => f.write_str("solana"), Self::Polygon => f.write_str("polygon"), + Self::Eip1558453 => f.write_str("eip155:8453"), + Self::Eip15584532 => f.write_str("eip155:84532"), + Self::Eip155137 => f.write_str("eip155:137"), + Self::Solana5eykt4UsFv8P8nJdTrEpY1vzqKqZKvdp => { + f.write_str("solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp") + } + Self::SolanaEtWtrabZaYq6iMfeYKouRu166Vu2xqa1 => { + f.write_str("solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1") + } + Self::Avalanche => f.write_str("avalanche"), + Self::Arbitrum => f.write_str("arbitrum"), + Self::ArbitrumSepolia => f.write_str("arbitrum-sepolia"), + Self::World => f.write_str("world"), + Self::WorldSepolia => f.write_str("world-sepolia"), } } } - impl ::std::str::FromStr for X402v1PaymentPayloadNetwork { + impl ::std::str::FromStr for X402SupportedPaymentKindNetwork { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { match value { @@ -60586,17 +66744,31 @@ pub mod types { "solana-devnet" => Ok(Self::SolanaDevnet), "solana" => Ok(Self::Solana), "polygon" => Ok(Self::Polygon), + "eip155:8453" => Ok(Self::Eip1558453), + "eip155:84532" => Ok(Self::Eip15584532), + "eip155:137" => Ok(Self::Eip155137), + "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp" => { + Ok(Self::Solana5eykt4UsFv8P8nJdTrEpY1vzqKqZKvdp) + } + "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1" => { + Ok(Self::SolanaEtWtrabZaYq6iMfeYKouRu166Vu2xqa1) + } + "avalanche" => Ok(Self::Avalanche), + "arbitrum" => Ok(Self::Arbitrum), + "arbitrum-sepolia" => Ok(Self::ArbitrumSepolia), + "world" => Ok(Self::World), + "world-sepolia" => Ok(Self::WorldSepolia), _ => Err("invalid value".into()), } } } - impl ::std::convert::TryFrom<&str> for X402v1PaymentPayloadNetwork { + impl ::std::convert::TryFrom<&str> for X402SupportedPaymentKindNetwork { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for X402v1PaymentPayloadNetwork { + impl ::std::convert::TryFrom<&::std::string::String> for X402SupportedPaymentKindNetwork { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -60604,7 +66776,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for X402v1PaymentPayloadNetwork { + impl ::std::convert::TryFrom<::std::string::String> for X402SupportedPaymentKindNetwork { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -60612,81 +66784,20 @@ pub mod types { value.parse() } } - ///The payload of the payment depending on the x402Version, scheme, and network. - /// - ///
JSON schema - /// - /// ```json - ///{ - /// "description": "The payload of the payment depending on the x402Version, scheme, and network.", - /// "examples": [ - /// { - /// "authorization": { - /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "nonce": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", - /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "validAfter": "1716150000", - /// "validBefore": "1716150000", - /// "value": "1000000000000000000" - /// }, - /// "signature": "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" - /// } - /// ], - /// "type": "object", - /// "oneOf": [ - /// { - /// "$ref": "#/components/schemas/x402ExactEvmPayload" - /// }, - /// { - /// "$ref": "#/components/schemas/x402ExactEvmPermit2Payload" - /// }, - /// { - /// "$ref": "#/components/schemas/x402ExactSolanaPayload" - /// } - /// ] - ///} - /// ``` - ///
- #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - #[serde(untagged)] - pub enum X402v1PaymentPayloadPayload { - EvmPayload(X402ExactEvmPayload), - EvmPermit2Payload(X402ExactEvmPermit2Payload), - SolanaPayload(X402ExactSolanaPayload), - } - impl ::std::convert::From<&Self> for X402v1PaymentPayloadPayload { - fn from(value: &X402v1PaymentPayloadPayload) -> Self { - value.clone() - } - } - impl ::std::convert::From for X402v1PaymentPayloadPayload { - fn from(value: X402ExactEvmPayload) -> Self { - Self::EvmPayload(value) - } - } - impl ::std::convert::From for X402v1PaymentPayloadPayload { - fn from(value: X402ExactEvmPermit2Payload) -> Self { - Self::EvmPermit2Payload(value) - } - } - impl ::std::convert::From for X402v1PaymentPayloadPayload { - fn from(value: X402ExactSolanaPayload) -> Self { - Self::SolanaPayload(value) - } - } - ///The scheme of the payment protocol to use. Currently, the only supported scheme is `exact`. + ///The scheme of the payment protocol. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The scheme of the payment protocol to use. Currently, the only supported scheme is `exact`.", + /// "description": "The scheme of the payment protocol.", /// "examples": [ /// "exact" /// ], /// "type": "string", /// "enum": [ - /// "exact" + /// "exact", + /// "upto" /// ] ///} /// ``` @@ -60703,38 +66814,42 @@ pub mod types { PartialEq, PartialOrd, )] - pub enum X402v1PaymentPayloadScheme { + pub enum X402SupportedPaymentKindScheme { #[serde(rename = "exact")] Exact, + #[serde(rename = "upto")] + Upto, } - impl ::std::convert::From<&Self> for X402v1PaymentPayloadScheme { - fn from(value: &X402v1PaymentPayloadScheme) -> Self { + impl ::std::convert::From<&Self> for X402SupportedPaymentKindScheme { + fn from(value: &X402SupportedPaymentKindScheme) -> Self { value.clone() } } - impl ::std::fmt::Display for X402v1PaymentPayloadScheme { + impl ::std::fmt::Display for X402SupportedPaymentKindScheme { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match *self { Self::Exact => f.write_str("exact"), + Self::Upto => f.write_str("upto"), } } } - impl ::std::str::FromStr for X402v1PaymentPayloadScheme { + impl ::std::str::FromStr for X402SupportedPaymentKindScheme { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { match value { "exact" => Ok(Self::Exact), + "upto" => Ok(Self::Upto), _ => Err("invalid value".into()), } } } - impl ::std::convert::TryFrom<&str> for X402v1PaymentPayloadScheme { + impl ::std::convert::TryFrom<&str> for X402SupportedPaymentKindScheme { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for X402v1PaymentPayloadScheme { + impl ::std::convert::TryFrom<&::std::string::String> for X402SupportedPaymentKindScheme { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -60742,7 +66857,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for X402v1PaymentPayloadScheme { + impl ::std::convert::TryFrom<::std::string::String> for X402SupportedPaymentKindScheme { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -60750,300 +66865,604 @@ pub mod types { value.parse() } } - /**The asset to pay with. - - For EVM networks, the asset will be a 0x-prefixed, checksum EVM address. - - For Solana-based networks, the asset will be a base58-encoded Solana address.*/ + ///The x402 protocol payment payload that the client attaches to x402-paid API requests to the resource server in the X-PAYMENT header. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The asset to pay with.\n\nFor EVM networks, the asset will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, the asset will be a base58-encoded Solana address.", + /// "description": "The x402 protocol payment payload that the client attaches to x402-paid API requests to the resource server in the X-PAYMENT header.", /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// { + /// "network": "base", + /// "payload": { + /// "authorization": { + /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "nonce": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", + /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "validAfter": "1716150000", + /// "validBefore": "1716150000", + /// "value": "1000000000000000000" + /// }, + /// "signature": "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" + /// }, + /// "scheme": "exact", + /// "x402Version": 1 + /// } /// ], - /// "type": "string", - /// "pattern": "^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$" + /// "type": "object", + /// "required": [ + /// "network", + /// "payload", + /// "scheme", + /// "x402Version" + /// ], + /// "properties": { + /// "network": { + /// "description": "The network of the blockchain to send payment on.", + /// "examples": [ + /// "base" + /// ], + /// "type": "string", + /// "enum": [ + /// "base-sepolia", + /// "base", + /// "solana-devnet", + /// "solana", + /// "polygon" + /// ] + /// }, + /// "payload": { + /// "description": "The payload of the payment depending on the x402Version, scheme, and network.", + /// "examples": [ + /// { + /// "authorization": { + /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "nonce": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", + /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "validAfter": "1716150000", + /// "validBefore": "1716150000", + /// "value": "1000000000000000000" + /// }, + /// "signature": "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" + /// } + /// ], + /// "type": "object", + /// "oneOf": [ + /// { + /// "$ref": "#/components/schemas/x402ExactEvmPayload" + /// }, + /// { + /// "$ref": "#/components/schemas/x402ExactEvmPermit2Payload" + /// }, + /// { + /// "$ref": "#/components/schemas/x402ExactSolanaPayload" + /// } + /// ] + /// }, + /// "scheme": { + /// "description": "The scheme of the payment protocol to use. Currently, the only supported scheme is `exact`.", + /// "examples": [ + /// "exact" + /// ], + /// "type": "string", + /// "enum": [ + /// "exact" + /// ] + /// }, + /// "x402Version": { + /// "$ref": "#/components/schemas/X402Version" + /// } + /// } ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct X402v1PaymentRequirementsAsset(::std::string::String); - impl ::std::ops::Deref for X402v1PaymentRequirementsAsset { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } - } - impl ::std::convert::From for ::std::string::String { - fn from(value: X402v1PaymentRequirementsAsset) -> Self { - value.0 - } + #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct X402V1PaymentPayload { + ///The network of the blockchain to send payment on. + pub network: X402v1PaymentPayloadNetwork, + ///The payload of the payment depending on the x402Version, scheme, and network. + pub payload: X402v1PaymentPayloadPayload, + ///The scheme of the payment protocol to use. Currently, the only supported scheme is `exact`. + pub scheme: X402v1PaymentPayloadScheme, + #[serde(rename = "x402Version")] + pub x402_version: X402Version, } - impl ::std::convert::From<&X402v1PaymentRequirementsAsset> for X402v1PaymentRequirementsAsset { - fn from(value: &X402v1PaymentRequirementsAsset) -> Self { + impl ::std::convert::From<&X402V1PaymentPayload> for X402V1PaymentPayload { + fn from(value: &X402V1PaymentPayload) -> Self { value.clone() } } - impl ::std::str::FromStr for X402v1PaymentRequirementsAsset { - type Err = self::error::ConversionError; - fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$") - .unwrap() - }); - if PATTERN.find(value).is_none() { - return Err( - "doesn't match pattern \"^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$\"" - .into(), - ); - } - Ok(Self(value.to_string())) - } - } - impl ::std::convert::TryFrom<&str> for X402v1PaymentRequirementsAsset { - type Error = self::error::ConversionError; - fn try_from(value: &str) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<&::std::string::String> for X402v1PaymentRequirementsAsset { - type Error = self::error::ConversionError; - fn try_from( - value: &::std::string::String, - ) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<::std::string::String> for X402v1PaymentRequirementsAsset { - type Error = self::error::ConversionError; - fn try_from( - value: ::std::string::String, - ) -> ::std::result::Result { - value.parse() + impl X402V1PaymentPayload { + pub fn builder() -> builder::X402V1PaymentPayload { + Default::default() } } - impl<'de> ::serde::Deserialize<'de> for X402v1PaymentRequirementsAsset { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) - } - } - ///The network of the blockchain to send payment on. + ///The x402 protocol payment requirements that the resource server expects the client's payment payload to meet. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The network of the blockchain to send payment on.", - /// "examples": [ - /// "base" + /// "description": "The x402 protocol payment requirements that the resource server expects the client's payment payload to meet.", + /// "type": "object", + /// "required": [ + /// "asset", + /// "description", + /// "maxAmountRequired", + /// "maxTimeoutSeconds", + /// "mimeType", + /// "network", + /// "payTo", + /// "resource", + /// "scheme" /// ], - /// "type": "string", - /// "enum": [ - /// "base-sepolia", - /// "base", - /// "solana-devnet", - /// "solana", - /// "polygon" - /// ] + /// "properties": { + /// "asset": { + /// "description": "The asset to pay with.\n\nFor EVM networks, the asset will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, the asset will be a base58-encoded Solana address.", + /// "examples": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ], + /// "type": "string", + /// "pattern": "^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$" + /// }, + /// "description": { + /// "description": "A human-readable description of the resource.", + /// "examples": [ + /// "Premium API access for data analysis" + /// ], + /// "allOf": [ + /// { + /// "$ref": "#/components/schemas/Description" + /// } + /// ] + /// }, + /// "extra": { + /// "description": "The optional additional scheme-specific payment info.", + /// "examples": [ + /// { + /// "gasLimit": "1000000" + /// } + /// ], + /// "type": "object", + /// "additionalProperties": true + /// }, + /// "maxAmountRequired": { + /// "description": "The maximum amount required to pay for the resource in atomic units of the payment asset.", + /// "examples": [ + /// "1000000" + /// ], + /// "type": "string" + /// }, + /// "maxTimeoutSeconds": { + /// "description": "The maximum time in seconds for the resource server to respond.", + /// "examples": [ + /// 10 + /// ], + /// "type": "integer" + /// }, + /// "mimeType": { + /// "description": "The MIME type of the resource response.", + /// "examples": [ + /// "application/json" + /// ], + /// "type": "string" + /// }, + /// "network": { + /// "description": "The network of the blockchain to send payment on.", + /// "examples": [ + /// "base" + /// ], + /// "type": "string", + /// "enum": [ + /// "base-sepolia", + /// "base", + /// "solana-devnet", + /// "solana", + /// "polygon" + /// ] + /// }, + /// "outputSchema": { + /// "description": "The optional JSON schema describing the resource output.", + /// "examples": [ + /// { + /// "data": "string" + /// } + /// ], + /// "type": "object", + /// "additionalProperties": true + /// }, + /// "payTo": { + /// "description": "The destination to pay value to.\n\nFor EVM networks, payTo will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, payTo will be a base58-encoded Solana address.", + /// "examples": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ], + /// "type": "string", + /// "pattern": "^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$" + /// }, + /// "resource": { + /// "description": "The URL of the resource to pay for.", + /// "examples": [ + /// "https://api.example.com/premium/resource/123" + /// ], + /// "type": "string" + /// }, + /// "scheme": { + /// "description": "The scheme of the payment protocol to use. Currently, the only supported scheme is `exact`.", + /// "examples": [ + /// "exact" + /// ], + /// "type": "string", + /// "enum": [ + /// "exact" + /// ] + /// } + /// } ///} /// ``` ///
- #[derive( - ::serde::Deserialize, - ::serde::Serialize, - Clone, - Copy, - Debug, - Eq, - Hash, - Ord, - PartialEq, - PartialOrd, - )] - pub enum X402v1PaymentRequirementsNetwork { - #[serde(rename = "base-sepolia")] - BaseSepolia, - #[serde(rename = "base")] - Base, - #[serde(rename = "solana-devnet")] - SolanaDevnet, - #[serde(rename = "solana")] - Solana, - #[serde(rename = "polygon")] - Polygon, + #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct X402V1PaymentRequirements { + /**The asset to pay with. + + For EVM networks, the asset will be a 0x-prefixed, checksum EVM address. + + For Solana-based networks, the asset will be a base58-encoded Solana address.*/ + pub asset: X402v1PaymentRequirementsAsset, + ///A human-readable description of the resource. + pub description: Description, + ///The optional additional scheme-specific payment info. + #[serde(default, skip_serializing_if = "::serde_json::Map::is_empty")] + pub extra: ::serde_json::Map<::std::string::String, ::serde_json::Value>, + ///The maximum amount required to pay for the resource in atomic units of the payment asset. + #[serde(rename = "maxAmountRequired")] + pub max_amount_required: ::std::string::String, + ///The maximum time in seconds for the resource server to respond. + #[serde(rename = "maxTimeoutSeconds")] + pub max_timeout_seconds: i64, + ///The MIME type of the resource response. + #[serde(rename = "mimeType")] + pub mime_type: ::std::string::String, + ///The network of the blockchain to send payment on. + pub network: X402v1PaymentRequirementsNetwork, + ///The optional JSON schema describing the resource output. + #[serde( + rename = "outputSchema", + default, + skip_serializing_if = "::serde_json::Map::is_empty" + )] + pub output_schema: ::serde_json::Map<::std::string::String, ::serde_json::Value>, + /**The destination to pay value to. + + For EVM networks, payTo will be a 0x-prefixed, checksum EVM address. + + For Solana-based networks, payTo will be a base58-encoded Solana address.*/ + #[serde(rename = "payTo")] + pub pay_to: X402v1PaymentRequirementsPayTo, + ///The URL of the resource to pay for. + pub resource: ::std::string::String, + ///The scheme of the payment protocol to use. Currently, the only supported scheme is `exact`. + pub scheme: X402v1PaymentRequirementsScheme, } - impl ::std::convert::From<&Self> for X402v1PaymentRequirementsNetwork { - fn from(value: &X402v1PaymentRequirementsNetwork) -> Self { + impl ::std::convert::From<&X402V1PaymentRequirements> for X402V1PaymentRequirements { + fn from(value: &X402V1PaymentRequirements) -> Self { value.clone() } } - impl ::std::fmt::Display for X402v1PaymentRequirementsNetwork { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - match *self { - Self::BaseSepolia => f.write_str("base-sepolia"), - Self::Base => f.write_str("base"), - Self::SolanaDevnet => f.write_str("solana-devnet"), - Self::Solana => f.write_str("solana"), - Self::Polygon => f.write_str("polygon"), - } - } - } - impl ::std::str::FromStr for X402v1PaymentRequirementsNetwork { - type Err = self::error::ConversionError; - fn from_str(value: &str) -> ::std::result::Result { - match value { - "base-sepolia" => Ok(Self::BaseSepolia), - "base" => Ok(Self::Base), - "solana-devnet" => Ok(Self::SolanaDevnet), - "solana" => Ok(Self::Solana), - "polygon" => Ok(Self::Polygon), - _ => Err("invalid value".into()), - } - } - } - impl ::std::convert::TryFrom<&str> for X402v1PaymentRequirementsNetwork { - type Error = self::error::ConversionError; - fn try_from(value: &str) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<&::std::string::String> for X402v1PaymentRequirementsNetwork { - type Error = self::error::ConversionError; - fn try_from( - value: &::std::string::String, - ) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<::std::string::String> for X402v1PaymentRequirementsNetwork { - type Error = self::error::ConversionError; - fn try_from( - value: ::std::string::String, - ) -> ::std::result::Result { - value.parse() + impl X402V1PaymentRequirements { + pub fn builder() -> builder::X402V1PaymentRequirements { + Default::default() } } - /**The destination to pay value to. - - For EVM networks, payTo will be a 0x-prefixed, checksum EVM address. - - For Solana-based networks, payTo will be a base58-encoded Solana address.*/ + ///The x402 protocol payment payload that the client attaches to x402-paid API requests to the resource server in the X-PAYMENT header. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The destination to pay value to.\n\nFor EVM networks, payTo will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, payTo will be a base58-encoded Solana address.", + /// "description": "The x402 protocol payment payload that the client attaches to x402-paid API requests to the resource server in the X-PAYMENT header.", /// "examples": [ - /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// { + /// "accepted": { + /// "amount": "1000", + /// "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + /// "extra": { + /// "name": "USDC", + /// "version": "2" + /// }, + /// "maxTimeoutSeconds": 60, + /// "network": "eip155:84532", + /// "payTo": "0x122F8Fcaf2152420445Aa424E1D8C0306935B5c9", + /// "scheme": "exact" + /// }, + /// "payload": { + /// "authorization": { + /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "nonce": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", + /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "validAfter": "1716150000", + /// "validBefore": "1716150000", + /// "value": "1000000000000000000" + /// }, + /// "signature": "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" + /// }, + /// "resource": { + /// "description": "Premium API access for data analysis.", + /// "mimeType": "application/json", + /// "url": "https://api.example.com/premium/resource/123" + /// }, + /// "x402Version": 2 + /// } /// ], - /// "type": "string", - /// "pattern": "^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$" + /// "type": "object", + /// "required": [ + /// "accepted", + /// "payload", + /// "x402Version" + /// ], + /// "properties": { + /// "accepted": { + /// "$ref": "#/components/schemas/x402V2PaymentRequirements" + /// }, + /// "extensions": { + /// "description": "Optional protocol extensions.", + /// "examples": [ + /// { + /// "bazaar": { + /// "info": { + /// "input": { + /// "method": "GET", + /// "type": "http" + /// } + /// }, + /// "schema": {} + /// } + /// } + /// ], + /// "type": "object", + /// "additionalProperties": true + /// }, + /// "payload": { + /// "description": "The payload of the payment depending on the x402Version, scheme, and network.", + /// "examples": [ + /// { + /// "authorization": { + /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "nonce": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", + /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "validAfter": "1716150000", + /// "validBefore": "1716150000", + /// "value": "1000000000000000000" + /// }, + /// "signature": "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" + /// } + /// ], + /// "type": "object", + /// "oneOf": [ + /// { + /// "$ref": "#/components/schemas/x402ExactEvmPayload" + /// }, + /// { + /// "$ref": "#/components/schemas/x402ExactEvmPermit2Payload" + /// }, + /// { + /// "$ref": "#/components/schemas/x402ExactSolanaPayload" + /// } + /// ] + /// }, + /// "resource": { + /// "$ref": "#/components/schemas/x402ResourceInfo" + /// }, + /// "x402Version": { + /// "$ref": "#/components/schemas/X402Version" + /// } + /// } ///} /// ``` ///
- #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] - #[serde(transparent)] - pub struct X402v1PaymentRequirementsPayTo(::std::string::String); - impl ::std::ops::Deref for X402v1PaymentRequirementsPayTo { - type Target = ::std::string::String; - fn deref(&self) -> &::std::string::String { - &self.0 - } - } - impl ::std::convert::From for ::std::string::String { - fn from(value: X402v1PaymentRequirementsPayTo) -> Self { - value.0 - } + #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct X402V2PaymentPayload { + pub accepted: X402V2PaymentRequirements, + ///Optional protocol extensions. + #[serde(default, skip_serializing_if = "::serde_json::Map::is_empty")] + pub extensions: ::serde_json::Map<::std::string::String, ::serde_json::Value>, + ///The payload of the payment depending on the x402Version, scheme, and network. + pub payload: X402v2PaymentPayloadPayload, + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub resource: ::std::option::Option, + #[serde(rename = "x402Version")] + pub x402_version: X402Version, } - impl ::std::convert::From<&X402v1PaymentRequirementsPayTo> for X402v1PaymentRequirementsPayTo { - fn from(value: &X402v1PaymentRequirementsPayTo) -> Self { + impl ::std::convert::From<&X402V2PaymentPayload> for X402V2PaymentPayload { + fn from(value: &X402V2PaymentPayload) -> Self { value.clone() } } - impl ::std::str::FromStr for X402v1PaymentRequirementsPayTo { - type Err = self::error::ConversionError; - fn from_str(value: &str) -> ::std::result::Result { - static PATTERN: ::std::sync::LazyLock<::regress::Regex> = - ::std::sync::LazyLock::new(|| { - ::regress::Regex::new("^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$") - .unwrap() - }); - if PATTERN.find(value).is_none() { - return Err( - "doesn't match pattern \"^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$\"" - .into(), - ); - } - Ok(Self(value.to_string())) - } - } - impl ::std::convert::TryFrom<&str> for X402v1PaymentRequirementsPayTo { - type Error = self::error::ConversionError; - fn try_from(value: &str) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<&::std::string::String> for X402v1PaymentRequirementsPayTo { - type Error = self::error::ConversionError; - fn try_from( - value: &::std::string::String, - ) -> ::std::result::Result { - value.parse() - } - } - impl ::std::convert::TryFrom<::std::string::String> for X402v1PaymentRequirementsPayTo { - type Error = self::error::ConversionError; - fn try_from( - value: ::std::string::String, - ) -> ::std::result::Result { - value.parse() - } - } - impl<'de> ::serde::Deserialize<'de> for X402v1PaymentRequirementsPayTo { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - ::std::string::String::deserialize(deserializer)? - .parse() - .map_err(|e: self::error::ConversionError| { - ::custom(e.to_string()) - }) + impl X402V2PaymentPayload { + pub fn builder() -> builder::X402V2PaymentPayload { + Default::default() } } - ///The scheme of the payment protocol to use. Currently, the only supported scheme is `exact`. + ///The x402 protocol payment requirements that the resource server expects the client's payment payload to meet. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The scheme of the payment protocol to use. Currently, the only supported scheme is `exact`.", - /// "examples": [ - /// "exact" + /// "description": "The x402 protocol payment requirements that the resource server expects the client's payment payload to meet.", + /// "type": "object", + /// "required": [ + /// "amount", + /// "asset", + /// "maxTimeoutSeconds", + /// "network", + /// "payTo", + /// "scheme" /// ], - /// "type": "string", - /// "enum": [ - /// "exact" - /// ] + /// "properties": { + /// "amount": { + /// "description": "The amount to pay for the resource in atomic units of the payment asset.", + /// "examples": [ + /// "1000000" + /// ], + /// "type": "string" + /// }, + /// "asset": { + /// "description": "The asset to pay with.\n\nFor EVM networks, the asset will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, the asset will be a base58-encoded Solana address.", + /// "examples": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ], + /// "type": "string", + /// "pattern": "^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$" + /// }, + /// "extra": { + /// "description": "The optional additional scheme-specific payment info.", + /// "examples": [ + /// { + /// "name": "USDC", + /// "version": "2" + /// } + /// ], + /// "type": "object", + /// "additionalProperties": true + /// }, + /// "maxTimeoutSeconds": { + /// "description": "The maximum time in seconds for the resource server to respond.", + /// "examples": [ + /// 10 + /// ], + /// "type": "integer" + /// }, + /// "network": { + /// "description": "The network of the blockchain to send payment on in caip2 format.", + /// "examples": [ + /// "eip155:1" + /// ], + /// "type": "string" + /// }, + /// "payTo": { + /// "description": "The destination to pay value to.\n\nFor EVM networks, payTo will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, payTo will be a base58-encoded Solana address.", + /// "examples": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ], + /// "type": "string", + /// "pattern": "^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$" + /// }, + /// "scheme": { + /// "description": "The scheme of the payment protocol to use. Supported schemes are `exact` and `upto`.", + /// "examples": [ + /// "exact" + /// ], + /// "type": "string", + /// "enum": [ + /// "exact", + /// "upto" + /// ] + /// } + /// } ///} /// ``` ///
- #[derive( - ::serde::Deserialize, - ::serde::Serialize, + #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + pub struct X402V2PaymentRequirements { + ///The amount to pay for the resource in atomic units of the payment asset. + pub amount: ::std::string::String, + /**The asset to pay with. + + For EVM networks, the asset will be a 0x-prefixed, checksum EVM address. + + For Solana-based networks, the asset will be a base58-encoded Solana address.*/ + pub asset: X402v2PaymentRequirementsAsset, + ///The optional additional scheme-specific payment info. + #[serde(default, skip_serializing_if = "::serde_json::Map::is_empty")] + pub extra: ::serde_json::Map<::std::string::String, ::serde_json::Value>, + ///The maximum time in seconds for the resource server to respond. + #[serde(rename = "maxTimeoutSeconds")] + pub max_timeout_seconds: i64, + ///The network of the blockchain to send payment on in caip2 format. + pub network: ::std::string::String, + /**The destination to pay value to. + + For EVM networks, payTo will be a 0x-prefixed, checksum EVM address. + + For Solana-based networks, payTo will be a base58-encoded Solana address.*/ + #[serde(rename = "payTo")] + pub pay_to: X402v2PaymentRequirementsPayTo, + ///The scheme of the payment protocol to use. Supported schemes are `exact` and `upto`. + pub scheme: X402v2PaymentRequirementsScheme, + } + impl ::std::convert::From<&X402V2PaymentRequirements> for X402V2PaymentRequirements { + fn from(value: &X402V2PaymentRequirements) -> Self { + value.clone() + } + } + impl X402V2PaymentRequirements { + pub fn builder() -> builder::X402V2PaymentRequirements { + Default::default() + } + } + ///The reason the payment is invalid on the x402 protocol. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The reason the payment is invalid on the x402 protocol.", + /// "examples": [ + /// "insufficient_funds" + /// ], + /// "type": "string", + /// "enum": [ + /// "insufficient_funds", + /// "invalid_scheme", + /// "invalid_network", + /// "invalid_x402_version", + /// "invalid_payment_requirements", + /// "invalid_payload", + /// "invalid_exact_evm_payload_authorization_value", + /// "invalid_exact_evm_payload_authorization_value_too_low", + /// "invalid_exact_evm_payload_authorization_valid_after", + /// "invalid_exact_evm_payload_authorization_valid_before", + /// "invalid_exact_evm_payload_authorization_typed_data_message", + /// "invalid_exact_evm_payload_authorization_from_address_kyt", + /// "invalid_exact_evm_payload_authorization_to_address_kyt", + /// "invalid_exact_evm_payload_signature", + /// "invalid_exact_evm_payload_signature_address", + /// "invalid_exact_evm_permit2_payload_allowance_required", + /// "invalid_exact_evm_permit2_payload_signature", + /// "invalid_exact_evm_permit2_payload_deadline", + /// "invalid_exact_evm_permit2_payload_valid_after", + /// "invalid_exact_evm_permit2_payload_spender", + /// "invalid_exact_evm_permit2_payload_recipient", + /// "invalid_exact_evm_permit2_payload_amount", + /// "invalid_exact_svm_payload_transaction", + /// "invalid_exact_svm_payload_transaction_amount_mismatch", + /// "invalid_exact_svm_payload_transaction_create_ata_instruction", + /// "invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_payee", + /// "invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_asset", + /// "invalid_exact_svm_payload_transaction_instructions", + /// "invalid_exact_svm_payload_transaction_instructions_length", + /// "invalid_exact_svm_payload_transaction_instructions_compute_limit_instruction", + /// "invalid_exact_svm_payload_transaction_instructions_compute_price_instruction", + /// "invalid_exact_svm_payload_transaction_instructions_compute_price_instruction_too_high", + /// "invalid_exact_svm_payload_transaction_instruction_not_spl_token_transfer_checked", + /// "invalid_exact_svm_payload_transaction_instruction_not_token_2022_transfer_checked", + /// "invalid_exact_svm_payload_transaction_not_a_transfer_instruction", + /// "invalid_exact_svm_payload_transaction_cannot_derive_receiver_ata", + /// "invalid_exact_svm_payload_transaction_receiver_ata_not_found", + /// "invalid_exact_svm_payload_transaction_sender_ata_not_found", + /// "invalid_exact_svm_payload_transaction_simulation_failed", + /// "invalid_exact_svm_payload_transaction_transfer_to_incorrect_ata", + /// "invalid_exact_svm_payload_transaction_fee_payer_included_in_instruction_accounts", + /// "invalid_exact_svm_payload_transaction_fee_payer_transferring_funds", + /// "unknown_error" + /// ] + ///} + /// ``` + ///
+ #[derive( + ::serde::Deserialize, + ::serde::Serialize, Clone, Copy, Debug, @@ -61053,38 +67472,422 @@ pub mod types { PartialEq, PartialOrd, )] - pub enum X402v1PaymentRequirementsScheme { - #[serde(rename = "exact")] - Exact, + pub enum X402VerifyInvalidReason { + #[serde(rename = "insufficient_funds")] + InsufficientFunds, + #[serde(rename = "invalid_scheme")] + InvalidScheme, + #[serde(rename = "invalid_network")] + InvalidNetwork, + #[serde(rename = "invalid_x402_version")] + InvalidX402Version, + #[serde(rename = "invalid_payment_requirements")] + InvalidPaymentRequirements, + #[serde(rename = "invalid_payload")] + InvalidPayload, + #[serde(rename = "invalid_exact_evm_payload_authorization_value")] + InvalidExactEvmPayloadAuthorizationValue, + #[serde(rename = "invalid_exact_evm_payload_authorization_value_too_low")] + InvalidExactEvmPayloadAuthorizationValueTooLow, + #[serde(rename = "invalid_exact_evm_payload_authorization_valid_after")] + InvalidExactEvmPayloadAuthorizationValidAfter, + #[serde(rename = "invalid_exact_evm_payload_authorization_valid_before")] + InvalidExactEvmPayloadAuthorizationValidBefore, + #[serde(rename = "invalid_exact_evm_payload_authorization_typed_data_message")] + InvalidExactEvmPayloadAuthorizationTypedDataMessage, + #[serde(rename = "invalid_exact_evm_payload_authorization_from_address_kyt")] + InvalidExactEvmPayloadAuthorizationFromAddressKyt, + #[serde(rename = "invalid_exact_evm_payload_authorization_to_address_kyt")] + InvalidExactEvmPayloadAuthorizationToAddressKyt, + #[serde(rename = "invalid_exact_evm_payload_signature")] + InvalidExactEvmPayloadSignature, + #[serde(rename = "invalid_exact_evm_payload_signature_address")] + InvalidExactEvmPayloadSignatureAddress, + #[serde(rename = "invalid_exact_evm_permit2_payload_allowance_required")] + InvalidExactEvmPermit2PayloadAllowanceRequired, + #[serde(rename = "invalid_exact_evm_permit2_payload_signature")] + InvalidExactEvmPermit2PayloadSignature, + #[serde(rename = "invalid_exact_evm_permit2_payload_deadline")] + InvalidExactEvmPermit2PayloadDeadline, + #[serde(rename = "invalid_exact_evm_permit2_payload_valid_after")] + InvalidExactEvmPermit2PayloadValidAfter, + #[serde(rename = "invalid_exact_evm_permit2_payload_spender")] + InvalidExactEvmPermit2PayloadSpender, + #[serde(rename = "invalid_exact_evm_permit2_payload_recipient")] + InvalidExactEvmPermit2PayloadRecipient, + #[serde(rename = "invalid_exact_evm_permit2_payload_amount")] + InvalidExactEvmPermit2PayloadAmount, + #[serde(rename = "invalid_exact_svm_payload_transaction")] + InvalidExactSvmPayloadTransaction, + #[serde(rename = "invalid_exact_svm_payload_transaction_amount_mismatch")] + InvalidExactSvmPayloadTransactionAmountMismatch, + #[serde(rename = "invalid_exact_svm_payload_transaction_create_ata_instruction")] + InvalidExactSvmPayloadTransactionCreateAtaInstruction, + #[serde( + rename = "invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_payee" + )] + InvalidExactSvmPayloadTransactionCreateAtaInstructionIncorrectPayee, + #[serde( + rename = "invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_asset" + )] + InvalidExactSvmPayloadTransactionCreateAtaInstructionIncorrectAsset, + #[serde(rename = "invalid_exact_svm_payload_transaction_instructions")] + InvalidExactSvmPayloadTransactionInstructions, + #[serde(rename = "invalid_exact_svm_payload_transaction_instructions_length")] + InvalidExactSvmPayloadTransactionInstructionsLength, + #[serde( + rename = "invalid_exact_svm_payload_transaction_instructions_compute_limit_instruction" + )] + InvalidExactSvmPayloadTransactionInstructionsComputeLimitInstruction, + #[serde( + rename = "invalid_exact_svm_payload_transaction_instructions_compute_price_instruction" + )] + InvalidExactSvmPayloadTransactionInstructionsComputePriceInstruction, + #[serde( + rename = "invalid_exact_svm_payload_transaction_instructions_compute_price_instruction_too_high" + )] + InvalidExactSvmPayloadTransactionInstructionsComputePriceInstructionTooHigh, + #[serde( + rename = "invalid_exact_svm_payload_transaction_instruction_not_spl_token_transfer_checked" + )] + InvalidExactSvmPayloadTransactionInstructionNotSplTokenTransferChecked, + #[serde( + rename = "invalid_exact_svm_payload_transaction_instruction_not_token_2022_transfer_checked" + )] + InvalidExactSvmPayloadTransactionInstructionNotToken2022TransferChecked, + #[serde(rename = "invalid_exact_svm_payload_transaction_not_a_transfer_instruction")] + InvalidExactSvmPayloadTransactionNotATransferInstruction, + #[serde(rename = "invalid_exact_svm_payload_transaction_cannot_derive_receiver_ata")] + InvalidExactSvmPayloadTransactionCannotDeriveReceiverAta, + #[serde(rename = "invalid_exact_svm_payload_transaction_receiver_ata_not_found")] + InvalidExactSvmPayloadTransactionReceiverAtaNotFound, + #[serde(rename = "invalid_exact_svm_payload_transaction_sender_ata_not_found")] + InvalidExactSvmPayloadTransactionSenderAtaNotFound, + #[serde(rename = "invalid_exact_svm_payload_transaction_simulation_failed")] + InvalidExactSvmPayloadTransactionSimulationFailed, + #[serde(rename = "invalid_exact_svm_payload_transaction_transfer_to_incorrect_ata")] + InvalidExactSvmPayloadTransactionTransferToIncorrectAta, + #[serde( + rename = "invalid_exact_svm_payload_transaction_fee_payer_included_in_instruction_accounts" + )] + InvalidExactSvmPayloadTransactionFeePayerIncludedInInstructionAccounts, + #[serde(rename = "invalid_exact_svm_payload_transaction_fee_payer_transferring_funds")] + InvalidExactSvmPayloadTransactionFeePayerTransferringFunds, + #[serde(rename = "unknown_error")] + UnknownError, } - impl ::std::convert::From<&Self> for X402v1PaymentRequirementsScheme { - fn from(value: &X402v1PaymentRequirementsScheme) -> Self { + impl ::std::convert::From<&Self> for X402VerifyInvalidReason { + fn from(value: &X402VerifyInvalidReason) -> Self { value.clone() } } - impl ::std::fmt::Display for X402v1PaymentRequirementsScheme { + impl ::std::fmt::Display for X402VerifyInvalidReason { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match *self { - Self::Exact => f.write_str("exact"), + Self::InsufficientFunds => f.write_str("insufficient_funds"), + Self::InvalidScheme => f.write_str("invalid_scheme"), + Self::InvalidNetwork => f.write_str("invalid_network"), + Self::InvalidX402Version => f.write_str("invalid_x402_version"), + Self::InvalidPaymentRequirements => { + f.write_str("invalid_payment_requirements") + } + Self::InvalidPayload => f.write_str("invalid_payload"), + Self::InvalidExactEvmPayloadAuthorizationValue => { + f.write_str("invalid_exact_evm_payload_authorization_value") + } + Self::InvalidExactEvmPayloadAuthorizationValueTooLow => { + f.write_str("invalid_exact_evm_payload_authorization_value_too_low") + } + Self::InvalidExactEvmPayloadAuthorizationValidAfter => { + f.write_str("invalid_exact_evm_payload_authorization_valid_after") + } + Self::InvalidExactEvmPayloadAuthorizationValidBefore => { + f.write_str("invalid_exact_evm_payload_authorization_valid_before") + } + Self::InvalidExactEvmPayloadAuthorizationTypedDataMessage => { + f.write_str( + "invalid_exact_evm_payload_authorization_typed_data_message", + ) + } + Self::InvalidExactEvmPayloadAuthorizationFromAddressKyt => { + f.write_str( + "invalid_exact_evm_payload_authorization_from_address_kyt", + ) + } + Self::InvalidExactEvmPayloadAuthorizationToAddressKyt => { + f.write_str("invalid_exact_evm_payload_authorization_to_address_kyt") + } + Self::InvalidExactEvmPayloadSignature => { + f.write_str("invalid_exact_evm_payload_signature") + } + Self::InvalidExactEvmPayloadSignatureAddress => { + f.write_str("invalid_exact_evm_payload_signature_address") + } + Self::InvalidExactEvmPermit2PayloadAllowanceRequired => { + f.write_str("invalid_exact_evm_permit2_payload_allowance_required") + } + Self::InvalidExactEvmPermit2PayloadSignature => { + f.write_str("invalid_exact_evm_permit2_payload_signature") + } + Self::InvalidExactEvmPermit2PayloadDeadline => { + f.write_str("invalid_exact_evm_permit2_payload_deadline") + } + Self::InvalidExactEvmPermit2PayloadValidAfter => { + f.write_str("invalid_exact_evm_permit2_payload_valid_after") + } + Self::InvalidExactEvmPermit2PayloadSpender => { + f.write_str("invalid_exact_evm_permit2_payload_spender") + } + Self::InvalidExactEvmPermit2PayloadRecipient => { + f.write_str("invalid_exact_evm_permit2_payload_recipient") + } + Self::InvalidExactEvmPermit2PayloadAmount => { + f.write_str("invalid_exact_evm_permit2_payload_amount") + } + Self::InvalidExactSvmPayloadTransaction => { + f.write_str("invalid_exact_svm_payload_transaction") + } + Self::InvalidExactSvmPayloadTransactionAmountMismatch => { + f.write_str("invalid_exact_svm_payload_transaction_amount_mismatch") + } + Self::InvalidExactSvmPayloadTransactionCreateAtaInstruction => { + f.write_str( + "invalid_exact_svm_payload_transaction_create_ata_instruction", + ) + } + Self::InvalidExactSvmPayloadTransactionCreateAtaInstructionIncorrectPayee => { + f.write_str( + "invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_payee", + ) + } + Self::InvalidExactSvmPayloadTransactionCreateAtaInstructionIncorrectAsset => { + f.write_str( + "invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_asset", + ) + } + Self::InvalidExactSvmPayloadTransactionInstructions => { + f.write_str("invalid_exact_svm_payload_transaction_instructions") + } + Self::InvalidExactSvmPayloadTransactionInstructionsLength => { + f.write_str( + "invalid_exact_svm_payload_transaction_instructions_length", + ) + } + Self::InvalidExactSvmPayloadTransactionInstructionsComputeLimitInstruction => { + f.write_str( + "invalid_exact_svm_payload_transaction_instructions_compute_limit_instruction", + ) + } + Self::InvalidExactSvmPayloadTransactionInstructionsComputePriceInstruction => { + f.write_str( + "invalid_exact_svm_payload_transaction_instructions_compute_price_instruction", + ) + } + Self::InvalidExactSvmPayloadTransactionInstructionsComputePriceInstructionTooHigh => { + f.write_str( + "invalid_exact_svm_payload_transaction_instructions_compute_price_instruction_too_high", + ) + } + Self::InvalidExactSvmPayloadTransactionInstructionNotSplTokenTransferChecked => { + f.write_str( + "invalid_exact_svm_payload_transaction_instruction_not_spl_token_transfer_checked", + ) + } + Self::InvalidExactSvmPayloadTransactionInstructionNotToken2022TransferChecked => { + f.write_str( + "invalid_exact_svm_payload_transaction_instruction_not_token_2022_transfer_checked", + ) + } + Self::InvalidExactSvmPayloadTransactionNotATransferInstruction => { + f.write_str( + "invalid_exact_svm_payload_transaction_not_a_transfer_instruction", + ) + } + Self::InvalidExactSvmPayloadTransactionCannotDeriveReceiverAta => { + f.write_str( + "invalid_exact_svm_payload_transaction_cannot_derive_receiver_ata", + ) + } + Self::InvalidExactSvmPayloadTransactionReceiverAtaNotFound => { + f.write_str( + "invalid_exact_svm_payload_transaction_receiver_ata_not_found", + ) + } + Self::InvalidExactSvmPayloadTransactionSenderAtaNotFound => { + f.write_str( + "invalid_exact_svm_payload_transaction_sender_ata_not_found", + ) + } + Self::InvalidExactSvmPayloadTransactionSimulationFailed => { + f.write_str( + "invalid_exact_svm_payload_transaction_simulation_failed", + ) + } + Self::InvalidExactSvmPayloadTransactionTransferToIncorrectAta => { + f.write_str( + "invalid_exact_svm_payload_transaction_transfer_to_incorrect_ata", + ) + } + Self::InvalidExactSvmPayloadTransactionFeePayerIncludedInInstructionAccounts => { + f.write_str( + "invalid_exact_svm_payload_transaction_fee_payer_included_in_instruction_accounts", + ) + } + Self::InvalidExactSvmPayloadTransactionFeePayerTransferringFunds => { + f.write_str( + "invalid_exact_svm_payload_transaction_fee_payer_transferring_funds", + ) + } + Self::UnknownError => f.write_str("unknown_error"), } } } - impl ::std::str::FromStr for X402v1PaymentRequirementsScheme { + impl ::std::str::FromStr for X402VerifyInvalidReason { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { match value { - "exact" => Ok(Self::Exact), + "insufficient_funds" => Ok(Self::InsufficientFunds), + "invalid_scheme" => Ok(Self::InvalidScheme), + "invalid_network" => Ok(Self::InvalidNetwork), + "invalid_x402_version" => Ok(Self::InvalidX402Version), + "invalid_payment_requirements" => Ok(Self::InvalidPaymentRequirements), + "invalid_payload" => Ok(Self::InvalidPayload), + "invalid_exact_evm_payload_authorization_value" => { + Ok(Self::InvalidExactEvmPayloadAuthorizationValue) + } + "invalid_exact_evm_payload_authorization_value_too_low" => { + Ok(Self::InvalidExactEvmPayloadAuthorizationValueTooLow) + } + "invalid_exact_evm_payload_authorization_valid_after" => { + Ok(Self::InvalidExactEvmPayloadAuthorizationValidAfter) + } + "invalid_exact_evm_payload_authorization_valid_before" => { + Ok(Self::InvalidExactEvmPayloadAuthorizationValidBefore) + } + "invalid_exact_evm_payload_authorization_typed_data_message" => { + Ok(Self::InvalidExactEvmPayloadAuthorizationTypedDataMessage) + } + "invalid_exact_evm_payload_authorization_from_address_kyt" => { + Ok(Self::InvalidExactEvmPayloadAuthorizationFromAddressKyt) + } + "invalid_exact_evm_payload_authorization_to_address_kyt" => { + Ok(Self::InvalidExactEvmPayloadAuthorizationToAddressKyt) + } + "invalid_exact_evm_payload_signature" => { + Ok(Self::InvalidExactEvmPayloadSignature) + } + "invalid_exact_evm_payload_signature_address" => { + Ok(Self::InvalidExactEvmPayloadSignatureAddress) + } + "invalid_exact_evm_permit2_payload_allowance_required" => { + Ok(Self::InvalidExactEvmPermit2PayloadAllowanceRequired) + } + "invalid_exact_evm_permit2_payload_signature" => { + Ok(Self::InvalidExactEvmPermit2PayloadSignature) + } + "invalid_exact_evm_permit2_payload_deadline" => { + Ok(Self::InvalidExactEvmPermit2PayloadDeadline) + } + "invalid_exact_evm_permit2_payload_valid_after" => { + Ok(Self::InvalidExactEvmPermit2PayloadValidAfter) + } + "invalid_exact_evm_permit2_payload_spender" => { + Ok(Self::InvalidExactEvmPermit2PayloadSpender) + } + "invalid_exact_evm_permit2_payload_recipient" => { + Ok(Self::InvalidExactEvmPermit2PayloadRecipient) + } + "invalid_exact_evm_permit2_payload_amount" => { + Ok(Self::InvalidExactEvmPermit2PayloadAmount) + } + "invalid_exact_svm_payload_transaction" => { + Ok(Self::InvalidExactSvmPayloadTransaction) + } + "invalid_exact_svm_payload_transaction_amount_mismatch" => { + Ok(Self::InvalidExactSvmPayloadTransactionAmountMismatch) + } + "invalid_exact_svm_payload_transaction_create_ata_instruction" => { + Ok(Self::InvalidExactSvmPayloadTransactionCreateAtaInstruction) + } + "invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_payee" => { + Ok( + Self::InvalidExactSvmPayloadTransactionCreateAtaInstructionIncorrectPayee, + ) + } + "invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_asset" => { + Ok( + Self::InvalidExactSvmPayloadTransactionCreateAtaInstructionIncorrectAsset, + ) + } + "invalid_exact_svm_payload_transaction_instructions" => { + Ok(Self::InvalidExactSvmPayloadTransactionInstructions) + } + "invalid_exact_svm_payload_transaction_instructions_length" => { + Ok(Self::InvalidExactSvmPayloadTransactionInstructionsLength) + } + "invalid_exact_svm_payload_transaction_instructions_compute_limit_instruction" => { + Ok( + Self::InvalidExactSvmPayloadTransactionInstructionsComputeLimitInstruction, + ) + } + "invalid_exact_svm_payload_transaction_instructions_compute_price_instruction" => { + Ok( + Self::InvalidExactSvmPayloadTransactionInstructionsComputePriceInstruction, + ) + } + "invalid_exact_svm_payload_transaction_instructions_compute_price_instruction_too_high" => { + Ok( + Self::InvalidExactSvmPayloadTransactionInstructionsComputePriceInstructionTooHigh, + ) + } + "invalid_exact_svm_payload_transaction_instruction_not_spl_token_transfer_checked" => { + Ok( + Self::InvalidExactSvmPayloadTransactionInstructionNotSplTokenTransferChecked, + ) + } + "invalid_exact_svm_payload_transaction_instruction_not_token_2022_transfer_checked" => { + Ok( + Self::InvalidExactSvmPayloadTransactionInstructionNotToken2022TransferChecked, + ) + } + "invalid_exact_svm_payload_transaction_not_a_transfer_instruction" => { + Ok(Self::InvalidExactSvmPayloadTransactionNotATransferInstruction) + } + "invalid_exact_svm_payload_transaction_cannot_derive_receiver_ata" => { + Ok(Self::InvalidExactSvmPayloadTransactionCannotDeriveReceiverAta) + } + "invalid_exact_svm_payload_transaction_receiver_ata_not_found" => { + Ok(Self::InvalidExactSvmPayloadTransactionReceiverAtaNotFound) + } + "invalid_exact_svm_payload_transaction_sender_ata_not_found" => { + Ok(Self::InvalidExactSvmPayloadTransactionSenderAtaNotFound) + } + "invalid_exact_svm_payload_transaction_simulation_failed" => { + Ok(Self::InvalidExactSvmPayloadTransactionSimulationFailed) + } + "invalid_exact_svm_payload_transaction_transfer_to_incorrect_ata" => { + Ok(Self::InvalidExactSvmPayloadTransactionTransferToIncorrectAta) + } + "invalid_exact_svm_payload_transaction_fee_payer_included_in_instruction_accounts" => { + Ok( + Self::InvalidExactSvmPayloadTransactionFeePayerIncludedInInstructionAccounts, + ) + } + "invalid_exact_svm_payload_transaction_fee_payer_transferring_funds" => { + Ok(Self::InvalidExactSvmPayloadTransactionFeePayerTransferringFunds) + } + "unknown_error" => Ok(Self::UnknownError), _ => Err("invalid value".into()), } } } - impl ::std::convert::TryFrom<&str> for X402v1PaymentRequirementsScheme { + impl ::std::convert::TryFrom<&str> for X402VerifyInvalidReason { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for X402v1PaymentRequirementsScheme { + impl ::std::convert::TryFrom<&::std::string::String> for X402VerifyInvalidReason { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -61092,7 +67895,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for X402v1PaymentRequirementsScheme { + impl ::std::convert::TryFrom<::std::string::String> for X402VerifyInvalidReason { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -61100,79 +67903,99 @@ pub mod types { value.parse() } } - ///The payload of the payment depending on the x402Version, scheme, and network. + ///The result when x402 payment verification fails. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The payload of the payment depending on the x402Version, scheme, and network.", + /// "description": "The result when x402 payment verification fails.", /// "examples": [ /// { - /// "authorization": { - /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "nonce": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", - /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - /// "validAfter": "1716150000", - /// "validBefore": "1716150000", - /// "value": "1000000000000000000" - /// }, - /// "signature": "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" + /// "invalidMessage": "Insufficient funds", + /// "invalidReason": "insufficient_funds", + /// "isValid": false, + /// "payer": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" /// } /// ], /// "type": "object", - /// "oneOf": [ - /// { - /// "$ref": "#/components/schemas/x402ExactEvmPayload" + /// "required": [ + /// "invalidReason", + /// "isValid" + /// ], + /// "properties": { + /// "invalidMessage": { + /// "description": "The message describing the invalid reason.", + /// "examples": [ + /// "Insufficient funds" + /// ], + /// "type": "string" /// }, - /// { - /// "$ref": "#/components/schemas/x402ExactEvmPermit2Payload" + /// "invalidReason": { + /// "$ref": "#/components/schemas/x402VerifyInvalidReason" /// }, - /// { - /// "$ref": "#/components/schemas/x402ExactSolanaPayload" + /// "isValid": { + /// "description": "Indicates whether the payment is valid.", + /// "examples": [ + /// false + /// ], + /// "type": "boolean" + /// }, + /// "payer": { + /// "description": "The onchain address of the client that is paying for the resource.\n\nFor EVM networks, the payer will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, the payer will be a base58-encoded Solana address.", + /// "examples": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ], + /// "type": "string", + /// "pattern": "^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$" /// } - /// ] + /// } ///} /// ``` ///
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] - #[serde(untagged)] - pub enum X402v2PaymentPayloadPayload { - EvmPayload(X402ExactEvmPayload), - EvmPermit2Payload(X402ExactEvmPermit2Payload), - SolanaPayload(X402ExactSolanaPayload), + pub struct X402VerifyPaymentRejection { + ///The message describing the invalid reason. + #[serde( + rename = "invalidMessage", + default, + skip_serializing_if = "::std::option::Option::is_none" + )] + pub invalid_message: ::std::option::Option<::std::string::String>, + #[serde(rename = "invalidReason")] + pub invalid_reason: X402VerifyInvalidReason, + ///Indicates whether the payment is valid. + #[serde(rename = "isValid")] + pub is_valid: bool, + /**The onchain address of the client that is paying for the resource. + + For EVM networks, the payer will be a 0x-prefixed, checksum EVM address. + + For Solana-based networks, the payer will be a base58-encoded Solana address.*/ + #[serde(default, skip_serializing_if = "::std::option::Option::is_none")] + pub payer: ::std::option::Option, } - impl ::std::convert::From<&Self> for X402v2PaymentPayloadPayload { - fn from(value: &X402v2PaymentPayloadPayload) -> Self { + impl ::std::convert::From<&X402VerifyPaymentRejection> for X402VerifyPaymentRejection { + fn from(value: &X402VerifyPaymentRejection) -> Self { value.clone() } } - impl ::std::convert::From for X402v2PaymentPayloadPayload { - fn from(value: X402ExactEvmPayload) -> Self { - Self::EvmPayload(value) - } - } - impl ::std::convert::From for X402v2PaymentPayloadPayload { - fn from(value: X402ExactEvmPermit2Payload) -> Self { - Self::EvmPermit2Payload(value) - } - } - impl ::std::convert::From for X402v2PaymentPayloadPayload { - fn from(value: X402ExactSolanaPayload) -> Self { - Self::SolanaPayload(value) + impl X402VerifyPaymentRejection { + pub fn builder() -> builder::X402VerifyPaymentRejection { + Default::default() } } - /**The asset to pay with. + /**The onchain address of the client that is paying for the resource. - For EVM networks, the asset will be a 0x-prefixed, checksum EVM address. + For EVM networks, the payer will be a 0x-prefixed, checksum EVM address. - For Solana-based networks, the asset will be a base58-encoded Solana address.*/ + For Solana-based networks, the payer will be a base58-encoded Solana address.*/ /// ///
JSON schema /// /// ```json ///{ - /// "description": "The asset to pay with.\n\nFor EVM networks, the asset will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, the asset will be a base58-encoded Solana address.", + /// "description": "The onchain address of the client that is paying for the resource.\n\nFor EVM networks, the payer will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, the payer will be a base58-encoded Solana address.", /// "examples": [ /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" /// ], @@ -61183,24 +68006,24 @@ pub mod types { ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct X402v2PaymentRequirementsAsset(::std::string::String); - impl ::std::ops::Deref for X402v2PaymentRequirementsAsset { + pub struct X402VerifyPaymentRejectionPayer(::std::string::String); + impl ::std::ops::Deref for X402VerifyPaymentRejectionPayer { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: X402v2PaymentRequirementsAsset) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: X402VerifyPaymentRejectionPayer) -> Self { value.0 } } - impl ::std::convert::From<&X402v2PaymentRequirementsAsset> for X402v2PaymentRequirementsAsset { - fn from(value: &X402v2PaymentRequirementsAsset) -> Self { + impl ::std::convert::From<&X402VerifyPaymentRejectionPayer> for X402VerifyPaymentRejectionPayer { + fn from(value: &X402VerifyPaymentRejectionPayer) -> Self { value.clone() } } - impl ::std::str::FromStr for X402v2PaymentRequirementsAsset { + impl ::std::str::FromStr for X402VerifyPaymentRejectionPayer { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = @@ -61217,13 +68040,13 @@ pub mod types { Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for X402v2PaymentRequirementsAsset { + impl ::std::convert::TryFrom<&str> for X402VerifyPaymentRejectionPayer { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for X402v2PaymentRequirementsAsset { + impl ::std::convert::TryFrom<&::std::string::String> for X402VerifyPaymentRejectionPayer { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -61231,7 +68054,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for X402v2PaymentRequirementsAsset { + impl ::std::convert::TryFrom<::std::string::String> for X402VerifyPaymentRejectionPayer { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -61239,7 +68062,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for X402v2PaymentRequirementsAsset { + impl<'de> ::serde::Deserialize<'de> for X402VerifyPaymentRejectionPayer { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -61251,17 +68074,307 @@ pub mod types { }) } } - /**The destination to pay value to. + ///The version of the x402 protocol. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The version of the x402 protocol.", + /// "examples": [ + /// 2 + /// ], + /// "type": "integer", + /// "enum": [ + /// 1, + /// 2 + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug)] + #[serde(transparent)] + pub struct X402Version(i64); + impl ::std::ops::Deref for X402Version { + type Target = i64; + fn deref(&self) -> &i64 { + &self.0 + } + } + impl ::std::convert::From for i64 { + fn from(value: X402Version) -> Self { + value.0 + } + } + impl ::std::convert::From<&X402Version> for X402Version { + fn from(value: &X402Version) -> Self { + value.clone() + } + } + impl ::std::convert::TryFrom for X402Version { + type Error = self::error::ConversionError; + fn try_from(value: i64) -> ::std::result::Result { + if ![1_i64, 2_i64].contains(&value) { + Err("invalid value".into()) + } else { + Ok(Self(value)) + } + } + } + impl<'de> ::serde::Deserialize<'de> for X402Version { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + Self::try_from(::deserialize(deserializer)?) + .map_err(|e| ::custom(e.to_string())) + } + } + ///The network of the blockchain to send payment on. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The network of the blockchain to send payment on.", + /// "examples": [ + /// "base" + /// ], + /// "type": "string", + /// "enum": [ + /// "base-sepolia", + /// "base", + /// "solana-devnet", + /// "solana", + /// "polygon" + /// ] + ///} + /// ``` + ///
+ #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum X402v1PaymentPayloadNetwork { + #[serde(rename = "base-sepolia")] + BaseSepolia, + #[serde(rename = "base")] + Base, + #[serde(rename = "solana-devnet")] + SolanaDevnet, + #[serde(rename = "solana")] + Solana, + #[serde(rename = "polygon")] + Polygon, + } + impl ::std::convert::From<&Self> for X402v1PaymentPayloadNetwork { + fn from(value: &X402v1PaymentPayloadNetwork) -> Self { + value.clone() + } + } + impl ::std::fmt::Display for X402v1PaymentPayloadNetwork { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::BaseSepolia => f.write_str("base-sepolia"), + Self::Base => f.write_str("base"), + Self::SolanaDevnet => f.write_str("solana-devnet"), + Self::Solana => f.write_str("solana"), + Self::Polygon => f.write_str("polygon"), + } + } + } + impl ::std::str::FromStr for X402v1PaymentPayloadNetwork { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "base-sepolia" => Ok(Self::BaseSepolia), + "base" => Ok(Self::Base), + "solana-devnet" => Ok(Self::SolanaDevnet), + "solana" => Ok(Self::Solana), + "polygon" => Ok(Self::Polygon), + _ => Err("invalid value".into()), + } + } + } + impl ::std::convert::TryFrom<&str> for X402v1PaymentPayloadNetwork { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for X402v1PaymentPayloadNetwork { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for X402v1PaymentPayloadNetwork { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + ///The payload of the payment depending on the x402Version, scheme, and network. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The payload of the payment depending on the x402Version, scheme, and network.", + /// "examples": [ + /// { + /// "authorization": { + /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "nonce": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", + /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "validAfter": "1716150000", + /// "validBefore": "1716150000", + /// "value": "1000000000000000000" + /// }, + /// "signature": "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" + /// } + /// ], + /// "type": "object", + /// "oneOf": [ + /// { + /// "$ref": "#/components/schemas/x402ExactEvmPayload" + /// }, + /// { + /// "$ref": "#/components/schemas/x402ExactEvmPermit2Payload" + /// }, + /// { + /// "$ref": "#/components/schemas/x402ExactSolanaPayload" + /// } + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + #[serde(untagged)] + pub enum X402v1PaymentPayloadPayload { + EvmPayload(X402ExactEvmPayload), + EvmPermit2Payload(X402ExactEvmPermit2Payload), + SolanaPayload(X402ExactSolanaPayload), + } + impl ::std::convert::From<&Self> for X402v1PaymentPayloadPayload { + fn from(value: &X402v1PaymentPayloadPayload) -> Self { + value.clone() + } + } + impl ::std::convert::From for X402v1PaymentPayloadPayload { + fn from(value: X402ExactEvmPayload) -> Self { + Self::EvmPayload(value) + } + } + impl ::std::convert::From for X402v1PaymentPayloadPayload { + fn from(value: X402ExactEvmPermit2Payload) -> Self { + Self::EvmPermit2Payload(value) + } + } + impl ::std::convert::From for X402v1PaymentPayloadPayload { + fn from(value: X402ExactSolanaPayload) -> Self { + Self::SolanaPayload(value) + } + } + ///The scheme of the payment protocol to use. Currently, the only supported scheme is `exact`. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The scheme of the payment protocol to use. Currently, the only supported scheme is `exact`.", + /// "examples": [ + /// "exact" + /// ], + /// "type": "string", + /// "enum": [ + /// "exact" + /// ] + ///} + /// ``` + ///
+ #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum X402v1PaymentPayloadScheme { + #[serde(rename = "exact")] + Exact, + } + impl ::std::convert::From<&Self> for X402v1PaymentPayloadScheme { + fn from(value: &X402v1PaymentPayloadScheme) -> Self { + value.clone() + } + } + impl ::std::fmt::Display for X402v1PaymentPayloadScheme { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Exact => f.write_str("exact"), + } + } + } + impl ::std::str::FromStr for X402v1PaymentPayloadScheme { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "exact" => Ok(Self::Exact), + _ => Err("invalid value".into()), + } + } + } + impl ::std::convert::TryFrom<&str> for X402v1PaymentPayloadScheme { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for X402v1PaymentPayloadScheme { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for X402v1PaymentPayloadScheme { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + /**The asset to pay with. - For EVM networks, payTo will be a 0x-prefixed, checksum EVM address. + For EVM networks, the asset will be a 0x-prefixed, checksum EVM address. - For Solana-based networks, payTo will be a base58-encoded Solana address.*/ + For Solana-based networks, the asset will be a base58-encoded Solana address.*/ /// ///
JSON schema /// /// ```json ///{ - /// "description": "The destination to pay value to.\n\nFor EVM networks, payTo will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, payTo will be a base58-encoded Solana address.", + /// "description": "The asset to pay with.\n\nFor EVM networks, the asset will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, the asset will be a base58-encoded Solana address.", /// "examples": [ /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" /// ], @@ -61272,24 +68385,24 @@ pub mod types { ///
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[serde(transparent)] - pub struct X402v2PaymentRequirementsPayTo(::std::string::String); - impl ::std::ops::Deref for X402v2PaymentRequirementsPayTo { + pub struct X402v1PaymentRequirementsAsset(::std::string::String); + impl ::std::ops::Deref for X402v1PaymentRequirementsAsset { type Target = ::std::string::String; fn deref(&self) -> &::std::string::String { &self.0 } } - impl ::std::convert::From for ::std::string::String { - fn from(value: X402v2PaymentRequirementsPayTo) -> Self { + impl ::std::convert::From for ::std::string::String { + fn from(value: X402v1PaymentRequirementsAsset) -> Self { value.0 } } - impl ::std::convert::From<&X402v2PaymentRequirementsPayTo> for X402v2PaymentRequirementsPayTo { - fn from(value: &X402v2PaymentRequirementsPayTo) -> Self { + impl ::std::convert::From<&X402v1PaymentRequirementsAsset> for X402v1PaymentRequirementsAsset { + fn from(value: &X402v1PaymentRequirementsAsset) -> Self { value.clone() } } - impl ::std::str::FromStr for X402v2PaymentRequirementsPayTo { + impl ::std::str::FromStr for X402v1PaymentRequirementsAsset { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = @@ -61306,13 +68419,13 @@ pub mod types { Ok(Self(value.to_string())) } } - impl ::std::convert::TryFrom<&str> for X402v2PaymentRequirementsPayTo { + impl ::std::convert::TryFrom<&str> for X402v1PaymentRequirementsAsset { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for X402v2PaymentRequirementsPayTo { + impl ::std::convert::TryFrom<&::std::string::String> for X402v1PaymentRequirementsAsset { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -61320,7 +68433,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for X402v2PaymentRequirementsPayTo { + impl ::std::convert::TryFrom<::std::string::String> for X402v1PaymentRequirementsAsset { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -61328,7 +68441,7 @@ pub mod types { value.parse() } } - impl<'de> ::serde::Deserialize<'de> for X402v2PaymentRequirementsPayTo { + impl<'de> ::serde::Deserialize<'de> for X402v1PaymentRequirementsAsset { fn deserialize(deserializer: D) -> ::std::result::Result where D: ::serde::Deserializer<'de>, @@ -61340,20 +68453,23 @@ pub mod types { }) } } - ///The scheme of the payment protocol to use. Supported schemes are `exact` and `upto`. + ///The network of the blockchain to send payment on. /// ///
JSON schema /// /// ```json ///{ - /// "description": "The scheme of the payment protocol to use. Supported schemes are `exact` and `upto`.", + /// "description": "The network of the blockchain to send payment on.", /// "examples": [ - /// "exact" + /// "base" /// ], /// "type": "string", /// "enum": [ - /// "exact", - /// "upto" + /// "base-sepolia", + /// "base", + /// "solana-devnet", + /// "solana", + /// "polygon" /// ] ///} /// ``` @@ -61370,42 +68486,54 @@ pub mod types { PartialEq, PartialOrd, )] - pub enum X402v2PaymentRequirementsScheme { - #[serde(rename = "exact")] - Exact, - #[serde(rename = "upto")] - Upto, + pub enum X402v1PaymentRequirementsNetwork { + #[serde(rename = "base-sepolia")] + BaseSepolia, + #[serde(rename = "base")] + Base, + #[serde(rename = "solana-devnet")] + SolanaDevnet, + #[serde(rename = "solana")] + Solana, + #[serde(rename = "polygon")] + Polygon, } - impl ::std::convert::From<&Self> for X402v2PaymentRequirementsScheme { - fn from(value: &X402v2PaymentRequirementsScheme) -> Self { + impl ::std::convert::From<&Self> for X402v1PaymentRequirementsNetwork { + fn from(value: &X402v1PaymentRequirementsNetwork) -> Self { value.clone() } } - impl ::std::fmt::Display for X402v2PaymentRequirementsScheme { + impl ::std::fmt::Display for X402v1PaymentRequirementsNetwork { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match *self { - Self::Exact => f.write_str("exact"), - Self::Upto => f.write_str("upto"), + Self::BaseSepolia => f.write_str("base-sepolia"), + Self::Base => f.write_str("base"), + Self::SolanaDevnet => f.write_str("solana-devnet"), + Self::Solana => f.write_str("solana"), + Self::Polygon => f.write_str("polygon"), } } } - impl ::std::str::FromStr for X402v2PaymentRequirementsScheme { + impl ::std::str::FromStr for X402v1PaymentRequirementsNetwork { type Err = self::error::ConversionError; fn from_str(value: &str) -> ::std::result::Result { match value { - "exact" => Ok(Self::Exact), - "upto" => Ok(Self::Upto), + "base-sepolia" => Ok(Self::BaseSepolia), + "base" => Ok(Self::Base), + "solana-devnet" => Ok(Self::SolanaDevnet), + "solana" => Ok(Self::Solana), + "polygon" => Ok(Self::Polygon), _ => Err("invalid value".into()), } } } - impl ::std::convert::TryFrom<&str> for X402v2PaymentRequirementsScheme { + impl ::std::convert::TryFrom<&str> for X402v1PaymentRequirementsNetwork { type Error = self::error::ConversionError; fn try_from(value: &str) -> ::std::result::Result { value.parse() } } - impl ::std::convert::TryFrom<&::std::string::String> for X402v2PaymentRequirementsScheme { + impl ::std::convert::TryFrom<&::std::string::String> for X402v1PaymentRequirementsNetwork { type Error = self::error::ConversionError; fn try_from( value: &::std::string::String, @@ -61413,7 +68541,7 @@ pub mod types { value.parse() } } - impl ::std::convert::TryFrom<::std::string::String> for X402v2PaymentRequirementsScheme { + impl ::std::convert::TryFrom<::std::string::String> for X402v1PaymentRequirementsNetwork { type Error = self::error::ConversionError; fn try_from( value: ::std::string::String, @@ -61421,17 +68549,503 @@ pub mod types { value.parse() } } - /// Types for composing complex structures. - pub mod builder { - #[derive(Clone, Debug)] - pub struct AbiFunction { - constant: ::std::result::Result<::std::option::Option, ::std::string::String>, - gas: ::std::result::Result<::std::option::Option, ::std::string::String>, - inputs: - ::std::result::Result<::std::vec::Vec, ::std::string::String>, - name: ::std::result::Result<::std::string::String, ::std::string::String>, - outputs: - ::std::result::Result<::std::vec::Vec, ::std::string::String>, + /**The destination to pay value to. + + For EVM networks, payTo will be a 0x-prefixed, checksum EVM address. + + For Solana-based networks, payTo will be a base58-encoded Solana address.*/ + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The destination to pay value to.\n\nFor EVM networks, payTo will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, payTo will be a base58-encoded Solana address.", + /// "examples": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ], + /// "type": "string", + /// "pattern": "^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct X402v1PaymentRequirementsPayTo(::std::string::String); + impl ::std::ops::Deref for X402v1PaymentRequirementsPayTo { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: X402v1PaymentRequirementsPayTo) -> Self { + value.0 + } + } + impl ::std::convert::From<&X402v1PaymentRequirementsPayTo> for X402v1PaymentRequirementsPayTo { + fn from(value: &X402v1PaymentRequirementsPayTo) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for X402v1PaymentRequirementsPayTo { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$") + .unwrap() + }); + if PATTERN.find(value).is_none() { + return Err( + "doesn't match pattern \"^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$\"" + .into(), + ); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for X402v1PaymentRequirementsPayTo { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for X402v1PaymentRequirementsPayTo { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for X402v1PaymentRequirementsPayTo { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for X402v1PaymentRequirementsPayTo { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///The scheme of the payment protocol to use. Currently, the only supported scheme is `exact`. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The scheme of the payment protocol to use. Currently, the only supported scheme is `exact`.", + /// "examples": [ + /// "exact" + /// ], + /// "type": "string", + /// "enum": [ + /// "exact" + /// ] + ///} + /// ``` + ///
+ #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum X402v1PaymentRequirementsScheme { + #[serde(rename = "exact")] + Exact, + } + impl ::std::convert::From<&Self> for X402v1PaymentRequirementsScheme { + fn from(value: &X402v1PaymentRequirementsScheme) -> Self { + value.clone() + } + } + impl ::std::fmt::Display for X402v1PaymentRequirementsScheme { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Exact => f.write_str("exact"), + } + } + } + impl ::std::str::FromStr for X402v1PaymentRequirementsScheme { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "exact" => Ok(Self::Exact), + _ => Err("invalid value".into()), + } + } + } + impl ::std::convert::TryFrom<&str> for X402v1PaymentRequirementsScheme { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for X402v1PaymentRequirementsScheme { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for X402v1PaymentRequirementsScheme { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + ///The payload of the payment depending on the x402Version, scheme, and network. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The payload of the payment depending on the x402Version, scheme, and network.", + /// "examples": [ + /// { + /// "authorization": { + /// "from": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "nonce": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", + /// "to": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + /// "validAfter": "1716150000", + /// "validBefore": "1716150000", + /// "value": "1000000000000000000" + /// }, + /// "signature": "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f134801234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" + /// } + /// ], + /// "type": "object", + /// "oneOf": [ + /// { + /// "$ref": "#/components/schemas/x402ExactEvmPayload" + /// }, + /// { + /// "$ref": "#/components/schemas/x402ExactEvmPermit2Payload" + /// }, + /// { + /// "$ref": "#/components/schemas/x402ExactSolanaPayload" + /// } + /// ] + ///} + /// ``` + ///
+ #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)] + #[serde(untagged)] + pub enum X402v2PaymentPayloadPayload { + EvmPayload(X402ExactEvmPayload), + EvmPermit2Payload(X402ExactEvmPermit2Payload), + SolanaPayload(X402ExactSolanaPayload), + } + impl ::std::convert::From<&Self> for X402v2PaymentPayloadPayload { + fn from(value: &X402v2PaymentPayloadPayload) -> Self { + value.clone() + } + } + impl ::std::convert::From for X402v2PaymentPayloadPayload { + fn from(value: X402ExactEvmPayload) -> Self { + Self::EvmPayload(value) + } + } + impl ::std::convert::From for X402v2PaymentPayloadPayload { + fn from(value: X402ExactEvmPermit2Payload) -> Self { + Self::EvmPermit2Payload(value) + } + } + impl ::std::convert::From for X402v2PaymentPayloadPayload { + fn from(value: X402ExactSolanaPayload) -> Self { + Self::SolanaPayload(value) + } + } + /**The asset to pay with. + + For EVM networks, the asset will be a 0x-prefixed, checksum EVM address. + + For Solana-based networks, the asset will be a base58-encoded Solana address.*/ + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The asset to pay with.\n\nFor EVM networks, the asset will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, the asset will be a base58-encoded Solana address.", + /// "examples": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ], + /// "type": "string", + /// "pattern": "^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct X402v2PaymentRequirementsAsset(::std::string::String); + impl ::std::ops::Deref for X402v2PaymentRequirementsAsset { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: X402v2PaymentRequirementsAsset) -> Self { + value.0 + } + } + impl ::std::convert::From<&X402v2PaymentRequirementsAsset> for X402v2PaymentRequirementsAsset { + fn from(value: &X402v2PaymentRequirementsAsset) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for X402v2PaymentRequirementsAsset { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$") + .unwrap() + }); + if PATTERN.find(value).is_none() { + return Err( + "doesn't match pattern \"^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$\"" + .into(), + ); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for X402v2PaymentRequirementsAsset { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for X402v2PaymentRequirementsAsset { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for X402v2PaymentRequirementsAsset { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for X402v2PaymentRequirementsAsset { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + /**The destination to pay value to. + + For EVM networks, payTo will be a 0x-prefixed, checksum EVM address. + + For Solana-based networks, payTo will be a base58-encoded Solana address.*/ + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The destination to pay value to.\n\nFor EVM networks, payTo will be a 0x-prefixed, checksum EVM address.\n\nFor Solana-based networks, payTo will be a base58-encoded Solana address.", + /// "examples": [ + /// "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + /// ], + /// "type": "string", + /// "pattern": "^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$" + ///} + /// ``` + ///
+ #[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct X402v2PaymentRequirementsPayTo(::std::string::String); + impl ::std::ops::Deref for X402v2PaymentRequirementsPayTo { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + impl ::std::convert::From for ::std::string::String { + fn from(value: X402v2PaymentRequirementsPayTo) -> Self { + value.0 + } + } + impl ::std::convert::From<&X402v2PaymentRequirementsPayTo> for X402v2PaymentRequirementsPayTo { + fn from(value: &X402v2PaymentRequirementsPayTo) -> Self { + value.clone() + } + } + impl ::std::str::FromStr for X402v2PaymentRequirementsPayTo { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::new("^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$") + .unwrap() + }); + if PATTERN.find(value).is_none() { + return Err( + "doesn't match pattern \"^(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$\"" + .into(), + ); + } + Ok(Self(value.to_string())) + } + } + impl ::std::convert::TryFrom<&str> for X402v2PaymentRequirementsPayTo { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for X402v2PaymentRequirementsPayTo { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for X402v2PaymentRequirementsPayTo { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl<'de> ::serde::Deserialize<'de> for X402v2PaymentRequirementsPayTo { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::string::String::deserialize(deserializer)? + .parse() + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///The scheme of the payment protocol to use. Supported schemes are `exact` and `upto`. + /// + ///
JSON schema + /// + /// ```json + ///{ + /// "description": "The scheme of the payment protocol to use. Supported schemes are `exact` and `upto`.", + /// "examples": [ + /// "exact" + /// ], + /// "type": "string", + /// "enum": [ + /// "exact", + /// "upto" + /// ] + ///} + /// ``` + ///
+ #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum X402v2PaymentRequirementsScheme { + #[serde(rename = "exact")] + Exact, + #[serde(rename = "upto")] + Upto, + } + impl ::std::convert::From<&Self> for X402v2PaymentRequirementsScheme { + fn from(value: &X402v2PaymentRequirementsScheme) -> Self { + value.clone() + } + } + impl ::std::fmt::Display for X402v2PaymentRequirementsScheme { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Exact => f.write_str("exact"), + Self::Upto => f.write_str("upto"), + } + } + } + impl ::std::str::FromStr for X402v2PaymentRequirementsScheme { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "exact" => Ok(Self::Exact), + "upto" => Ok(Self::Upto), + _ => Err("invalid value".into()), + } + } + } + impl ::std::convert::TryFrom<&str> for X402v2PaymentRequirementsScheme { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<&::std::string::String> for X402v2PaymentRequirementsScheme { + type Error = self::error::ConversionError; + fn try_from( + value: &::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for X402v2PaymentRequirementsScheme { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + /// Types for composing complex structures. + pub mod builder { + #[derive(Clone, Debug)] + pub struct AbiFunction { + constant: ::std::result::Result<::std::option::Option, ::std::string::String>, + gas: ::std::result::Result<::std::option::Option, ::std::string::String>, + inputs: + ::std::result::Result<::std::vec::Vec, ::std::string::String>, + name: ::std::result::Result<::std::string::String, ::std::string::String>, + outputs: + ::std::result::Result<::std::vec::Vec, ::std::string::String>, payable: ::std::result::Result<::std::option::Option, ::std::string::String>, state_mutability: ::std::result::Result, @@ -61717,21 +69331,140 @@ pub mod types { } } #[derive(Clone, Debug)] - pub struct AccountTokenAddressesResponse { - account_address: ::std::result::Result< - ::std::option::Option<::std::string::String>, + pub struct Account { + account_id: ::std::result::Result, + created_at: ::std::result::Result< + ::chrono::DateTime<::chrono::offset::Utc>, ::std::string::String, >, - token_addresses: ::std::result::Result< - ::std::vec::Vec, + name: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + owner: ::std::result::Result, + type_: ::std::result::Result, + updated_at: ::std::result::Result< + ::chrono::DateTime<::chrono::offset::Utc>, ::std::string::String, >, - total_count: ::std::result::Result<::std::option::Option, ::std::string::String>, } - impl ::std::default::Default for AccountTokenAddressesResponse { + impl ::std::default::Default for Account { fn default() -> Self { Self { - account_address: Ok(Default::default()), + account_id: Err("no value supplied for account_id".to_string()), + created_at: Err("no value supplied for created_at".to_string()), + name: Ok(Default::default()), + owner: Err("no value supplied for owner".to_string()), + type_: Err("no value supplied for type_".to_string()), + updated_at: Err("no value supplied for updated_at".to_string()), + } + } + } + impl Account { + pub fn account_id(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.account_id = value + .try_into() + .map_err(|e| format!("error converting supplied value for account_id: {}", e)); + self + } + pub fn created_at(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, + T::Error: ::std::fmt::Display, + { + self.created_at = value + .try_into() + .map_err(|e| format!("error converting supplied value for created_at: {}", e)); + self + } + pub fn name(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.name = value + .try_into() + .map_err(|e| format!("error converting supplied value for name: {}", e)); + self + } + pub fn owner(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.owner = value + .try_into() + .map_err(|e| format!("error converting supplied value for owner: {}", e)); + self + } + pub fn type_(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.type_ = value + .try_into() + .map_err(|e| format!("error converting supplied value for type_: {}", e)); + self + } + pub fn updated_at(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, + T::Error: ::std::fmt::Display, + { + self.updated_at = value + .try_into() + .map_err(|e| format!("error converting supplied value for updated_at: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::Account { + type Error = super::error::ConversionError; + fn try_from( + value: Account, + ) -> ::std::result::Result { + Ok(Self { + account_id: value.account_id?, + created_at: value.created_at?, + name: value.name?, + owner: value.owner?, + type_: value.type_?, + updated_at: value.updated_at?, + }) + } + } + impl ::std::convert::From for Account { + fn from(value: super::Account) -> Self { + Self { + account_id: Ok(value.account_id), + created_at: Ok(value.created_at), + name: Ok(value.name), + owner: Ok(value.owner), + type_: Ok(value.type_), + updated_at: Ok(value.updated_at), + } + } + } + #[derive(Clone, Debug)] + pub struct AccountTokenAddressesResponse { + account_address: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + token_addresses: ::std::result::Result< + ::std::vec::Vec, + ::std::string::String, + >, + total_count: ::std::result::Result<::std::option::Option, ::std::string::String>, + } + impl ::std::default::Default for AccountTokenAddressesResponse { + fn default() -> Self { + Self { + account_address: Ok(Default::default()), token_addresses: Ok(Default::default()), total_count: Ok(Default::default()), } @@ -61973,6 +69706,241 @@ pub mod types { } } #[derive(Clone, Debug)] + pub struct AmountDetail { + available: ::std::result::Result<::std::string::String, ::std::string::String>, + total: ::std::result::Result<::std::string::String, ::std::string::String>, + } + impl ::std::default::Default for AmountDetail { + fn default() -> Self { + Self { + available: Err("no value supplied for available".to_string()), + total: Err("no value supplied for total".to_string()), + } + } + } + impl AmountDetail { + pub fn available(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::string::String>, + T::Error: ::std::fmt::Display, + { + self.available = value + .try_into() + .map_err(|e| format!("error converting supplied value for available: {}", e)); + self + } + pub fn total(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::string::String>, + T::Error: ::std::fmt::Display, + { + self.total = value + .try_into() + .map_err(|e| format!("error converting supplied value for total: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::AmountDetail { + type Error = super::error::ConversionError; + fn try_from( + value: AmountDetail, + ) -> ::std::result::Result { + Ok(Self { + available: value.available?, + total: value.total?, + }) + } + } + impl ::std::convert::From for AmountDetail { + fn from(value: super::AmountDetail) -> Self { + Self { + available: Ok(value.available), + total: Ok(value.total), + } + } + } + #[derive(Clone, Debug)] + pub struct Balance { + amount: ::std::result::Result< + ::std::collections::HashMap<::std::string::String, super::AmountDetail>, + ::std::string::String, + >, + asset: ::std::result::Result, + } + impl ::std::default::Default for Balance { + fn default() -> Self { + Self { + amount: Err("no value supplied for amount".to_string()), + asset: Err("no value supplied for asset".to_string()), + } + } + } + impl Balance { + pub fn amount(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + ::std::collections::HashMap<::std::string::String, super::AmountDetail>, + >, + T::Error: ::std::fmt::Display, + { + self.amount = value + .try_into() + .map_err(|e| format!("error converting supplied value for amount: {}", e)); + self + } + pub fn asset(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.asset = value + .try_into() + .map_err(|e| format!("error converting supplied value for asset: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::Balance { + type Error = super::error::ConversionError; + fn try_from( + value: Balance, + ) -> ::std::result::Result { + Ok(Self { + amount: value.amount?, + asset: value.asset?, + }) + } + } + impl ::std::convert::From for Balance { + fn from(value: super::Balance) -> Self { + Self { + amount: Ok(value.amount), + asset: Ok(value.asset), + } + } + } + #[derive(Clone, Debug)] + pub struct Balances { + balances: ::std::result::Result<::std::vec::Vec, ::std::string::String>, + } + impl ::std::default::Default for Balances { + fn default() -> Self { + Self { + balances: Err("no value supplied for balances".to_string()), + } + } + } + impl Balances { + pub fn balances(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::vec::Vec>, + T::Error: ::std::fmt::Display, + { + self.balances = value + .try_into() + .map_err(|e| format!("error converting supplied value for balances: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::Balances { + type Error = super::error::ConversionError; + fn try_from( + value: Balances, + ) -> ::std::result::Result { + Ok(Self { + balances: value.balances?, + }) + } + } + impl ::std::convert::From for Balances { + fn from(value: super::Balances) -> Self { + Self { + balances: Ok(value.balances), + } + } + } + #[derive(Clone, Debug)] + pub struct BalancesAsset { + decimals: ::std::result::Result, + name: ::std::result::Result<::std::string::String, ::std::string::String>, + symbol: ::std::result::Result, + type_: ::std::result::Result, + } + impl ::std::default::Default for BalancesAsset { + fn default() -> Self { + Self { + decimals: Err("no value supplied for decimals".to_string()), + name: Err("no value supplied for name".to_string()), + symbol: Err("no value supplied for symbol".to_string()), + type_: Err("no value supplied for type_".to_string()), + } + } + } + impl BalancesAsset { + pub fn decimals(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.decimals = value + .try_into() + .map_err(|e| format!("error converting supplied value for decimals: {}", e)); + self + } + pub fn name(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::string::String>, + T::Error: ::std::fmt::Display, + { + self.name = value + .try_into() + .map_err(|e| format!("error converting supplied value for name: {}", e)); + self + } + pub fn symbol(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.symbol = value + .try_into() + .map_err(|e| format!("error converting supplied value for symbol: {}", e)); + self + } + pub fn type_(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.type_ = value + .try_into() + .map_err(|e| format!("error converting supplied value for type_: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::BalancesAsset { + type Error = super::error::ConversionError; + fn try_from( + value: BalancesAsset, + ) -> ::std::result::Result { + Ok(Self { + decimals: value.decimals?, + name: value.name?, + symbol: value.symbol?, + type_: value.type_?, + }) + } + } + impl ::std::convert::From for BalancesAsset { + fn from(value: super::BalancesAsset) -> Self { + Self { + decimals: Ok(value.decimals), + name: Ok(value.name), + symbol: Ok(value.symbol), + type_: Ok(value.type_), + } + } + } + #[derive(Clone, Debug)] pub struct CommonSwapResponse { block_number: ::std::result::Result, @@ -62432,6 +70400,157 @@ pub mod types { } } #[derive(Clone, Debug)] + pub struct CreateAccountRequest { + name: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + } + impl ::std::default::Default for CreateAccountRequest { + fn default() -> Self { + Self { + name: Ok(Default::default()), + } + } + } + impl CreateAccountRequest { + pub fn name(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.name = value + .try_into() + .map_err(|e| format!("error converting supplied value for name: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::CreateAccountRequest { + type Error = super::error::ConversionError; + fn try_from( + value: CreateAccountRequest, + ) -> ::std::result::Result { + Ok(Self { name: value.name? }) + } + } + impl ::std::convert::From for CreateAccountRequest { + fn from(value: super::CreateAccountRequest) -> Self { + Self { + name: Ok(value.name), + } + } + } + #[derive(Clone, Debug)] + pub struct CreateCryptoDepositDestinationRequest { + account_id: ::std::result::Result, + crypto: + ::std::result::Result, + metadata: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + target: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + type_: ::std::result::Result< + super::CreateCryptoDepositDestinationRequestType, + ::std::string::String, + >, + } + impl ::std::default::Default for CreateCryptoDepositDestinationRequest { + fn default() -> Self { + Self { + account_id: Err("no value supplied for account_id".to_string()), + crypto: Err("no value supplied for crypto".to_string()), + metadata: Ok(Default::default()), + target: Ok(Default::default()), + type_: Err("no value supplied for type_".to_string()), + } + } + } + impl CreateCryptoDepositDestinationRequest { + pub fn account_id(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.account_id = value + .try_into() + .map_err(|e| format!("error converting supplied value for account_id: {}", e)); + self + } + pub fn crypto(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.crypto = value + .try_into() + .map_err(|e| format!("error converting supplied value for crypto: {}", e)); + self + } + pub fn metadata(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.metadata = value + .try_into() + .map_err(|e| format!("error converting supplied value for metadata: {}", e)); + self + } + pub fn target(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.target = value + .try_into() + .map_err(|e| format!("error converting supplied value for target: {}", e)); + self + } + pub fn type_(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.type_ = value + .try_into() + .map_err(|e| format!("error converting supplied value for type_: {}", e)); + self + } + } + impl ::std::convert::TryFrom + for super::CreateCryptoDepositDestinationRequest + { + type Error = super::error::ConversionError; + fn try_from( + value: CreateCryptoDepositDestinationRequest, + ) -> ::std::result::Result { + Ok(Self { + account_id: value.account_id?, + crypto: value.crypto?, + metadata: value.metadata?, + target: value.target?, + type_: value.type_?, + }) + } + } + impl ::std::convert::From + for CreateCryptoDepositDestinationRequest + { + fn from(value: super::CreateCryptoDepositDestinationRequest) -> Self { + Self { + account_id: Ok(value.account_id), + crypto: Ok(value.crypto), + metadata: Ok(value.metadata), + target: Ok(value.target), + type_: Ok(value.type_), + } + } + } + #[derive(Clone, Debug)] pub struct CreateDelegationForEndUserAccountBody { expires_at: ::std::result::Result< ::chrono::DateTime<::chrono::offset::Utc>, @@ -62548,6 +70667,142 @@ pub mod types { } } #[derive(Clone, Debug)] + pub struct CreateDepositDestinationCrypto { + network: ::std::result::Result, + } + impl ::std::default::Default for CreateDepositDestinationCrypto { + fn default() -> Self { + Self { + network: Err("no value supplied for network".to_string()), + } + } + } + impl CreateDepositDestinationCrypto { + pub fn network(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.network = value + .try_into() + .map_err(|e| format!("error converting supplied value for network: {}", e)); + self + } + } + impl ::std::convert::TryFrom + for super::CreateDepositDestinationCrypto + { + type Error = super::error::ConversionError; + fn try_from( + value: CreateDepositDestinationCrypto, + ) -> ::std::result::Result { + Ok(Self { + network: value.network?, + }) + } + } + impl ::std::convert::From + for CreateDepositDestinationCrypto + { + fn from(value: super::CreateDepositDestinationCrypto) -> Self { + Self { + network: Ok(value.network), + } + } + } + #[derive(Clone, Debug)] + pub struct CreateDepositDestinationRequestBase { + account_id: ::std::result::Result, + metadata: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + target: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + type_: ::std::result::Result, + } + impl ::std::default::Default for CreateDepositDestinationRequestBase { + fn default() -> Self { + Self { + account_id: Err("no value supplied for account_id".to_string()), + metadata: Ok(Default::default()), + target: Ok(Default::default()), + type_: Err("no value supplied for type_".to_string()), + } + } + } + impl CreateDepositDestinationRequestBase { + pub fn account_id(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.account_id = value + .try_into() + .map_err(|e| format!("error converting supplied value for account_id: {}", e)); + self + } + pub fn metadata(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.metadata = value + .try_into() + .map_err(|e| format!("error converting supplied value for metadata: {}", e)); + self + } + pub fn target(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.target = value + .try_into() + .map_err(|e| format!("error converting supplied value for target: {}", e)); + self + } + pub fn type_(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.type_ = value + .try_into() + .map_err(|e| format!("error converting supplied value for type_: {}", e)); + self + } + } + impl ::std::convert::TryFrom + for super::CreateDepositDestinationRequestBase + { + type Error = super::error::ConversionError; + fn try_from( + value: CreateDepositDestinationRequestBase, + ) -> ::std::result::Result { + Ok(Self { + account_id: value.account_id?, + metadata: value.metadata?, + target: value.target?, + type_: value.type_?, + }) + } + } + impl ::std::convert::From + for CreateDepositDestinationRequestBase + { + fn from(value: super::CreateDepositDestinationRequestBase) -> Self { + Self { + account_id: Ok(value.account_id), + metadata: Ok(value.metadata), + target: Ok(value.target), + type_: Ok(value.type_), + } + } + } + #[derive(Clone, Debug)] pub struct CreateEndUserBody { authentication_methods: ::std::result::Result, @@ -65041,6 +73296,177 @@ pub mod types { } } #[derive(Clone, Debug)] + pub struct CryptoDepositDestination { + account_id: ::std::result::Result, + created_at: ::std::result::Result< + ::chrono::DateTime<::chrono::offset::Utc>, + ::std::string::String, + >, + crypto: ::std::result::Result, + deposit_destination_id: + ::std::result::Result, + metadata: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + status: ::std::result::Result, + target: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + type_: + ::std::result::Result, + updated_at: ::std::result::Result< + ::chrono::DateTime<::chrono::offset::Utc>, + ::std::string::String, + >, + } + impl ::std::default::Default for CryptoDepositDestination { + fn default() -> Self { + Self { + account_id: Err("no value supplied for account_id".to_string()), + created_at: Err("no value supplied for created_at".to_string()), + crypto: Err("no value supplied for crypto".to_string()), + deposit_destination_id: Err( + "no value supplied for deposit_destination_id".to_string() + ), + metadata: Ok(Default::default()), + status: Err("no value supplied for status".to_string()), + target: Ok(Default::default()), + type_: Err("no value supplied for type_".to_string()), + updated_at: Err("no value supplied for updated_at".to_string()), + } + } + } + impl CryptoDepositDestination { + pub fn account_id(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.account_id = value + .try_into() + .map_err(|e| format!("error converting supplied value for account_id: {}", e)); + self + } + pub fn created_at(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, + T::Error: ::std::fmt::Display, + { + self.created_at = value + .try_into() + .map_err(|e| format!("error converting supplied value for created_at: {}", e)); + self + } + pub fn crypto(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.crypto = value + .try_into() + .map_err(|e| format!("error converting supplied value for crypto: {}", e)); + self + } + pub fn deposit_destination_id(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.deposit_destination_id = value.try_into().map_err(|e| { + format!( + "error converting supplied value for deposit_destination_id: {}", + e + ) + }); + self + } + pub fn metadata(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.metadata = value + .try_into() + .map_err(|e| format!("error converting supplied value for metadata: {}", e)); + self + } + pub fn status(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.status = value + .try_into() + .map_err(|e| format!("error converting supplied value for status: {}", e)); + self + } + pub fn target(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.target = value + .try_into() + .map_err(|e| format!("error converting supplied value for target: {}", e)); + self + } + pub fn type_(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.type_ = value + .try_into() + .map_err(|e| format!("error converting supplied value for type_: {}", e)); + self + } + pub fn updated_at(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, + T::Error: ::std::fmt::Display, + { + self.updated_at = value + .try_into() + .map_err(|e| format!("error converting supplied value for updated_at: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::CryptoDepositDestination { + type Error = super::error::ConversionError; + fn try_from( + value: CryptoDepositDestination, + ) -> ::std::result::Result { + Ok(Self { + account_id: value.account_id?, + created_at: value.created_at?, + crypto: value.crypto?, + deposit_destination_id: value.deposit_destination_id?, + metadata: value.metadata?, + status: value.status?, + target: value.target?, + type_: value.type_?, + updated_at: value.updated_at?, + }) + } + } + impl ::std::convert::From for CryptoDepositDestination { + fn from(value: super::CryptoDepositDestination) -> Self { + Self { + account_id: Ok(value.account_id), + created_at: Ok(value.created_at), + crypto: Ok(value.crypto), + deposit_destination_id: Ok(value.deposit_destination_id), + metadata: Ok(value.metadata), + status: Ok(value.status), + target: Ok(value.target), + type_: Ok(value.type_), + updated_at: Ok(value.updated_at), + } + } + } + #[derive(Clone, Debug)] pub struct DateOfBirth { day: ::std::result::Result< ::std::option::Option, @@ -65118,6 +73544,543 @@ pub mod types { } } #[derive(Clone, Debug)] + pub struct DepositDestinationCrypto { + address: ::std::result::Result, + network: ::std::result::Result, + } + impl ::std::default::Default for DepositDestinationCrypto { + fn default() -> Self { + Self { + address: Err("no value supplied for address".to_string()), + network: Err("no value supplied for network".to_string()), + } + } + } + impl DepositDestinationCrypto { + pub fn address(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.address = value + .try_into() + .map_err(|e| format!("error converting supplied value for address: {}", e)); + self + } + pub fn network(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.network = value + .try_into() + .map_err(|e| format!("error converting supplied value for network: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::DepositDestinationCrypto { + type Error = super::error::ConversionError; + fn try_from( + value: DepositDestinationCrypto, + ) -> ::std::result::Result { + Ok(Self { + address: value.address?, + network: value.network?, + }) + } + } + impl ::std::convert::From for DepositDestinationCrypto { + fn from(value: super::DepositDestinationCrypto) -> Self { + Self { + address: Ok(value.address), + network: Ok(value.network), + } + } + } + #[derive(Clone, Debug)] + pub struct DepositDestinationReference { + id: ::std::result::Result, + } + impl ::std::default::Default for DepositDestinationReference { + fn default() -> Self { + Self { + id: Err("no value supplied for id".to_string()), + } + } + } + impl DepositDestinationReference { + pub fn id(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.id = value + .try_into() + .map_err(|e| format!("error converting supplied value for id: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::DepositDestinationReference { + type Error = super::error::ConversionError; + fn try_from( + value: DepositDestinationReference, + ) -> ::std::result::Result { + Ok(Self { id: value.id? }) + } + } + impl ::std::convert::From for DepositDestinationReference { + fn from(value: super::DepositDestinationReference) -> Self { + Self { id: Ok(value.id) } + } + } + #[derive(Clone, Debug)] + pub struct DepositDestinationTargetAccount { + account_id: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + asset: ::std::result::Result, + } + impl ::std::default::Default for DepositDestinationTargetAccount { + fn default() -> Self { + Self { + account_id: Ok(Default::default()), + asset: Err("no value supplied for asset".to_string()), + } + } + } + impl DepositDestinationTargetAccount { + pub fn account_id(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.account_id = value + .try_into() + .map_err(|e| format!("error converting supplied value for account_id: {}", e)); + self + } + pub fn asset(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.asset = value + .try_into() + .map_err(|e| format!("error converting supplied value for asset: {}", e)); + self + } + } + impl ::std::convert::TryFrom + for super::DepositDestinationTargetAccount + { + type Error = super::error::ConversionError; + fn try_from( + value: DepositDestinationTargetAccount, + ) -> ::std::result::Result { + Ok(Self { + account_id: value.account_id?, + asset: value.asset?, + }) + } + } + impl ::std::convert::From + for DepositDestinationTargetAccount + { + fn from(value: super::DepositDestinationTargetAccount) -> Self { + Self { + account_id: Ok(value.account_id), + asset: Ok(value.asset), + } + } + } + #[derive(Clone, Debug)] + pub struct DepositTravelRuleBeneficiary { + name: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + } + impl ::std::default::Default for DepositTravelRuleBeneficiary { + fn default() -> Self { + Self { + name: Ok(Default::default()), + } + } + } + impl DepositTravelRuleBeneficiary { + pub fn name(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.name = value + .try_into() + .map_err(|e| format!("error converting supplied value for name: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::DepositTravelRuleBeneficiary { + type Error = super::error::ConversionError; + fn try_from( + value: DepositTravelRuleBeneficiary, + ) -> ::std::result::Result { + Ok(Self { name: value.name? }) + } + } + impl ::std::convert::From for DepositTravelRuleBeneficiary { + fn from(value: super::DepositTravelRuleBeneficiary) -> Self { + Self { + name: Ok(value.name), + } + } + } + #[derive(Clone, Debug)] + pub struct DepositTravelRuleOriginator { + address: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + date_of_birth: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + name: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + personal_id: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + virtual_asset_service_provider: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + wallet_type: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + } + impl ::std::default::Default for DepositTravelRuleOriginator { + fn default() -> Self { + Self { + address: Ok(Default::default()), + date_of_birth: Ok(Default::default()), + name: Ok(Default::default()), + personal_id: Ok(Default::default()), + virtual_asset_service_provider: Ok(Default::default()), + wallet_type: Ok(Default::default()), + } + } + } + impl DepositTravelRuleOriginator { + pub fn address(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.address = value + .try_into() + .map_err(|e| format!("error converting supplied value for address: {}", e)); + self + } + pub fn date_of_birth(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.date_of_birth = value.try_into().map_err(|e| { + format!("error converting supplied value for date_of_birth: {}", e) + }); + self + } + pub fn name(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.name = value + .try_into() + .map_err(|e| format!("error converting supplied value for name: {}", e)); + self + } + pub fn personal_id(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.personal_id = value + .try_into() + .map_err(|e| format!("error converting supplied value for personal_id: {}", e)); + self + } + pub fn virtual_asset_service_provider(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.virtual_asset_service_provider = value.try_into().map_err(|e| { + format!( + "error converting supplied value for virtual_asset_service_provider: {}", + e + ) + }); + self + } + pub fn wallet_type(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + ::std::option::Option, + >, + T::Error: ::std::fmt::Display, + { + self.wallet_type = value + .try_into() + .map_err(|e| format!("error converting supplied value for wallet_type: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::DepositTravelRuleOriginator { + type Error = super::error::ConversionError; + fn try_from( + value: DepositTravelRuleOriginator, + ) -> ::std::result::Result { + Ok(Self { + address: value.address?, + date_of_birth: value.date_of_birth?, + name: value.name?, + personal_id: value.personal_id?, + virtual_asset_service_provider: value.virtual_asset_service_provider?, + wallet_type: value.wallet_type?, + }) + } + } + impl ::std::convert::From for DepositTravelRuleOriginator { + fn from(value: super::DepositTravelRuleOriginator) -> Self { + Self { + address: Ok(value.address), + date_of_birth: Ok(value.date_of_birth), + name: Ok(value.name), + personal_id: Ok(value.personal_id), + virtual_asset_service_provider: Ok(value.virtual_asset_service_provider), + wallet_type: Ok(value.wallet_type), + } + } + } + #[derive(Clone, Debug)] + pub struct DepositTravelRuleRequest { + beneficiary: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + is_self: ::std::result::Result<::std::option::Option, ::std::string::String>, + originator: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + } + impl ::std::default::Default for DepositTravelRuleRequest { + fn default() -> Self { + Self { + beneficiary: Ok(Default::default()), + is_self: Ok(Default::default()), + originator: Ok(Default::default()), + } + } + } + impl DepositTravelRuleRequest { + pub fn beneficiary(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + ::std::option::Option, + >, + T::Error: ::std::fmt::Display, + { + self.beneficiary = value + .try_into() + .map_err(|e| format!("error converting supplied value for beneficiary: {}", e)); + self + } + pub fn is_self(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.is_self = value + .try_into() + .map_err(|e| format!("error converting supplied value for is_self: {}", e)); + self + } + pub fn originator(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + ::std::option::Option, + >, + T::Error: ::std::fmt::Display, + { + self.originator = value + .try_into() + .map_err(|e| format!("error converting supplied value for originator: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::DepositTravelRuleRequest { + type Error = super::error::ConversionError; + fn try_from( + value: DepositTravelRuleRequest, + ) -> ::std::result::Result { + Ok(Self { + beneficiary: value.beneficiary?, + is_self: value.is_self?, + originator: value.originator?, + }) + } + } + impl ::std::convert::From for DepositTravelRuleRequest { + fn from(value: super::DepositTravelRuleRequest) -> Self { + Self { + beneficiary: Ok(value.beneficiary), + is_self: Ok(value.is_self), + originator: Ok(value.originator), + } + } + } + #[derive(Clone, Debug)] + pub struct DepositTravelRuleResponse { + missing_fields: ::std::result::Result< + ::std::vec::Vec<::std::string::String>, + ::std::string::String, + >, + reason: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + status: ::std::result::Result, + } + impl ::std::default::Default for DepositTravelRuleResponse { + fn default() -> Self { + Self { + missing_fields: Ok(Default::default()), + reason: Ok(Default::default()), + status: Err("no value supplied for status".to_string()), + } + } + } + impl DepositTravelRuleResponse { + pub fn missing_fields(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::vec::Vec<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.missing_fields = value.try_into().map_err(|e| { + format!("error converting supplied value for missing_fields: {}", e) + }); + self + } + pub fn reason(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.reason = value + .try_into() + .map_err(|e| format!("error converting supplied value for reason: {}", e)); + self + } + pub fn status(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.status = value + .try_into() + .map_err(|e| format!("error converting supplied value for status: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::DepositTravelRuleResponse { + type Error = super::error::ConversionError; + fn try_from( + value: DepositTravelRuleResponse, + ) -> ::std::result::Result { + Ok(Self { + missing_fields: value.missing_fields?, + reason: value.reason?, + status: value.status?, + }) + } + } + impl ::std::convert::From for DepositTravelRuleResponse { + fn from(value: super::DepositTravelRuleResponse) -> Self { + Self { + missing_fields: Ok(value.missing_fields), + reason: Ok(value.reason), + status: Ok(value.status), + } + } + } + #[derive(Clone, Debug)] + pub struct DepositTravelRuleVasp { + identifier: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + name: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + } + impl ::std::default::Default for DepositTravelRuleVasp { + fn default() -> Self { + Self { + identifier: Ok(Default::default()), + name: Ok(Default::default()), + } + } + } + impl DepositTravelRuleVasp { + pub fn identifier(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.identifier = value + .try_into() + .map_err(|e| format!("error converting supplied value for identifier: {}", e)); + self + } + pub fn name(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.name = value + .try_into() + .map_err(|e| format!("error converting supplied value for name: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::DepositTravelRuleVasp { + type Error = super::error::ConversionError; + fn try_from( + value: DepositTravelRuleVasp, + ) -> ::std::result::Result { + Ok(Self { + identifier: value.identifier?, + name: value.name?, + }) + } + } + impl ::std::convert::From for DepositTravelRuleVasp { + fn from(value: super::DepositTravelRuleVasp) -> Self { + Self { + identifier: Ok(value.identifier), + name: Ok(value.name), + } + } + } + #[derive(Clone, Debug)] pub struct DeveloperJwtAuthentication { kid: ::std::result::Result<::std::string::String, ::std::string::String>, sub: ::std::result::Result<::std::string::String, ::std::string::String>, @@ -65387,6 +74350,46 @@ pub mod types { } } #[derive(Clone, Debug)] + pub struct EmailAddress { + email: ::std::result::Result<::std::string::String, ::std::string::String>, + } + impl ::std::default::Default for EmailAddress { + fn default() -> Self { + Self { + email: Err("no value supplied for email".to_string()), + } + } + } + impl EmailAddress { + pub fn email(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::string::String>, + T::Error: ::std::fmt::Display, + { + self.email = value + .try_into() + .map_err(|e| format!("error converting supplied value for email: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::EmailAddress { + type Error = super::error::ConversionError; + fn try_from( + value: EmailAddress, + ) -> ::std::result::Result { + Ok(Self { + email: value.email?, + }) + } + } + impl ::std::convert::From for EmailAddress { + fn from(value: super::EmailAddress) -> Self { + Self { + email: Ok(value.email), + } + } + } + #[derive(Clone, Debug)] pub struct EmailAuthentication { email: ::std::result::Result<::std::string::String, ::std::string::String>, type_: ::std::result::Result, @@ -65441,6 +74444,60 @@ pub mod types { } } #[derive(Clone, Debug)] + pub struct EmailInstrument { + asset: ::std::result::Result, + email: ::std::result::Result<::std::string::String, ::std::string::String>, + } + impl ::std::default::Default for EmailInstrument { + fn default() -> Self { + Self { + asset: Err("no value supplied for asset".to_string()), + email: Err("no value supplied for email".to_string()), + } + } + } + impl EmailInstrument { + pub fn asset(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.asset = value + .try_into() + .map_err(|e| format!("error converting supplied value for asset: {}", e)); + self + } + pub fn email(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::string::String>, + T::Error: ::std::fmt::Display, + { + self.email = value + .try_into() + .map_err(|e| format!("error converting supplied value for email: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::EmailInstrument { + type Error = super::error::ConversionError; + fn try_from( + value: EmailInstrument, + ) -> ::std::result::Result { + Ok(Self { + asset: value.asset?, + email: value.email?, + }) + } + } + impl ::std::convert::From for EmailInstrument { + fn from(value: super::EmailInstrument) -> Self { + Self { + asset: Ok(value.asset), + email: Ok(value.email), + } + } + } + #[derive(Clone, Debug)] pub struct EndUser { authentication_methods: ::std::result::Result, @@ -67634,6 +76691,212 @@ pub mod types { } } #[derive(Clone, Debug)] + pub struct FedwireDetails { + account_last4: + ::std::result::Result, + asset: ::std::result::Result<::std::string::String, ::std::string::String>, + bank_name: ::std::result::Result<::std::string::String, ::std::string::String>, + routing_number: + ::std::result::Result, + } + impl ::std::default::Default for FedwireDetails { + fn default() -> Self { + Self { + account_last4: Err("no value supplied for account_last4".to_string()), + asset: Err("no value supplied for asset".to_string()), + bank_name: Err("no value supplied for bank_name".to_string()), + routing_number: Err("no value supplied for routing_number".to_string()), + } + } + } + impl FedwireDetails { + pub fn account_last4(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.account_last4 = value.try_into().map_err(|e| { + format!("error converting supplied value for account_last4: {}", e) + }); + self + } + pub fn asset(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::string::String>, + T::Error: ::std::fmt::Display, + { + self.asset = value + .try_into() + .map_err(|e| format!("error converting supplied value for asset: {}", e)); + self + } + pub fn bank_name(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::string::String>, + T::Error: ::std::fmt::Display, + { + self.bank_name = value + .try_into() + .map_err(|e| format!("error converting supplied value for bank_name: {}", e)); + self + } + pub fn routing_number(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.routing_number = value.try_into().map_err(|e| { + format!("error converting supplied value for routing_number: {}", e) + }); + self + } + } + impl ::std::convert::TryFrom for super::FedwireDetails { + type Error = super::error::ConversionError; + fn try_from( + value: FedwireDetails, + ) -> ::std::result::Result { + Ok(Self { + account_last4: value.account_last4?, + asset: value.asset?, + bank_name: value.bank_name?, + routing_number: value.routing_number?, + }) + } + } + impl ::std::convert::From for FedwireDetails { + fn from(value: super::FedwireDetails) -> Self { + Self { + account_last4: Ok(value.account_last4), + asset: Ok(value.asset), + bank_name: Ok(value.bank_name), + routing_number: Ok(value.routing_number), + } + } + } + #[derive(Clone, Debug)] + pub struct FedwirePaymentMethod { + active: ::std::result::Result, + created_at: ::std::result::Result< + ::chrono::DateTime<::chrono::offset::Utc>, + ::std::string::String, + >, + fedwire: ::std::result::Result, + payment_method_id: ::std::result::Result, + payment_rail: ::std::result::Result< + super::FedwirePaymentMethodPaymentRail, + ::std::string::String, + >, + updated_at: ::std::result::Result< + ::chrono::DateTime<::chrono::offset::Utc>, + ::std::string::String, + >, + } + impl ::std::default::Default for FedwirePaymentMethod { + fn default() -> Self { + Self { + active: Err("no value supplied for active".to_string()), + created_at: Err("no value supplied for created_at".to_string()), + fedwire: Err("no value supplied for fedwire".to_string()), + payment_method_id: Err("no value supplied for payment_method_id".to_string()), + payment_rail: Err("no value supplied for payment_rail".to_string()), + updated_at: Err("no value supplied for updated_at".to_string()), + } + } + } + impl FedwirePaymentMethod { + pub fn active(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.active = value + .try_into() + .map_err(|e| format!("error converting supplied value for active: {}", e)); + self + } + pub fn created_at(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, + T::Error: ::std::fmt::Display, + { + self.created_at = value + .try_into() + .map_err(|e| format!("error converting supplied value for created_at: {}", e)); + self + } + pub fn fedwire(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.fedwire = value + .try_into() + .map_err(|e| format!("error converting supplied value for fedwire: {}", e)); + self + } + pub fn payment_method_id(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.payment_method_id = value.try_into().map_err(|e| { + format!( + "error converting supplied value for payment_method_id: {}", + e + ) + }); + self + } + pub fn payment_rail(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.payment_rail = value.try_into().map_err(|e| { + format!("error converting supplied value for payment_rail: {}", e) + }); + self + } + pub fn updated_at(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, + T::Error: ::std::fmt::Display, + { + self.updated_at = value + .try_into() + .map_err(|e| format!("error converting supplied value for updated_at: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::FedwirePaymentMethod { + type Error = super::error::ConversionError; + fn try_from( + value: FedwirePaymentMethod, + ) -> ::std::result::Result { + Ok(Self { + active: value.active?, + created_at: value.created_at?, + fedwire: value.fedwire?, + payment_method_id: value.payment_method_id?, + payment_rail: value.payment_rail?, + updated_at: value.updated_at?, + }) + } + } + impl ::std::convert::From for FedwirePaymentMethod { + fn from(value: super::FedwirePaymentMethod) -> Self { + Self { + active: Ok(value.active), + created_at: Ok(value.created_at), + fedwire: Ok(value.fedwire), + payment_method_id: Ok(value.payment_method_id), + payment_rail: Ok(value.payment_rail), + updated_at: Ok(value.updated_at), + } + } + } + #[derive(Clone, Debug)] pub struct GetDelegationForEndUserAccountResponse { expires_at: ::std::result::Result< ::chrono::DateTime<::chrono::offset::Utc>, @@ -69003,6 +78266,63 @@ pub mod types { } } #[derive(Clone, Debug)] + pub struct ListBalancesResponse { + balances: ::std::result::Result<::std::vec::Vec, ::std::string::String>, + next_page_token: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + } + impl ::std::default::Default for ListBalancesResponse { + fn default() -> Self { + Self { + balances: Err("no value supplied for balances".to_string()), + next_page_token: Ok(Default::default()), + } + } + } + impl ListBalancesResponse { + pub fn balances(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::vec::Vec>, + T::Error: ::std::fmt::Display, + { + self.balances = value + .try_into() + .map_err(|e| format!("error converting supplied value for balances: {}", e)); + self + } + pub fn next_page_token(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.next_page_token = value.try_into().map_err(|e| { + format!("error converting supplied value for next_page_token: {}", e) + }); + self + } + } + impl ::std::convert::TryFrom for super::ListBalancesResponse { + type Error = super::error::ConversionError; + fn try_from( + value: ListBalancesResponse, + ) -> ::std::result::Result { + Ok(Self { + balances: value.balances?, + next_page_token: value.next_page_token?, + }) + } + } + impl ::std::convert::From for ListBalancesResponse { + fn from(value: super::ListBalancesResponse) -> Self { + Self { + balances: Ok(value.balances), + next_page_token: Ok(value.next_page_token), + } + } + } + #[derive(Clone, Debug)] pub struct ListDataTokenBalancesResponse { balances: ::std::result::Result<::std::vec::Vec, ::std::string::String>, @@ -69063,6 +78383,75 @@ pub mod types { } } #[derive(Clone, Debug)] + pub struct ListDepositDestinationsResponse { + deposit_destinations: ::std::result::Result< + ::std::vec::Vec, + ::std::string::String, + >, + next_page_token: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + } + impl ::std::default::Default for ListDepositDestinationsResponse { + fn default() -> Self { + Self { + deposit_destinations: Err( + "no value supplied for deposit_destinations".to_string() + ), + next_page_token: Ok(Default::default()), + } + } + } + impl ListDepositDestinationsResponse { + pub fn deposit_destinations(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::vec::Vec>, + T::Error: ::std::fmt::Display, + { + self.deposit_destinations = value.try_into().map_err(|e| { + format!( + "error converting supplied value for deposit_destinations: {}", + e + ) + }); + self + } + pub fn next_page_token(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.next_page_token = value.try_into().map_err(|e| { + format!("error converting supplied value for next_page_token: {}", e) + }); + self + } + } + impl ::std::convert::TryFrom + for super::ListDepositDestinationsResponse + { + type Error = super::error::ConversionError; + fn try_from( + value: ListDepositDestinationsResponse, + ) -> ::std::result::Result { + Ok(Self { + deposit_destinations: value.deposit_destinations?, + next_page_token: value.next_page_token?, + }) + } + } + impl ::std::convert::From + for ListDepositDestinationsResponse + { + fn from(value: super::ListDepositDestinationsResponse) -> Self { + Self { + deposit_destinations: Ok(value.deposit_destinations), + next_page_token: Ok(value.next_page_token), + } + } + } + #[derive(Clone, Debug)] pub struct ListEndUsersResponse { end_users: ::std::result::Result<::std::vec::Vec, ::std::string::String>, @@ -69297,6 +78686,127 @@ pub mod types { } } #[derive(Clone, Debug)] + pub struct ListFoundationAccountsResponse { + accounts: ::std::result::Result<::std::vec::Vec, ::std::string::String>, + next_page_token: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + } + impl ::std::default::Default for ListFoundationAccountsResponse { + fn default() -> Self { + Self { + accounts: Err("no value supplied for accounts".to_string()), + next_page_token: Ok(Default::default()), + } + } + } + impl ListFoundationAccountsResponse { + pub fn accounts(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::vec::Vec>, + T::Error: ::std::fmt::Display, + { + self.accounts = value + .try_into() + .map_err(|e| format!("error converting supplied value for accounts: {}", e)); + self + } + pub fn next_page_token(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.next_page_token = value.try_into().map_err(|e| { + format!("error converting supplied value for next_page_token: {}", e) + }); + self + } + } + impl ::std::convert::TryFrom + for super::ListFoundationAccountsResponse + { + type Error = super::error::ConversionError; + fn try_from( + value: ListFoundationAccountsResponse, + ) -> ::std::result::Result { + Ok(Self { + accounts: value.accounts?, + next_page_token: value.next_page_token?, + }) + } + } + impl ::std::convert::From + for ListFoundationAccountsResponse + { + fn from(value: super::ListFoundationAccountsResponse) -> Self { + Self { + accounts: Ok(value.accounts), + next_page_token: Ok(value.next_page_token), + } + } + } + #[derive(Clone, Debug)] + pub struct ListPaymentMethodsResponse { + next_page_token: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + payment_methods: ::std::result::Result< + ::std::vec::Vec, + ::std::string::String, + >, + } + impl ::std::default::Default for ListPaymentMethodsResponse { + fn default() -> Self { + Self { + next_page_token: Ok(Default::default()), + payment_methods: Err("no value supplied for payment_methods".to_string()), + } + } + } + impl ListPaymentMethodsResponse { + pub fn next_page_token(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.next_page_token = value.try_into().map_err(|e| { + format!("error converting supplied value for next_page_token: {}", e) + }); + self + } + pub fn payment_methods(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::vec::Vec>, + T::Error: ::std::fmt::Display, + { + self.payment_methods = value.try_into().map_err(|e| { + format!("error converting supplied value for payment_methods: {}", e) + }); + self + } + } + impl ::std::convert::TryFrom for super::ListPaymentMethodsResponse { + type Error = super::error::ConversionError; + fn try_from( + value: ListPaymentMethodsResponse, + ) -> ::std::result::Result { + Ok(Self { + next_page_token: value.next_page_token?, + payment_methods: value.payment_methods?, + }) + } + } + impl ::std::convert::From for ListPaymentMethodsResponse { + fn from(value: super::ListPaymentMethodsResponse) -> Self { + Self { + next_page_token: Ok(value.next_page_token), + payment_methods: Ok(value.payment_methods), + } + } + } + #[derive(Clone, Debug)] pub struct ListPoliciesResponse { next_page_token: ::std::result::Result< ::std::option::Option<::std::string::String>, @@ -69582,6 +79092,64 @@ pub mod types { } } #[derive(Clone, Debug)] + pub struct ListTransfersResponse { + next_page_token: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + transfers: + ::std::result::Result<::std::vec::Vec, ::std::string::String>, + } + impl ::std::default::Default for ListTransfersResponse { + fn default() -> Self { + Self { + next_page_token: Ok(Default::default()), + transfers: Err("no value supplied for transfers".to_string()), + } + } + } + impl ListTransfersResponse { + pub fn next_page_token(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.next_page_token = value.try_into().map_err(|e| { + format!("error converting supplied value for next_page_token: {}", e) + }); + self + } + pub fn transfers(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::vec::Vec>, + T::Error: ::std::fmt::Display, + { + self.transfers = value + .try_into() + .map_err(|e| format!("error converting supplied value for transfers: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::ListTransfersResponse { + type Error = super::error::ConversionError; + fn try_from( + value: ListTransfersResponse, + ) -> ::std::result::Result { + Ok(Self { + next_page_token: value.next_page_token?, + transfers: value.transfers?, + }) + } + } + impl ::std::convert::From for ListTransfersResponse { + fn from(value: super::ListTransfersResponse) -> Self { + Self { + next_page_token: Ok(value.next_page_token), + transfers: Ok(value.transfers), + } + } + } + #[derive(Clone, Debug)] pub struct LookupEndUserResponse { end_users: ::std::result::Result<::std::vec::Vec, ::std::string::String>, @@ -70039,6 +79607,91 @@ pub mod types { } } #[derive(Clone, Debug)] + pub struct OnchainAddress { + address: ::std::result::Result, + asset: ::std::result::Result, + destination_tag: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + network: ::std::result::Result, + } + impl ::std::default::Default for OnchainAddress { + fn default() -> Self { + Self { + address: Err("no value supplied for address".to_string()), + asset: Err("no value supplied for asset".to_string()), + destination_tag: Ok(Default::default()), + network: Err("no value supplied for network".to_string()), + } + } + } + impl OnchainAddress { + pub fn address(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.address = value + .try_into() + .map_err(|e| format!("error converting supplied value for address: {}", e)); + self + } + pub fn asset(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.asset = value + .try_into() + .map_err(|e| format!("error converting supplied value for asset: {}", e)); + self + } + pub fn destination_tag(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.destination_tag = value.try_into().map_err(|e| { + format!("error converting supplied value for destination_tag: {}", e) + }); + self + } + pub fn network(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.network = value + .try_into() + .map_err(|e| format!("error converting supplied value for network: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::OnchainAddress { + type Error = super::error::ConversionError; + fn try_from( + value: OnchainAddress, + ) -> ::std::result::Result { + Ok(Self { + address: value.address?, + asset: value.asset?, + destination_tag: value.destination_tag?, + network: value.network?, + }) + } + } + impl ::std::convert::From for OnchainAddress { + fn from(value: super::OnchainAddress) -> Self { + Self { + address: Ok(value.address), + asset: Ok(value.asset), + destination_tag: Ok(value.destination_tag), + network: Ok(value.network), + } + } + } + #[derive(Clone, Debug)] pub struct OnchainDataColumnSchema { description: ::std::result::Result< ::std::option::Option, @@ -71433,6 +81086,355 @@ pub mod types { } } #[derive(Clone, Debug)] + pub struct OriginatingBankAccountUs { + account_last4: ::std::result::Result< + super::OriginatingBankAccountUsAccountLast4, + ::std::string::String, + >, + bank_name: ::std::result::Result<::std::string::String, ::std::string::String>, + currency: ::std::result::Result<::std::string::String, ::std::string::String>, + } + impl ::std::default::Default for OriginatingBankAccountUs { + fn default() -> Self { + Self { + account_last4: Err("no value supplied for account_last4".to_string()), + bank_name: Err("no value supplied for bank_name".to_string()), + currency: Err("no value supplied for currency".to_string()), + } + } + } + impl OriginatingBankAccountUs { + pub fn account_last4(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.account_last4 = value.try_into().map_err(|e| { + format!("error converting supplied value for account_last4: {}", e) + }); + self + } + pub fn bank_name(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::string::String>, + T::Error: ::std::fmt::Display, + { + self.bank_name = value + .try_into() + .map_err(|e| format!("error converting supplied value for bank_name: {}", e)); + self + } + pub fn currency(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::string::String>, + T::Error: ::std::fmt::Display, + { + self.currency = value + .try_into() + .map_err(|e| format!("error converting supplied value for currency: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::OriginatingBankAccountUs { + type Error = super::error::ConversionError; + fn try_from( + value: OriginatingBankAccountUs, + ) -> ::std::result::Result { + Ok(Self { + account_last4: value.account_last4?, + bank_name: value.bank_name?, + currency: value.currency?, + }) + } + } + impl ::std::convert::From for OriginatingBankAccountUs { + fn from(value: super::OriginatingBankAccountUs) -> Self { + Self { + account_last4: Ok(value.account_last4), + bank_name: Ok(value.bank_name), + currency: Ok(value.currency), + } + } + } + #[derive(Clone, Debug)] + pub struct PaymentMethod { + asset: ::std::result::Result, + payment_method_id: ::std::result::Result<::std::string::String, ::std::string::String>, + } + impl ::std::default::Default for PaymentMethod { + fn default() -> Self { + Self { + asset: Err("no value supplied for asset".to_string()), + payment_method_id: Err("no value supplied for payment_method_id".to_string()), + } + } + } + impl PaymentMethod { + pub fn asset(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.asset = value + .try_into() + .map_err(|e| format!("error converting supplied value for asset: {}", e)); + self + } + pub fn payment_method_id(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::string::String>, + T::Error: ::std::fmt::Display, + { + self.payment_method_id = value.try_into().map_err(|e| { + format!( + "error converting supplied value for payment_method_id: {}", + e + ) + }); + self + } + } + impl ::std::convert::TryFrom for super::PaymentMethod { + type Error = super::error::ConversionError; + fn try_from( + value: PaymentMethod, + ) -> ::std::result::Result { + Ok(Self { + asset: value.asset?, + payment_method_id: value.payment_method_id?, + }) + } + } + impl ::std::convert::From for PaymentMethod { + fn from(value: super::PaymentMethod) -> Self { + Self { + asset: Ok(value.asset), + payment_method_id: Ok(value.payment_method_id), + } + } + } + #[derive(Clone, Debug)] + pub struct PaymentMethodBase { + active: ::std::result::Result, + created_at: ::std::result::Result< + ::chrono::DateTime<::chrono::offset::Utc>, + ::std::string::String, + >, + payment_method_id: ::std::result::Result, + updated_at: ::std::result::Result< + ::chrono::DateTime<::chrono::offset::Utc>, + ::std::string::String, + >, + } + impl ::std::default::Default for PaymentMethodBase { + fn default() -> Self { + Self { + active: Err("no value supplied for active".to_string()), + created_at: Err("no value supplied for created_at".to_string()), + payment_method_id: Err("no value supplied for payment_method_id".to_string()), + updated_at: Err("no value supplied for updated_at".to_string()), + } + } + } + impl PaymentMethodBase { + pub fn active(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.active = value + .try_into() + .map_err(|e| format!("error converting supplied value for active: {}", e)); + self + } + pub fn created_at(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, + T::Error: ::std::fmt::Display, + { + self.created_at = value + .try_into() + .map_err(|e| format!("error converting supplied value for created_at: {}", e)); + self + } + pub fn payment_method_id(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.payment_method_id = value.try_into().map_err(|e| { + format!( + "error converting supplied value for payment_method_id: {}", + e + ) + }); + self + } + pub fn updated_at(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, + T::Error: ::std::fmt::Display, + { + self.updated_at = value + .try_into() + .map_err(|e| format!("error converting supplied value for updated_at: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::PaymentMethodBase { + type Error = super::error::ConversionError; + fn try_from( + value: PaymentMethodBase, + ) -> ::std::result::Result { + Ok(Self { + active: value.active?, + created_at: value.created_at?, + payment_method_id: value.payment_method_id?, + updated_at: value.updated_at?, + }) + } + } + impl ::std::convert::From for PaymentMethodBase { + fn from(value: super::PaymentMethodBase) -> Self { + Self { + active: Ok(value.active), + created_at: Ok(value.created_at), + payment_method_id: Ok(value.payment_method_id), + updated_at: Ok(value.updated_at), + } + } + } + #[derive(Clone, Debug)] + pub struct PhysicalAddress { + city: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + country_code: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + line1: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + line2: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + post_code: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + state: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + } + impl ::std::default::Default for PhysicalAddress { + fn default() -> Self { + Self { + city: Ok(Default::default()), + country_code: Ok(Default::default()), + line1: Ok(Default::default()), + line2: Ok(Default::default()), + post_code: Ok(Default::default()), + state: Ok(Default::default()), + } + } + } + impl PhysicalAddress { + pub fn city(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.city = value + .try_into() + .map_err(|e| format!("error converting supplied value for city: {}", e)); + self + } + pub fn country_code(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + ::std::option::Option, + >, + T::Error: ::std::fmt::Display, + { + self.country_code = value.try_into().map_err(|e| { + format!("error converting supplied value for country_code: {}", e) + }); + self + } + pub fn line1(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.line1 = value + .try_into() + .map_err(|e| format!("error converting supplied value for line1: {}", e)); + self + } + pub fn line2(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.line2 = value + .try_into() + .map_err(|e| format!("error converting supplied value for line2: {}", e)); + self + } + pub fn post_code(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.post_code = value + .try_into() + .map_err(|e| format!("error converting supplied value for post_code: {}", e)); + self + } + pub fn state(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.state = value + .try_into() + .map_err(|e| format!("error converting supplied value for state: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::PhysicalAddress { + type Error = super::error::ConversionError; + fn try_from( + value: PhysicalAddress, + ) -> ::std::result::Result { + Ok(Self { + city: value.city?, + country_code: value.country_code?, + line1: value.line1?, + line2: value.line2?, + post_code: value.post_code?, + state: value.state?, + }) + } + } + impl ::std::convert::From for PhysicalAddress { + fn from(value: super::PhysicalAddress) -> Self { + Self { + city: Ok(value.city), + country_code: Ok(value.country_code), + line1: Ok(value.line1), + line2: Ok(value.line2), + post_code: Ok(value.post_code), + state: Ok(value.state), + } + } + } + #[derive(Clone, Debug)] pub struct Policy { created_at: ::std::result::Result<::std::string::String, ::std::string::String>, description: ::std::result::Result< @@ -73907,6 +83909,208 @@ pub mod types { } } #[derive(Clone, Debug)] + pub struct SepaDetails { + asset: ::std::result::Result<::std::string::String, ::std::string::String>, + bank_name: ::std::result::Result<::std::string::String, ::std::string::String>, + bic: ::std::result::Result, + iban_last4: ::std::result::Result, + } + impl ::std::default::Default for SepaDetails { + fn default() -> Self { + Self { + asset: Err("no value supplied for asset".to_string()), + bank_name: Err("no value supplied for bank_name".to_string()), + bic: Err("no value supplied for bic".to_string()), + iban_last4: Err("no value supplied for iban_last4".to_string()), + } + } + } + impl SepaDetails { + pub fn asset(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::string::String>, + T::Error: ::std::fmt::Display, + { + self.asset = value + .try_into() + .map_err(|e| format!("error converting supplied value for asset: {}", e)); + self + } + pub fn bank_name(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::string::String>, + T::Error: ::std::fmt::Display, + { + self.bank_name = value + .try_into() + .map_err(|e| format!("error converting supplied value for bank_name: {}", e)); + self + } + pub fn bic(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.bic = value + .try_into() + .map_err(|e| format!("error converting supplied value for bic: {}", e)); + self + } + pub fn iban_last4(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.iban_last4 = value + .try_into() + .map_err(|e| format!("error converting supplied value for iban_last4: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::SepaDetails { + type Error = super::error::ConversionError; + fn try_from( + value: SepaDetails, + ) -> ::std::result::Result { + Ok(Self { + asset: value.asset?, + bank_name: value.bank_name?, + bic: value.bic?, + iban_last4: value.iban_last4?, + }) + } + } + impl ::std::convert::From for SepaDetails { + fn from(value: super::SepaDetails) -> Self { + Self { + asset: Ok(value.asset), + bank_name: Ok(value.bank_name), + bic: Ok(value.bic), + iban_last4: Ok(value.iban_last4), + } + } + } + #[derive(Clone, Debug)] + pub struct SepaPaymentMethod { + active: ::std::result::Result, + created_at: ::std::result::Result< + ::chrono::DateTime<::chrono::offset::Utc>, + ::std::string::String, + >, + payment_method_id: ::std::result::Result, + payment_rail: + ::std::result::Result, + sepa: ::std::result::Result, + updated_at: ::std::result::Result< + ::chrono::DateTime<::chrono::offset::Utc>, + ::std::string::String, + >, + } + impl ::std::default::Default for SepaPaymentMethod { + fn default() -> Self { + Self { + active: Err("no value supplied for active".to_string()), + created_at: Err("no value supplied for created_at".to_string()), + payment_method_id: Err("no value supplied for payment_method_id".to_string()), + payment_rail: Err("no value supplied for payment_rail".to_string()), + sepa: Err("no value supplied for sepa".to_string()), + updated_at: Err("no value supplied for updated_at".to_string()), + } + } + } + impl SepaPaymentMethod { + pub fn active(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.active = value + .try_into() + .map_err(|e| format!("error converting supplied value for active: {}", e)); + self + } + pub fn created_at(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, + T::Error: ::std::fmt::Display, + { + self.created_at = value + .try_into() + .map_err(|e| format!("error converting supplied value for created_at: {}", e)); + self + } + pub fn payment_method_id(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.payment_method_id = value.try_into().map_err(|e| { + format!( + "error converting supplied value for payment_method_id: {}", + e + ) + }); + self + } + pub fn payment_rail(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.payment_rail = value.try_into().map_err(|e| { + format!("error converting supplied value for payment_rail: {}", e) + }); + self + } + pub fn sepa(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.sepa = value + .try_into() + .map_err(|e| format!("error converting supplied value for sepa: {}", e)); + self + } + pub fn updated_at(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, + T::Error: ::std::fmt::Display, + { + self.updated_at = value + .try_into() + .map_err(|e| format!("error converting supplied value for updated_at: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::SepaPaymentMethod { + type Error = super::error::ConversionError; + fn try_from( + value: SepaPaymentMethod, + ) -> ::std::result::Result { + Ok(Self { + active: value.active?, + created_at: value.created_at?, + payment_method_id: value.payment_method_id?, + payment_rail: value.payment_rail?, + sepa: value.sepa?, + updated_at: value.updated_at?, + }) + } + } + impl ::std::convert::From for SepaPaymentMethod { + fn from(value: super::SepaPaymentMethod) -> Self { + Self { + active: Ok(value.active), + created_at: Ok(value.created_at), + payment_method_id: Ok(value.payment_method_id), + payment_rail: Ok(value.payment_rail), + sepa: Ok(value.sepa), + updated_at: Ok(value.updated_at), + } + } + } + #[derive(Clone, Debug)] pub struct SettleX402PaymentBody { payment_payload: ::std::result::Result, @@ -77874,6 +88078,226 @@ pub mod types { } } #[derive(Clone, Debug)] + pub struct SwiftDetails { + account_last4: + ::std::result::Result, + asset: ::std::result::Result<::std::string::String, ::std::string::String>, + bank_name: ::std::result::Result<::std::string::String, ::std::string::String>, + bic: ::std::result::Result, + iban_last4: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + } + impl ::std::default::Default for SwiftDetails { + fn default() -> Self { + Self { + account_last4: Err("no value supplied for account_last4".to_string()), + asset: Err("no value supplied for asset".to_string()), + bank_name: Err("no value supplied for bank_name".to_string()), + bic: Err("no value supplied for bic".to_string()), + iban_last4: Ok(Default::default()), + } + } + } + impl SwiftDetails { + pub fn account_last4(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.account_last4 = value.try_into().map_err(|e| { + format!("error converting supplied value for account_last4: {}", e) + }); + self + } + pub fn asset(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::string::String>, + T::Error: ::std::fmt::Display, + { + self.asset = value + .try_into() + .map_err(|e| format!("error converting supplied value for asset: {}", e)); + self + } + pub fn bank_name(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::string::String>, + T::Error: ::std::fmt::Display, + { + self.bank_name = value + .try_into() + .map_err(|e| format!("error converting supplied value for bank_name: {}", e)); + self + } + pub fn bic(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.bic = value + .try_into() + .map_err(|e| format!("error converting supplied value for bic: {}", e)); + self + } + pub fn iban_last4(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.iban_last4 = value + .try_into() + .map_err(|e| format!("error converting supplied value for iban_last4: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::SwiftDetails { + type Error = super::error::ConversionError; + fn try_from( + value: SwiftDetails, + ) -> ::std::result::Result { + Ok(Self { + account_last4: value.account_last4?, + asset: value.asset?, + bank_name: value.bank_name?, + bic: value.bic?, + iban_last4: value.iban_last4?, + }) + } + } + impl ::std::convert::From for SwiftDetails { + fn from(value: super::SwiftDetails) -> Self { + Self { + account_last4: Ok(value.account_last4), + asset: Ok(value.asset), + bank_name: Ok(value.bank_name), + bic: Ok(value.bic), + iban_last4: Ok(value.iban_last4), + } + } + } + #[derive(Clone, Debug)] + pub struct SwiftPaymentMethod { + active: ::std::result::Result, + created_at: ::std::result::Result< + ::chrono::DateTime<::chrono::offset::Utc>, + ::std::string::String, + >, + payment_method_id: ::std::result::Result, + payment_rail: + ::std::result::Result, + swift: ::std::result::Result, + updated_at: ::std::result::Result< + ::chrono::DateTime<::chrono::offset::Utc>, + ::std::string::String, + >, + } + impl ::std::default::Default for SwiftPaymentMethod { + fn default() -> Self { + Self { + active: Err("no value supplied for active".to_string()), + created_at: Err("no value supplied for created_at".to_string()), + payment_method_id: Err("no value supplied for payment_method_id".to_string()), + payment_rail: Err("no value supplied for payment_rail".to_string()), + swift: Err("no value supplied for swift".to_string()), + updated_at: Err("no value supplied for updated_at".to_string()), + } + } + } + impl SwiftPaymentMethod { + pub fn active(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.active = value + .try_into() + .map_err(|e| format!("error converting supplied value for active: {}", e)); + self + } + pub fn created_at(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, + T::Error: ::std::fmt::Display, + { + self.created_at = value + .try_into() + .map_err(|e| format!("error converting supplied value for created_at: {}", e)); + self + } + pub fn payment_method_id(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.payment_method_id = value.try_into().map_err(|e| { + format!( + "error converting supplied value for payment_method_id: {}", + e + ) + }); + self + } + pub fn payment_rail(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.payment_rail = value.try_into().map_err(|e| { + format!("error converting supplied value for payment_rail: {}", e) + }); + self + } + pub fn swift(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.swift = value + .try_into() + .map_err(|e| format!("error converting supplied value for swift: {}", e)); + self + } + pub fn updated_at(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, + T::Error: ::std::fmt::Display, + { + self.updated_at = value + .try_into() + .map_err(|e| format!("error converting supplied value for updated_at: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::SwiftPaymentMethod { + type Error = super::error::ConversionError; + fn try_from( + value: SwiftPaymentMethod, + ) -> ::std::result::Result { + Ok(Self { + active: value.active?, + created_at: value.created_at?, + payment_method_id: value.payment_method_id?, + payment_rail: value.payment_rail?, + swift: value.swift?, + updated_at: value.updated_at?, + }) + } + } + impl ::std::convert::From for SwiftPaymentMethod { + fn from(value: super::SwiftPaymentMethod) -> Self { + Self { + active: Ok(value.active), + created_at: Ok(value.created_at), + payment_method_id: Ok(value.payment_method_id), + payment_rail: Ok(value.payment_rail), + swift: Ok(value.swift), + updated_at: Ok(value.updated_at), + } + } + } + #[derive(Clone, Debug)] pub struct TelegramAuthentication { auth_date: ::std::result::Result, first_name: ::std::result::Result< @@ -78265,1569 +88689,1956 @@ pub mod types { } } #[derive(Clone, Debug)] - pub struct UpdateEvmAccountBody { - account_policy: ::std::result::Result< - ::std::option::Option, + pub struct Transfer { + completed_at: ::std::result::Result< + ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, ::std::string::String, >, - name: ::std::result::Result< - ::std::option::Option, + created_at: ::std::result::Result< + ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + ::std::string::String, + >, + details: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + estimate: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + exchange_rate: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + executed_at: ::std::result::Result< + ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + ::std::string::String, + >, + expires_at: ::std::result::Result< + ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + ::std::string::String, + >, + failure_reason: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + fees: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + metadata: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + source: ::std::result::Result, + source_amount: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + source_asset: + ::std::result::Result<::std::option::Option, ::std::string::String>, + status: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + target: ::std::result::Result, + target_amount: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + target_asset: + ::std::result::Result<::std::option::Option, ::std::string::String>, + transfer_id: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + updated_at: ::std::result::Result< + ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, ::std::string::String, >, } - impl ::std::default::Default for UpdateEvmAccountBody { + impl ::std::default::Default for Transfer { fn default() -> Self { Self { - account_policy: Ok(Default::default()), - name: Ok(Default::default()), + completed_at: Ok(Default::default()), + created_at: Ok(Default::default()), + details: Ok(Default::default()), + estimate: Ok(Default::default()), + exchange_rate: Ok(Default::default()), + executed_at: Ok(Default::default()), + expires_at: Ok(Default::default()), + failure_reason: Ok(Default::default()), + fees: Ok(Default::default()), + metadata: Ok(Default::default()), + source: Err("no value supplied for source".to_string()), + source_amount: Ok(Default::default()), + source_asset: Ok(Default::default()), + status: Ok(Default::default()), + target: Err("no value supplied for target".to_string()), + target_amount: Ok(Default::default()), + target_asset: Ok(Default::default()), + transfer_id: Ok(Default::default()), + updated_at: Ok(Default::default()), } } } - impl UpdateEvmAccountBody { - pub fn account_policy(mut self, value: T) -> Self + impl Transfer { + pub fn completed_at(mut self, value: T) -> Self where T: ::std::convert::TryInto< - ::std::option::Option, + ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, >, T::Error: ::std::fmt::Display, { - self.account_policy = value.try_into().map_err(|e| { - format!("error converting supplied value for account_policy: {}", e) + self.completed_at = value.try_into().map_err(|e| { + format!("error converting supplied value for completed_at: {}", e) }); self } - pub fn name(mut self, value: T) -> Self + pub fn created_at(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option>, + T: ::std::convert::TryInto< + ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + >, T::Error: ::std::fmt::Display, { - self.name = value + self.created_at = value .try_into() - .map_err(|e| format!("error converting supplied value for name: {}", e)); + .map_err(|e| format!("error converting supplied value for created_at: {}", e)); + self + } + pub fn details(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.details = value + .try_into() + .map_err(|e| format!("error converting supplied value for details: {}", e)); + self + } + pub fn estimate(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.estimate = value + .try_into() + .map_err(|e| format!("error converting supplied value for estimate: {}", e)); + self + } + pub fn exchange_rate(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.exchange_rate = value.try_into().map_err(|e| { + format!("error converting supplied value for exchange_rate: {}", e) + }); + self + } + pub fn executed_at(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + >, + T::Error: ::std::fmt::Display, + { + self.executed_at = value + .try_into() + .map_err(|e| format!("error converting supplied value for executed_at: {}", e)); + self + } + pub fn expires_at(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + >, + T::Error: ::std::fmt::Display, + { + self.expires_at = value + .try_into() + .map_err(|e| format!("error converting supplied value for expires_at: {}", e)); + self + } + pub fn failure_reason(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.failure_reason = value.try_into().map_err(|e| { + format!("error converting supplied value for failure_reason: {}", e) + }); + self + } + pub fn fees(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.fees = value + .try_into() + .map_err(|e| format!("error converting supplied value for fees: {}", e)); + self + } + pub fn metadata(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.metadata = value + .try_into() + .map_err(|e| format!("error converting supplied value for metadata: {}", e)); + self + } + pub fn source(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.source = value + .try_into() + .map_err(|e| format!("error converting supplied value for source: {}", e)); + self + } + pub fn source_amount(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.source_amount = value.try_into().map_err(|e| { + format!("error converting supplied value for source_amount: {}", e) + }); + self + } + pub fn source_asset(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.source_asset = value.try_into().map_err(|e| { + format!("error converting supplied value for source_asset: {}", e) + }); + self + } + pub fn status(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.status = value + .try_into() + .map_err(|e| format!("error converting supplied value for status: {}", e)); + self + } + pub fn target(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.target = value + .try_into() + .map_err(|e| format!("error converting supplied value for target: {}", e)); + self + } + pub fn target_amount(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.target_amount = value.try_into().map_err(|e| { + format!("error converting supplied value for target_amount: {}", e) + }); + self + } + pub fn target_asset(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.target_asset = value.try_into().map_err(|e| { + format!("error converting supplied value for target_asset: {}", e) + }); + self + } + pub fn transfer_id(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.transfer_id = value + .try_into() + .map_err(|e| format!("error converting supplied value for transfer_id: {}", e)); + self + } + pub fn updated_at(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + >, + T::Error: ::std::fmt::Display, + { + self.updated_at = value + .try_into() + .map_err(|e| format!("error converting supplied value for updated_at: {}", e)); self } } - impl ::std::convert::TryFrom for super::UpdateEvmAccountBody { + impl ::std::convert::TryFrom for super::Transfer { type Error = super::error::ConversionError; fn try_from( - value: UpdateEvmAccountBody, + value: Transfer, ) -> ::std::result::Result { Ok(Self { - account_policy: value.account_policy?, - name: value.name?, + completed_at: value.completed_at?, + created_at: value.created_at?, + details: value.details?, + estimate: value.estimate?, + exchange_rate: value.exchange_rate?, + executed_at: value.executed_at?, + expires_at: value.expires_at?, + failure_reason: value.failure_reason?, + fees: value.fees?, + metadata: value.metadata?, + source: value.source?, + source_amount: value.source_amount?, + source_asset: value.source_asset?, + status: value.status?, + target: value.target?, + target_amount: value.target_amount?, + target_asset: value.target_asset?, + transfer_id: value.transfer_id?, + updated_at: value.updated_at?, }) } } - impl ::std::convert::From for UpdateEvmAccountBody { - fn from(value: super::UpdateEvmAccountBody) -> Self { + impl ::std::convert::From for Transfer { + fn from(value: super::Transfer) -> Self { Self { - account_policy: Ok(value.account_policy), - name: Ok(value.name), + completed_at: Ok(value.completed_at), + created_at: Ok(value.created_at), + details: Ok(value.details), + estimate: Ok(value.estimate), + exchange_rate: Ok(value.exchange_rate), + executed_at: Ok(value.executed_at), + expires_at: Ok(value.expires_at), + failure_reason: Ok(value.failure_reason), + fees: Ok(value.fees), + metadata: Ok(value.metadata), + source: Ok(value.source), + source_amount: Ok(value.source_amount), + source_asset: Ok(value.source_asset), + status: Ok(value.status), + target: Ok(value.target), + target_amount: Ok(value.target_amount), + target_asset: Ok(value.target_asset), + transfer_id: Ok(value.transfer_id), + updated_at: Ok(value.updated_at), } } } #[derive(Clone, Debug)] - pub struct UpdateEvmSmartAccountBody { - name: ::std::result::Result< - ::std::option::Option, + pub struct TransferDetails { + deposit_destination: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + onchain_transactions: ::std::result::Result< + ::std::vec::Vec, + ::std::string::String, + >, + travel_rule: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, } - impl ::std::default::Default for UpdateEvmSmartAccountBody { + impl ::std::default::Default for TransferDetails { fn default() -> Self { Self { - name: Ok(Default::default()), + deposit_destination: Ok(Default::default()), + onchain_transactions: Ok(Default::default()), + travel_rule: Ok(Default::default()), } } } - impl UpdateEvmSmartAccountBody { - pub fn name(mut self, value: T) -> Self + impl TransferDetails { + pub fn deposit_destination(mut self, value: T) -> Self where T: ::std::convert::TryInto< - ::std::option::Option, + ::std::option::Option, >, T::Error: ::std::fmt::Display, { - self.name = value + self.deposit_destination = value.try_into().map_err(|e| { + format!( + "error converting supplied value for deposit_destination: {}", + e + ) + }); + self + } + pub fn onchain_transactions(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + ::std::vec::Vec, + >, + T::Error: ::std::fmt::Display, + { + self.onchain_transactions = value.try_into().map_err(|e| { + format!( + "error converting supplied value for onchain_transactions: {}", + e + ) + }); + self + } + pub fn travel_rule(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.travel_rule = value .try_into() - .map_err(|e| format!("error converting supplied value for name: {}", e)); + .map_err(|e| format!("error converting supplied value for travel_rule: {}", e)); self } } - impl ::std::convert::TryFrom for super::UpdateEvmSmartAccountBody { + impl ::std::convert::TryFrom for super::TransferDetails { type Error = super::error::ConversionError; fn try_from( - value: UpdateEvmSmartAccountBody, + value: TransferDetails, ) -> ::std::result::Result { - Ok(Self { name: value.name? }) + Ok(Self { + deposit_destination: value.deposit_destination?, + onchain_transactions: value.onchain_transactions?, + travel_rule: value.travel_rule?, + }) } } - impl ::std::convert::From for UpdateEvmSmartAccountBody { - fn from(value: super::UpdateEvmSmartAccountBody) -> Self { + impl ::std::convert::From for TransferDetails { + fn from(value: super::TransferDetails) -> Self { Self { - name: Ok(value.name), + deposit_destination: Ok(value.deposit_destination), + onchain_transactions: Ok(value.onchain_transactions), + travel_rule: Ok(value.travel_rule), } } } #[derive(Clone, Debug)] - pub struct UpdatePolicyBody { - description: ::std::result::Result< - ::std::option::Option, - ::std::string::String, - >, - rules: ::std::result::Result<::std::vec::Vec, ::std::string::String>, + pub struct TransferDetailsOnchainTransactionsItem { + network: ::std::result::Result, + transaction_hash: ::std::result::Result<::std::string::String, ::std::string::String>, } - impl ::std::default::Default for UpdatePolicyBody { + impl ::std::default::Default for TransferDetailsOnchainTransactionsItem { fn default() -> Self { Self { - description: Ok(Default::default()), - rules: Err("no value supplied for rules".to_string()), + network: Err("no value supplied for network".to_string()), + transaction_hash: Err("no value supplied for transaction_hash".to_string()), } } } - impl UpdatePolicyBody { - pub fn description(mut self, value: T) -> Self + impl TransferDetailsOnchainTransactionsItem { + pub fn network(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - ::std::option::Option, - >, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.description = value + self.network = value .try_into() - .map_err(|e| format!("error converting supplied value for description: {}", e)); + .map_err(|e| format!("error converting supplied value for network: {}", e)); self } - pub fn rules(mut self, value: T) -> Self + pub fn transaction_hash(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::vec::Vec>, + T: ::std::convert::TryInto<::std::string::String>, T::Error: ::std::fmt::Display, { - self.rules = value - .try_into() - .map_err(|e| format!("error converting supplied value for rules: {}", e)); + self.transaction_hash = value.try_into().map_err(|e| { + format!( + "error converting supplied value for transaction_hash: {}", + e + ) + }); self } } - impl ::std::convert::TryFrom for super::UpdatePolicyBody { + impl ::std::convert::TryFrom + for super::TransferDetailsOnchainTransactionsItem + { type Error = super::error::ConversionError; fn try_from( - value: UpdatePolicyBody, + value: TransferDetailsOnchainTransactionsItem, ) -> ::std::result::Result { Ok(Self { - description: value.description?, - rules: value.rules?, + network: value.network?, + transaction_hash: value.transaction_hash?, }) } } - impl ::std::convert::From for UpdatePolicyBody { - fn from(value: super::UpdatePolicyBody) -> Self { + impl ::std::convert::From + for TransferDetailsOnchainTransactionsItem + { + fn from(value: super::TransferDetailsOnchainTransactionsItem) -> Self { Self { - description: Ok(value.description), - rules: Ok(value.rules), + network: Ok(value.network), + transaction_hash: Ok(value.transaction_hash), } } } #[derive(Clone, Debug)] - pub struct UpdateSolanaAccountBody { - account_policy: ::std::result::Result< - ::std::option::Option, + pub struct TransferDetailsTravelRule { + status: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, - name: ::std::result::Result< - ::std::option::Option, + status_message: ::std::result::Result< + ::std::option::Option<::std::string::String>, ::std::string::String, >, } - impl ::std::default::Default for UpdateSolanaAccountBody { + impl ::std::default::Default for TransferDetailsTravelRule { fn default() -> Self { Self { - account_policy: Ok(Default::default()), - name: Ok(Default::default()), + status: Ok(Default::default()), + status_message: Ok(Default::default()), } } } - impl UpdateSolanaAccountBody { - pub fn account_policy(mut self, value: T) -> Self + impl TransferDetailsTravelRule { + pub fn status(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - ::std::option::Option, - >, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.account_policy = value.try_into().map_err(|e| { - format!("error converting supplied value for account_policy: {}", e) - }); + self.status = value + .try_into() + .map_err(|e| format!("error converting supplied value for status: {}", e)); self } - pub fn name(mut self, value: T) -> Self + pub fn status_message(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - ::std::option::Option, - >, + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, T::Error: ::std::fmt::Display, { - self.name = value - .try_into() - .map_err(|e| format!("error converting supplied value for name: {}", e)); + self.status_message = value.try_into().map_err(|e| { + format!("error converting supplied value for status_message: {}", e) + }); self } } - impl ::std::convert::TryFrom for super::UpdateSolanaAccountBody { + impl ::std::convert::TryFrom for super::TransferDetailsTravelRule { type Error = super::error::ConversionError; fn try_from( - value: UpdateSolanaAccountBody, + value: TransferDetailsTravelRule, ) -> ::std::result::Result { Ok(Self { - account_policy: value.account_policy?, - name: value.name?, + status: value.status?, + status_message: value.status_message?, }) } } - impl ::std::convert::From for UpdateSolanaAccountBody { - fn from(value: super::UpdateSolanaAccountBody) -> Self { + impl ::std::convert::From for TransferDetailsTravelRule { + fn from(value: super::TransferDetailsTravelRule) -> Self { Self { - account_policy: Ok(value.account_policy), - name: Ok(value.name), + status: Ok(value.status), + status_message: Ok(value.status_message), } } } #[derive(Clone, Debug)] - pub struct UserOperationReceipt { - block_hash: ::std::result::Result< - ::std::option::Option, + pub struct TransferEstimate { + estimated_at: ::std::result::Result< + ::chrono::DateTime<::chrono::offset::Utc>, ::std::string::String, >, - block_number: ::std::result::Result<::std::option::Option, ::std::string::String>, - gas_used: ::std::result::Result< - ::std::option::Option<::std::string::String>, + exchange_rate: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, - revert: ::std::result::Result< - ::std::option::Option, + fees: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, - transaction_hash: ::std::result::Result< - ::std::option::Option, + target_amount: ::std::result::Result< + ::std::option::Option<::std::string::String>, ::std::string::String, >, + target_asset: + ::std::result::Result<::std::option::Option, ::std::string::String>, } - impl ::std::default::Default for UserOperationReceipt { + impl ::std::default::Default for TransferEstimate { fn default() -> Self { Self { - block_hash: Ok(Default::default()), - block_number: Ok(Default::default()), - gas_used: Ok(Default::default()), - revert: Ok(Default::default()), - transaction_hash: Ok(Default::default()), + estimated_at: Err("no value supplied for estimated_at".to_string()), + exchange_rate: Ok(Default::default()), + fees: Ok(Default::default()), + target_amount: Ok(Default::default()), + target_asset: Ok(Default::default()), } } } - impl UserOperationReceipt { - pub fn block_hash(mut self, value: T) -> Self + impl TransferEstimate { + pub fn estimated_at(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - ::std::option::Option, - >, + T: ::std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, T::Error: ::std::fmt::Display, { - self.block_hash = value - .try_into() - .map_err(|e| format!("error converting supplied value for block_hash: {}", e)); + self.estimated_at = value.try_into().map_err(|e| { + format!("error converting supplied value for estimated_at: {}", e) + }); self } - pub fn block_number(mut self, value: T) -> Self + pub fn exchange_rate(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option>, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.block_number = value.try_into().map_err(|e| { - format!("error converting supplied value for block_number: {}", e) + self.exchange_rate = value.try_into().map_err(|e| { + format!("error converting supplied value for exchange_rate: {}", e) }); self } - pub fn gas_used(mut self, value: T) -> Self + pub fn fees(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.gas_used = value + self.fees = value .try_into() - .map_err(|e| format!("error converting supplied value for gas_used: {}", e)); + .map_err(|e| format!("error converting supplied value for fees: {}", e)); self } - pub fn revert(mut self, value: T) -> Self + pub fn target_amount(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - ::std::option::Option, - >, + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, T::Error: ::std::fmt::Display, { - self.revert = value - .try_into() - .map_err(|e| format!("error converting supplied value for revert: {}", e)); + self.target_amount = value.try_into().map_err(|e| { + format!("error converting supplied value for target_amount: {}", e) + }); self } - pub fn transaction_hash(mut self, value: T) -> Self + pub fn target_asset(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - ::std::option::Option, - >, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.transaction_hash = value.try_into().map_err(|e| { - format!( - "error converting supplied value for transaction_hash: {}", - e - ) + self.target_asset = value.try_into().map_err(|e| { + format!("error converting supplied value for target_asset: {}", e) }); self } } - impl ::std::convert::TryFrom for super::UserOperationReceipt { + impl ::std::convert::TryFrom for super::TransferEstimate { type Error = super::error::ConversionError; fn try_from( - value: UserOperationReceipt, + value: TransferEstimate, ) -> ::std::result::Result { Ok(Self { - block_hash: value.block_hash?, - block_number: value.block_number?, - gas_used: value.gas_used?, - revert: value.revert?, - transaction_hash: value.transaction_hash?, + estimated_at: value.estimated_at?, + exchange_rate: value.exchange_rate?, + fees: value.fees?, + target_amount: value.target_amount?, + target_asset: value.target_asset?, }) } } - impl ::std::convert::From for UserOperationReceipt { - fn from(value: super::UserOperationReceipt) -> Self { + impl ::std::convert::From for TransferEstimate { + fn from(value: super::TransferEstimate) -> Self { Self { - block_hash: Ok(value.block_hash), - block_number: Ok(value.block_number), - gas_used: Ok(value.gas_used), - revert: Ok(value.revert), - transaction_hash: Ok(value.transaction_hash), + estimated_at: Ok(value.estimated_at), + exchange_rate: Ok(value.exchange_rate), + fees: Ok(value.fees), + target_amount: Ok(value.target_amount), + target_asset: Ok(value.target_asset), } } } #[derive(Clone, Debug)] - pub struct UserOperationReceiptRevert { - data: - ::std::result::Result, - message: ::std::result::Result<::std::string::String, ::std::string::String>, + pub struct TransferExchangeRate { + rate: ::std::result::Result<::std::string::String, ::std::string::String>, + source_asset: ::std::result::Result, + target_asset: ::std::result::Result, } - impl ::std::default::Default for UserOperationReceiptRevert { + impl ::std::default::Default for TransferExchangeRate { fn default() -> Self { Self { - data: Err("no value supplied for data".to_string()), - message: Err("no value supplied for message".to_string()), + rate: Err("no value supplied for rate".to_string()), + source_asset: Err("no value supplied for source_asset".to_string()), + target_asset: Err("no value supplied for target_asset".to_string()), } } } - impl UserOperationReceiptRevert { - pub fn data(mut self, value: T) -> Self + impl TransferExchangeRate { + pub fn rate(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::string::String>, T::Error: ::std::fmt::Display, { - self.data = value + self.rate = value .try_into() - .map_err(|e| format!("error converting supplied value for data: {}", e)); + .map_err(|e| format!("error converting supplied value for rate: {}", e)); self } - pub fn message(mut self, value: T) -> Self + pub fn source_asset(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::string::String>, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.message = value - .try_into() - .map_err(|e| format!("error converting supplied value for message: {}", e)); + self.source_asset = value.try_into().map_err(|e| { + format!("error converting supplied value for source_asset: {}", e) + }); + self + } + pub fn target_asset(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.target_asset = value.try_into().map_err(|e| { + format!("error converting supplied value for target_asset: {}", e) + }); self } } - impl ::std::convert::TryFrom for super::UserOperationReceiptRevert { + impl ::std::convert::TryFrom for super::TransferExchangeRate { type Error = super::error::ConversionError; fn try_from( - value: UserOperationReceiptRevert, + value: TransferExchangeRate, ) -> ::std::result::Result { Ok(Self { - data: value.data?, - message: value.message?, + rate: value.rate?, + source_asset: value.source_asset?, + target_asset: value.target_asset?, }) } } - impl ::std::convert::From for UserOperationReceiptRevert { - fn from(value: super::UserOperationReceiptRevert) -> Self { + impl ::std::convert::From for TransferExchangeRate { + fn from(value: super::TransferExchangeRate) -> Self { Self { - data: Ok(value.data), - message: Ok(value.message), + rate: Ok(value.rate), + source_asset: Ok(value.source_asset), + target_asset: Ok(value.target_asset), } } } #[derive(Clone, Debug)] - pub struct ValidateEndUserAccessTokenBody { - access_token: ::std::result::Result<::std::string::String, ::std::string::String>, + pub struct TransferFee { + amount: ::std::result::Result<::std::string::String, ::std::string::String>, + asset: ::std::result::Result, + type_: ::std::result::Result, } - impl ::std::default::Default for ValidateEndUserAccessTokenBody { + impl ::std::default::Default for TransferFee { fn default() -> Self { Self { - access_token: Err("no value supplied for access_token".to_string()), + amount: Err("no value supplied for amount".to_string()), + asset: Err("no value supplied for asset".to_string()), + type_: Err("no value supplied for type_".to_string()), } } } - impl ValidateEndUserAccessTokenBody { - pub fn access_token(mut self, value: T) -> Self + impl TransferFee { + pub fn amount(mut self, value: T) -> Self where T: ::std::convert::TryInto<::std::string::String>, T::Error: ::std::fmt::Display, { - self.access_token = value.try_into().map_err(|e| { - format!("error converting supplied value for access_token: {}", e) - }); + self.amount = value + .try_into() + .map_err(|e| format!("error converting supplied value for amount: {}", e)); self } - } - impl ::std::convert::TryFrom - for super::ValidateEndUserAccessTokenBody - { - type Error = super::error::ConversionError; - fn try_from( - value: ValidateEndUserAccessTokenBody, - ) -> ::std::result::Result { - Ok(Self { - access_token: value.access_token?, - }) + pub fn asset(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.asset = value + .try_into() + .map_err(|e| format!("error converting supplied value for asset: {}", e)); + self } - } - impl ::std::convert::From - for ValidateEndUserAccessTokenBody - { - fn from(value: super::ValidateEndUserAccessTokenBody) -> Self { - Self { - access_token: Ok(value.access_token), - } - } - } - #[derive(Clone, Debug)] - pub struct VerifyX402PaymentBody { - payment_payload: - ::std::result::Result, - payment_requirements: - ::std::result::Result, - x402_version: ::std::result::Result, - } - impl ::std::default::Default for VerifyX402PaymentBody { - fn default() -> Self { - Self { - payment_payload: Err("no value supplied for payment_payload".to_string()), - payment_requirements: Err( - "no value supplied for payment_requirements".to_string() - ), - x402_version: Err("no value supplied for x402_version".to_string()), - } - } - } - impl VerifyX402PaymentBody { - pub fn payment_payload(mut self, value: T) -> Self - where - T: ::std::convert::TryInto, - T::Error: ::std::fmt::Display, - { - self.payment_payload = value.try_into().map_err(|e| { - format!("error converting supplied value for payment_payload: {}", e) - }); - self - } - pub fn payment_requirements(mut self, value: T) -> Self - where - T: ::std::convert::TryInto, - T::Error: ::std::fmt::Display, - { - self.payment_requirements = value.try_into().map_err(|e| { - format!( - "error converting supplied value for payment_requirements: {}", - e - ) - }); - self - } - pub fn x402_version(mut self, value: T) -> Self + pub fn type_(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.x402_version = value.try_into().map_err(|e| { - format!("error converting supplied value for x402_version: {}", e) - }); + self.type_ = value + .try_into() + .map_err(|e| format!("error converting supplied value for type_: {}", e)); self } } - impl ::std::convert::TryFrom for super::VerifyX402PaymentBody { + impl ::std::convert::TryFrom for super::TransferFee { type Error = super::error::ConversionError; fn try_from( - value: VerifyX402PaymentBody, + value: TransferFee, ) -> ::std::result::Result { Ok(Self { - payment_payload: value.payment_payload?, - payment_requirements: value.payment_requirements?, - x402_version: value.x402_version?, + amount: value.amount?, + asset: value.asset?, + type_: value.type_?, }) } } - impl ::std::convert::From for VerifyX402PaymentBody { - fn from(value: super::VerifyX402PaymentBody) -> Self { + impl ::std::convert::From for TransferFee { + fn from(value: super::TransferFee) -> Self { Self { - payment_payload: Ok(value.payment_payload), - payment_requirements: Ok(value.payment_requirements), - x402_version: Ok(value.x402_version), + amount: Ok(value.amount), + asset: Ok(value.asset), + type_: Ok(value.type_), } } } #[derive(Clone, Debug)] - pub struct VerifyX402PaymentResponse { - invalid_message: ::std::result::Result< - ::std::option::Option<::std::string::String>, + pub struct TransferRequest { + amount: ::std::result::Result<::std::string::String, ::std::string::String>, + amount_type: + ::std::result::Result, + asset: ::std::result::Result, + execute: ::std::result::Result, + metadata: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, - invalid_reason: ::std::result::Result< - ::std::option::Option, + source: ::std::result::Result, + target: ::std::result::Result, + travel_rule: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, - is_valid: ::std::result::Result, - payer: - ::std::result::Result, + validate_only: ::std::result::Result, } - impl ::std::default::Default for VerifyX402PaymentResponse { + impl ::std::default::Default for TransferRequest { fn default() -> Self { Self { - invalid_message: Ok(Default::default()), - invalid_reason: Ok(Default::default()), - is_valid: Err("no value supplied for is_valid".to_string()), - payer: Err("no value supplied for payer".to_string()), + amount: Err("no value supplied for amount".to_string()), + amount_type: Ok(super::defaults::transfer_request_amount_type()), + asset: Err("no value supplied for asset".to_string()), + execute: Err("no value supplied for execute".to_string()), + metadata: Ok(Default::default()), + source: Err("no value supplied for source".to_string()), + target: Err("no value supplied for target".to_string()), + travel_rule: Ok(Default::default()), + validate_only: Ok(Default::default()), } } } - impl VerifyX402PaymentResponse { - pub fn invalid_message(mut self, value: T) -> Self + impl TransferRequest { + pub fn amount(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T: ::std::convert::TryInto<::std::string::String>, T::Error: ::std::fmt::Display, { - self.invalid_message = value.try_into().map_err(|e| { - format!("error converting supplied value for invalid_message: {}", e) - }); + self.amount = value + .try_into() + .map_err(|e| format!("error converting supplied value for amount: {}", e)); self } - pub fn invalid_reason(mut self, value: T) -> Self + pub fn amount_type(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option>, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.invalid_reason = value.try_into().map_err(|e| { - format!("error converting supplied value for invalid_reason: {}", e) - }); + self.amount_type = value + .try_into() + .map_err(|e| format!("error converting supplied value for amount_type: {}", e)); self } - pub fn is_valid(mut self, value: T) -> Self + pub fn asset(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.asset = value + .try_into() + .map_err(|e| format!("error converting supplied value for asset: {}", e)); + self + } + pub fn execute(mut self, value: T) -> Self where T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.is_valid = value + self.execute = value .try_into() - .map_err(|e| format!("error converting supplied value for is_valid: {}", e)); + .map_err(|e| format!("error converting supplied value for execute: {}", e)); self } - pub fn payer(mut self, value: T) -> Self + pub fn metadata(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.payer = value + self.metadata = value .try_into() - .map_err(|e| format!("error converting supplied value for payer: {}", e)); + .map_err(|e| format!("error converting supplied value for metadata: {}", e)); + self + } + pub fn source(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.source = value + .try_into() + .map_err(|e| format!("error converting supplied value for source: {}", e)); + self + } + pub fn target(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.target = value + .try_into() + .map_err(|e| format!("error converting supplied value for target: {}", e)); + self + } + pub fn travel_rule(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.travel_rule = value + .try_into() + .map_err(|e| format!("error converting supplied value for travel_rule: {}", e)); + self + } + pub fn validate_only(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.validate_only = value.try_into().map_err(|e| { + format!("error converting supplied value for validate_only: {}", e) + }); self } } - impl ::std::convert::TryFrom for super::VerifyX402PaymentResponse { + impl ::std::convert::TryFrom for super::TransferRequest { type Error = super::error::ConversionError; fn try_from( - value: VerifyX402PaymentResponse, + value: TransferRequest, ) -> ::std::result::Result { Ok(Self { - invalid_message: value.invalid_message?, - invalid_reason: value.invalid_reason?, - is_valid: value.is_valid?, - payer: value.payer?, + amount: value.amount?, + amount_type: value.amount_type?, + asset: value.asset?, + execute: value.execute?, + metadata: value.metadata?, + source: value.source?, + target: value.target?, + travel_rule: value.travel_rule?, + validate_only: value.validate_only?, }) } } - impl ::std::convert::From for VerifyX402PaymentResponse { - fn from(value: super::VerifyX402PaymentResponse) -> Self { + impl ::std::convert::From for TransferRequest { + fn from(value: super::TransferRequest) -> Self { Self { - invalid_message: Ok(value.invalid_message), - invalid_reason: Ok(value.invalid_reason), - is_valid: Ok(value.is_valid), - payer: Ok(value.payer), + amount: Ok(value.amount), + amount_type: Ok(value.amount_type), + asset: Ok(value.asset), + execute: Ok(value.execute), + metadata: Ok(value.metadata), + source: Ok(value.source), + target: Ok(value.target), + travel_rule: Ok(value.travel_rule), + validate_only: Ok(value.validate_only), } } } #[derive(Clone, Debug)] - pub struct WebhookEventListResponse { - events: ::std::result::Result< - ::std::vec::Vec, - ::std::string::String, - >, + pub struct TransfersAccount { + account_id: ::std::result::Result<::std::string::String, ::std::string::String>, + asset: ::std::result::Result, } - impl ::std::default::Default for WebhookEventListResponse { + impl ::std::default::Default for TransfersAccount { fn default() -> Self { Self { - events: Err("no value supplied for events".to_string()), + account_id: Err("no value supplied for account_id".to_string()), + asset: Err("no value supplied for asset".to_string()), } } } - impl WebhookEventListResponse { - pub fn events(mut self, value: T) -> Self + impl TransfersAccount { + pub fn account_id(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::vec::Vec>, + T: ::std::convert::TryInto<::std::string::String>, T::Error: ::std::fmt::Display, { - self.events = value + self.account_id = value .try_into() - .map_err(|e| format!("error converting supplied value for events: {}", e)); + .map_err(|e| format!("error converting supplied value for account_id: {}", e)); + self + } + pub fn asset(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.asset = value + .try_into() + .map_err(|e| format!("error converting supplied value for asset: {}", e)); self } } - impl ::std::convert::TryFrom for super::WebhookEventListResponse { + impl ::std::convert::TryFrom for super::TransfersAccount { type Error = super::error::ConversionError; fn try_from( - value: WebhookEventListResponse, + value: TransfersAccount, ) -> ::std::result::Result { Ok(Self { - events: value.events?, + account_id: value.account_id?, + asset: value.asset?, }) } } - impl ::std::convert::From for WebhookEventListResponse { - fn from(value: super::WebhookEventListResponse) -> Self { + impl ::std::convert::From for TransfersAccount { + fn from(value: super::TransfersAccount) -> Self { Self { - events: Ok(value.events), + account_id: Ok(value.account_id), + asset: Ok(value.asset), } } } #[derive(Clone, Debug)] - pub struct WebhookEventResponse { - created_at: ::std::result::Result< - ::chrono::DateTime<::chrono::offset::Utc>, + pub struct TravelRule { + beneficiary: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, - event_id: ::std::result::Result<::std::string::String, ::std::string::String>, - event_type_name: ::std::result::Result<::std::string::String, ::std::string::String>, - response: ::std::result::Result< - ::std::option::Option, - ::std::string::String, - >, - retry_count: ::std::result::Result, - status: ::std::result::Result, - succeeded_at: ::std::result::Result< - ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + is_intermediary: + ::std::result::Result<::std::option::Option, ::std::string::String>, + is_self: ::std::result::Result<::std::option::Option, ::std::string::String>, + originator: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, } - impl ::std::default::Default for WebhookEventResponse { + impl ::std::default::Default for TravelRule { fn default() -> Self { Self { - created_at: Err("no value supplied for created_at".to_string()), - event_id: Err("no value supplied for event_id".to_string()), - event_type_name: Err("no value supplied for event_type_name".to_string()), - response: Ok(Default::default()), - retry_count: Err("no value supplied for retry_count".to_string()), - status: Err("no value supplied for status".to_string()), - succeeded_at: Ok(Default::default()), + beneficiary: Ok(Default::default()), + is_intermediary: Ok(Default::default()), + is_self: Ok(Default::default()), + originator: Ok(Default::default()), } } } - impl WebhookEventResponse { - pub fn created_at(mut self, value: T) -> Self + impl TravelRule { + pub fn beneficiary(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.created_at = value + self.beneficiary = value .try_into() - .map_err(|e| format!("error converting supplied value for created_at: {}", e)); + .map_err(|e| format!("error converting supplied value for beneficiary: {}", e)); self } - pub fn event_id(mut self, value: T) -> Self + pub fn is_intermediary(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::string::String>, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.event_id = value - .try_into() - .map_err(|e| format!("error converting supplied value for event_id: {}", e)); + self.is_intermediary = value.try_into().map_err(|e| { + format!("error converting supplied value for is_intermediary: {}", e) + }); self } - pub fn event_type_name(mut self, value: T) -> Self + pub fn is_self(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::string::String>, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.event_type_name = value.try_into().map_err(|e| { - format!("error converting supplied value for event_type_name: {}", e) - }); + self.is_self = value + .try_into() + .map_err(|e| format!("error converting supplied value for is_self: {}", e)); self } - pub fn response(mut self, value: T) -> Self + pub fn originator(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - ::std::option::Option, - >, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.response = value + self.originator = value .try_into() - .map_err(|e| format!("error converting supplied value for response: {}", e)); + .map_err(|e| format!("error converting supplied value for originator: {}", e)); self } - pub fn retry_count(mut self, value: T) -> Self + } + impl ::std::convert::TryFrom for super::TravelRule { + type Error = super::error::ConversionError; + fn try_from( + value: TravelRule, + ) -> ::std::result::Result { + Ok(Self { + beneficiary: value.beneficiary?, + is_intermediary: value.is_intermediary?, + is_self: value.is_self?, + originator: value.originator?, + }) + } + } + impl ::std::convert::From for TravelRule { + fn from(value: super::TravelRule) -> Self { + Self { + beneficiary: Ok(value.beneficiary), + is_intermediary: Ok(value.is_intermediary), + is_self: Ok(value.is_self), + originator: Ok(value.originator), + } + } + } + #[derive(Clone, Debug)] + pub struct TravelRuleBeneficiary { + address: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + financial_institution: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + name: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + wallet_type: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + } + impl ::std::default::Default for TravelRuleBeneficiary { + fn default() -> Self { + Self { + address: Ok(Default::default()), + financial_institution: Ok(Default::default()), + name: Ok(Default::default()), + wallet_type: Ok(Default::default()), + } + } + } + impl TravelRuleBeneficiary { + pub fn address(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.retry_count = value + self.address = value .try_into() - .map_err(|e| format!("error converting supplied value for retry_count: {}", e)); + .map_err(|e| format!("error converting supplied value for address: {}", e)); self } - pub fn status(mut self, value: T) -> Self + pub fn financial_institution(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, T::Error: ::std::fmt::Display, { - self.status = value + self.financial_institution = value.try_into().map_err(|e| { + format!( + "error converting supplied value for financial_institution: {}", + e + ) + }); + self + } + pub fn name(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.name = value .try_into() - .map_err(|e| format!("error converting supplied value for status: {}", e)); + .map_err(|e| format!("error converting supplied value for name: {}", e)); self } - pub fn succeeded_at(mut self, value: T) -> Self + pub fn wallet_type(mut self, value: T) -> Self where T: ::std::convert::TryInto< - ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + ::std::option::Option, >, T::Error: ::std::fmt::Display, { - self.succeeded_at = value.try_into().map_err(|e| { - format!("error converting supplied value for succeeded_at: {}", e) - }); + self.wallet_type = value + .try_into() + .map_err(|e| format!("error converting supplied value for wallet_type: {}", e)); self } } - impl ::std::convert::TryFrom for super::WebhookEventResponse { + impl ::std::convert::TryFrom for super::TravelRuleBeneficiary { type Error = super::error::ConversionError; fn try_from( - value: WebhookEventResponse, + value: TravelRuleBeneficiary, ) -> ::std::result::Result { Ok(Self { - created_at: value.created_at?, - event_id: value.event_id?, - event_type_name: value.event_type_name?, - response: value.response?, - retry_count: value.retry_count?, - status: value.status?, - succeeded_at: value.succeeded_at?, + address: value.address?, + financial_institution: value.financial_institution?, + name: value.name?, + wallet_type: value.wallet_type?, }) } } - impl ::std::convert::From for WebhookEventResponse { - fn from(value: super::WebhookEventResponse) -> Self { + impl ::std::convert::From for TravelRuleBeneficiary { + fn from(value: super::TravelRuleBeneficiary) -> Self { Self { - created_at: Ok(value.created_at), - event_id: Ok(value.event_id), - event_type_name: Ok(value.event_type_name), - response: Ok(value.response), - retry_count: Ok(value.retry_count), - status: Ok(value.status), - succeeded_at: Ok(value.succeeded_at), + address: Ok(value.address), + financial_institution: Ok(value.financial_institution), + name: Ok(value.name), + wallet_type: Ok(value.wallet_type), } } } #[derive(Clone, Debug)] - pub struct WebhookEventResponseDetail { - body: ::std::result::Result< + pub struct TravelRuleOriginator { + address: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + financial_institution: ::std::result::Result< ::std::option::Option<::std::string::String>, ::std::string::String, >, - elapsed_time_ms: - ::std::result::Result<::std::option::Option, ::std::string::String>, - error_name: ::std::result::Result< + name: ::std::result::Result< ::std::option::Option<::std::string::String>, ::std::string::String, >, - http_code: ::std::result::Result<::std::option::Option, ::std::string::String>, + virtual_asset_service_provider: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, } - impl ::std::default::Default for WebhookEventResponseDetail { + impl ::std::default::Default for TravelRuleOriginator { fn default() -> Self { Self { - body: Ok(Default::default()), - elapsed_time_ms: Ok(Default::default()), - error_name: Ok(Default::default()), - http_code: Ok(Default::default()), + address: Ok(Default::default()), + financial_institution: Ok(Default::default()), + name: Ok(Default::default()), + virtual_asset_service_provider: Ok(Default::default()), } } } - impl WebhookEventResponseDetail { - pub fn body(mut self, value: T) -> Self + impl TravelRuleOriginator { + pub fn address(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.body = value + self.address = value .try_into() - .map_err(|e| format!("error converting supplied value for body: {}", e)); + .map_err(|e| format!("error converting supplied value for address: {}", e)); self } - pub fn elapsed_time_ms(mut self, value: T) -> Self + pub fn financial_institution(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option>, + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, T::Error: ::std::fmt::Display, { - self.elapsed_time_ms = value.try_into().map_err(|e| { - format!("error converting supplied value for elapsed_time_ms: {}", e) + self.financial_institution = value.try_into().map_err(|e| { + format!( + "error converting supplied value for financial_institution: {}", + e + ) }); self } - pub fn error_name(mut self, value: T) -> Self + pub fn name(mut self, value: T) -> Self where T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, T::Error: ::std::fmt::Display, { - self.error_name = value + self.name = value .try_into() - .map_err(|e| format!("error converting supplied value for error_name: {}", e)); + .map_err(|e| format!("error converting supplied value for name: {}", e)); self } - pub fn http_code(mut self, value: T) -> Self + pub fn virtual_asset_service_provider(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option>, + T: ::std::convert::TryInto< + ::std::option::Option, + >, T::Error: ::std::fmt::Display, { - self.http_code = value - .try_into() - .map_err(|e| format!("error converting supplied value for http_code: {}", e)); + self.virtual_asset_service_provider = value.try_into().map_err(|e| { + format!( + "error converting supplied value for virtual_asset_service_provider: {}", + e + ) + }); self } } - impl ::std::convert::TryFrom for super::WebhookEventResponseDetail { + impl ::std::convert::TryFrom for super::TravelRuleOriginator { type Error = super::error::ConversionError; fn try_from( - value: WebhookEventResponseDetail, + value: TravelRuleOriginator, ) -> ::std::result::Result { Ok(Self { - body: value.body?, - elapsed_time_ms: value.elapsed_time_ms?, - error_name: value.error_name?, - http_code: value.http_code?, + address: value.address?, + financial_institution: value.financial_institution?, + name: value.name?, + virtual_asset_service_provider: value.virtual_asset_service_provider?, }) } } - impl ::std::convert::From for WebhookEventResponseDetail { - fn from(value: super::WebhookEventResponseDetail) -> Self { + impl ::std::convert::From for TravelRuleOriginator { + fn from(value: super::TravelRuleOriginator) -> Self { Self { - body: Ok(value.body), - elapsed_time_ms: Ok(value.elapsed_time_ms), - error_name: Ok(value.error_name), - http_code: Ok(value.http_code), + address: Ok(value.address), + financial_institution: Ok(value.financial_institution), + name: Ok(value.name), + virtual_asset_service_provider: Ok(value.virtual_asset_service_provider), } } } #[derive(Clone, Debug)] - pub struct WebhookSubscriptionListResponse { - next_page_token: ::std::result::Result< + pub struct TravelRuleOriginatorVirtualAssetServiceProvider { + address: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + identifier: ::std::result::Result< ::std::option::Option<::std::string::String>, ::std::string::String, >, - subscriptions: ::std::result::Result< - ::std::vec::Vec, + name: ::std::result::Result< + ::std::option::Option<::std::string::String>, ::std::string::String, >, } - impl ::std::default::Default for WebhookSubscriptionListResponse { + impl ::std::default::Default for TravelRuleOriginatorVirtualAssetServiceProvider { fn default() -> Self { Self { - next_page_token: Ok(Default::default()), - subscriptions: Err("no value supplied for subscriptions".to_string()), + address: Ok(Default::default()), + identifier: Ok(Default::default()), + name: Ok(Default::default()), } } } - impl WebhookSubscriptionListResponse { - pub fn next_page_token(mut self, value: T) -> Self + impl TravelRuleOriginatorVirtualAssetServiceProvider { + pub fn address(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.address = value + .try_into() + .map_err(|e| format!("error converting supplied value for address: {}", e)); + self + } + pub fn identifier(mut self, value: T) -> Self where T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, T::Error: ::std::fmt::Display, { - self.next_page_token = value.try_into().map_err(|e| { - format!("error converting supplied value for next_page_token: {}", e) - }); + self.identifier = value + .try_into() + .map_err(|e| format!("error converting supplied value for identifier: {}", e)); self } - pub fn subscriptions(mut self, value: T) -> Self + pub fn name(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::vec::Vec>, + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, T::Error: ::std::fmt::Display, { - self.subscriptions = value.try_into().map_err(|e| { - format!("error converting supplied value for subscriptions: {}", e) - }); + self.name = value + .try_into() + .map_err(|e| format!("error converting supplied value for name: {}", e)); self } } - impl ::std::convert::TryFrom - for super::WebhookSubscriptionListResponse + impl ::std::convert::TryFrom + for super::TravelRuleOriginatorVirtualAssetServiceProvider { type Error = super::error::ConversionError; fn try_from( - value: WebhookSubscriptionListResponse, + value: TravelRuleOriginatorVirtualAssetServiceProvider, ) -> ::std::result::Result { Ok(Self { - next_page_token: value.next_page_token?, - subscriptions: value.subscriptions?, + address: value.address?, + identifier: value.identifier?, + name: value.name?, }) } } - impl ::std::convert::From - for WebhookSubscriptionListResponse + impl ::std::convert::From + for TravelRuleOriginatorVirtualAssetServiceProvider { - fn from(value: super::WebhookSubscriptionListResponse) -> Self { + fn from(value: super::TravelRuleOriginatorVirtualAssetServiceProvider) -> Self { Self { - next_page_token: Ok(value.next_page_token), - subscriptions: Ok(value.subscriptions), + address: Ok(value.address), + identifier: Ok(value.identifier), + name: Ok(value.name), } } } #[derive(Clone, Debug)] - pub struct WebhookSubscriptionRequest { - description: ::std::result::Result< - ::std::option::Option, - ::std::string::String, - >, - event_types: ::std::result::Result< - ::std::vec::Vec<::std::string::String>, + pub struct TravelRuleParty { + address: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, - is_enabled: ::std::result::Result, - labels: ::std::result::Result< - ::std::collections::HashMap<::std::string::String, ::std::string::String>, + financial_institution: ::std::result::Result< + ::std::option::Option<::std::string::String>, ::std::string::String, >, - metadata: ::std::result::Result< - ::std::option::Option, + name: ::std::result::Result< + ::std::option::Option<::std::string::String>, ::std::string::String, >, - target: ::std::result::Result, } - impl ::std::default::Default for WebhookSubscriptionRequest { + impl ::std::default::Default for TravelRuleParty { fn default() -> Self { Self { - description: Ok(Default::default()), - event_types: Err("no value supplied for event_types".to_string()), - is_enabled: Err("no value supplied for is_enabled".to_string()), - labels: Ok(Default::default()), - metadata: Ok(Default::default()), - target: Err("no value supplied for target".to_string()), + address: Ok(Default::default()), + financial_institution: Ok(Default::default()), + name: Ok(Default::default()), } } } - impl WebhookSubscriptionRequest { - pub fn description(mut self, value: T) -> Self + impl TravelRuleParty { + pub fn address(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option>, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.description = value + self.address = value .try_into() - .map_err(|e| format!("error converting supplied value for description: {}", e)); + .map_err(|e| format!("error converting supplied value for address: {}", e)); self } - pub fn event_types(mut self, value: T) -> Self + pub fn financial_institution(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::vec::Vec<::std::string::String>>, + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, T::Error: ::std::fmt::Display, { - self.event_types = value - .try_into() - .map_err(|e| format!("error converting supplied value for event_types: {}", e)); + self.financial_institution = value.try_into().map_err(|e| { + format!( + "error converting supplied value for financial_institution: {}", + e + ) + }); self } - pub fn is_enabled(mut self, value: T) -> Self + pub fn name(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, T::Error: ::std::fmt::Display, { - self.is_enabled = value - .try_into() - .map_err(|e| format!("error converting supplied value for is_enabled: {}", e)); - self - } - pub fn labels(mut self, value: T) -> Self - where - T: ::std::convert::TryInto< - ::std::collections::HashMap<::std::string::String, ::std::string::String>, - >, - T::Error: ::std::fmt::Display, - { - self.labels = value - .try_into() - .map_err(|e| format!("error converting supplied value for labels: {}", e)); - self - } - pub fn metadata(mut self, value: T) -> Self - where - T: ::std::convert::TryInto<::std::option::Option>, - T::Error: ::std::fmt::Display, - { - self.metadata = value - .try_into() - .map_err(|e| format!("error converting supplied value for metadata: {}", e)); - self - } - pub fn target(mut self, value: T) -> Self - where - T: ::std::convert::TryInto, - T::Error: ::std::fmt::Display, - { - self.target = value + self.name = value .try_into() - .map_err(|e| format!("error converting supplied value for target: {}", e)); + .map_err(|e| format!("error converting supplied value for name: {}", e)); self } } - impl ::std::convert::TryFrom for super::WebhookSubscriptionRequest { + impl ::std::convert::TryFrom for super::TravelRuleParty { type Error = super::error::ConversionError; fn try_from( - value: WebhookSubscriptionRequest, + value: TravelRuleParty, ) -> ::std::result::Result { Ok(Self { - description: value.description?, - event_types: value.event_types?, - is_enabled: value.is_enabled?, - labels: value.labels?, - metadata: value.metadata?, - target: value.target?, + address: value.address?, + financial_institution: value.financial_institution?, + name: value.name?, }) } } - impl ::std::convert::From for WebhookSubscriptionRequest { - fn from(value: super::WebhookSubscriptionRequest) -> Self { + impl ::std::convert::From for TravelRuleParty { + fn from(value: super::TravelRuleParty) -> Self { Self { - description: Ok(value.description), - event_types: Ok(value.event_types), - is_enabled: Ok(value.is_enabled), - labels: Ok(value.labels), - metadata: Ok(value.metadata), - target: Ok(value.target), + address: Ok(value.address), + financial_institution: Ok(value.financial_institution), + name: Ok(value.name), } } } #[derive(Clone, Debug)] - pub struct WebhookSubscriptionResponse { - created_at: ::std::result::Result< - ::chrono::DateTime<::chrono::offset::Utc>, - ::std::string::String, - >, - description: ::std::result::Result< - ::std::option::Option, - ::std::string::String, - >, - event_types: ::std::result::Result< - ::std::vec::Vec<::std::string::String>, - ::std::string::String, - >, - is_enabled: ::std::result::Result, - labels: ::std::result::Result< - ::std::collections::HashMap<::std::string::String, ::std::string::String>, - ::std::string::String, - >, - metadata: ::std::result::Result< - ::std::option::Option, + pub struct UpdateEvmAccountBody { + account_policy: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, - secret: ::std::result::Result<::uuid::Uuid, ::std::string::String>, - subscription_id: ::std::result::Result<::uuid::Uuid, ::std::string::String>, - target: ::std::result::Result, - updated_at: ::std::result::Result< - ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + name: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, } - impl ::std::default::Default for WebhookSubscriptionResponse { + impl ::std::default::Default for UpdateEvmAccountBody { fn default() -> Self { Self { - created_at: Err("no value supplied for created_at".to_string()), - description: Ok(Default::default()), - event_types: Err("no value supplied for event_types".to_string()), - is_enabled: Err("no value supplied for is_enabled".to_string()), - labels: Ok(Default::default()), - metadata: Ok(Default::default()), - secret: Err("no value supplied for secret".to_string()), - subscription_id: Err("no value supplied for subscription_id".to_string()), - target: Err("no value supplied for target".to_string()), - updated_at: Ok(Default::default()), + account_policy: Ok(Default::default()), + name: Ok(Default::default()), } } } - impl WebhookSubscriptionResponse { - pub fn created_at(mut self, value: T) -> Self + impl UpdateEvmAccountBody { + pub fn account_policy(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, + T: ::std::convert::TryInto< + ::std::option::Option, + >, T::Error: ::std::fmt::Display, { - self.created_at = value - .try_into() - .map_err(|e| format!("error converting supplied value for created_at: {}", e)); + self.account_policy = value.try_into().map_err(|e| { + format!("error converting supplied value for account_policy: {}", e) + }); self } - pub fn description(mut self, value: T) -> Self + pub fn name(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option>, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.description = value + self.name = value .try_into() - .map_err(|e| format!("error converting supplied value for description: {}", e)); + .map_err(|e| format!("error converting supplied value for name: {}", e)); self } - pub fn event_types(mut self, value: T) -> Self - where - T: ::std::convert::TryInto<::std::vec::Vec<::std::string::String>>, - T::Error: ::std::fmt::Display, - { - self.event_types = value - .try_into() - .map_err(|e| format!("error converting supplied value for event_types: {}", e)); - self + } + impl ::std::convert::TryFrom for super::UpdateEvmAccountBody { + type Error = super::error::ConversionError; + fn try_from( + value: UpdateEvmAccountBody, + ) -> ::std::result::Result { + Ok(Self { + account_policy: value.account_policy?, + name: value.name?, + }) } - pub fn is_enabled(mut self, value: T) -> Self - where - T: ::std::convert::TryInto, - T::Error: ::std::fmt::Display, - { - self.is_enabled = value - .try_into() - .map_err(|e| format!("error converting supplied value for is_enabled: {}", e)); - self + } + impl ::std::convert::From for UpdateEvmAccountBody { + fn from(value: super::UpdateEvmAccountBody) -> Self { + Self { + account_policy: Ok(value.account_policy), + name: Ok(value.name), + } } - pub fn labels(mut self, value: T) -> Self - where - T: ::std::convert::TryInto< - ::std::collections::HashMap<::std::string::String, ::std::string::String>, - >, - T::Error: ::std::fmt::Display, - { - self.labels = value - .try_into() - .map_err(|e| format!("error converting supplied value for labels: {}", e)); - self + } + #[derive(Clone, Debug)] + pub struct UpdateEvmSmartAccountBody { + name: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + } + impl ::std::default::Default for UpdateEvmSmartAccountBody { + fn default() -> Self { + Self { + name: Ok(Default::default()), + } } - pub fn metadata(mut self, value: T) -> Self + } + impl UpdateEvmSmartAccountBody { + pub fn name(mut self, value: T) -> Self where T: ::std::convert::TryInto< - ::std::option::Option, + ::std::option::Option, >, T::Error: ::std::fmt::Display, { - self.metadata = value + self.name = value .try_into() - .map_err(|e| format!("error converting supplied value for metadata: {}", e)); + .map_err(|e| format!("error converting supplied value for name: {}", e)); self } - pub fn secret(mut self, value: T) -> Self - where - T: ::std::convert::TryInto<::uuid::Uuid>, - T::Error: ::std::fmt::Display, - { - self.secret = value - .try_into() - .map_err(|e| format!("error converting supplied value for secret: {}", e)); - self + } + impl ::std::convert::TryFrom for super::UpdateEvmSmartAccountBody { + type Error = super::error::ConversionError; + fn try_from( + value: UpdateEvmSmartAccountBody, + ) -> ::std::result::Result { + Ok(Self { name: value.name? }) } - pub fn subscription_id(mut self, value: T) -> Self - where - T: ::std::convert::TryInto<::uuid::Uuid>, - T::Error: ::std::fmt::Display, - { - self.subscription_id = value.try_into().map_err(|e| { - format!("error converting supplied value for subscription_id: {}", e) - }); - self + } + impl ::std::convert::From for UpdateEvmSmartAccountBody { + fn from(value: super::UpdateEvmSmartAccountBody) -> Self { + Self { + name: Ok(value.name), + } } - pub fn target(mut self, value: T) -> Self + } + #[derive(Clone, Debug)] + pub struct UpdatePolicyBody { + description: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + rules: ::std::result::Result<::std::vec::Vec, ::std::string::String>, + } + impl ::std::default::Default for UpdatePolicyBody { + fn default() -> Self { + Self { + description: Ok(Default::default()), + rules: Err("no value supplied for rules".to_string()), + } + } + } + impl UpdatePolicyBody { + pub fn description(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto< + ::std::option::Option, + >, T::Error: ::std::fmt::Display, { - self.target = value + self.description = value .try_into() - .map_err(|e| format!("error converting supplied value for target: {}", e)); + .map_err(|e| format!("error converting supplied value for description: {}", e)); self } - pub fn updated_at(mut self, value: T) -> Self + pub fn rules(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, - >, + T: ::std::convert::TryInto<::std::vec::Vec>, T::Error: ::std::fmt::Display, { - self.updated_at = value + self.rules = value .try_into() - .map_err(|e| format!("error converting supplied value for updated_at: {}", e)); + .map_err(|e| format!("error converting supplied value for rules: {}", e)); self } } - impl ::std::convert::TryFrom for super::WebhookSubscriptionResponse { + impl ::std::convert::TryFrom for super::UpdatePolicyBody { type Error = super::error::ConversionError; fn try_from( - value: WebhookSubscriptionResponse, + value: UpdatePolicyBody, ) -> ::std::result::Result { Ok(Self { - created_at: value.created_at?, description: value.description?, - event_types: value.event_types?, - is_enabled: value.is_enabled?, - labels: value.labels?, - metadata: value.metadata?, - secret: value.secret?, - subscription_id: value.subscription_id?, - target: value.target?, - updated_at: value.updated_at?, + rules: value.rules?, }) } } - impl ::std::convert::From for WebhookSubscriptionResponse { - fn from(value: super::WebhookSubscriptionResponse) -> Self { + impl ::std::convert::From for UpdatePolicyBody { + fn from(value: super::UpdatePolicyBody) -> Self { Self { - created_at: Ok(value.created_at), description: Ok(value.description), - event_types: Ok(value.event_types), - is_enabled: Ok(value.is_enabled), - labels: Ok(value.labels), - metadata: Ok(value.metadata), - secret: Ok(value.secret), - subscription_id: Ok(value.subscription_id), - target: Ok(value.target), - updated_at: Ok(value.updated_at), + rules: Ok(value.rules), } } } #[derive(Clone, Debug)] - pub struct WebhookSubscriptionResponseMetadata { - secret: - ::std::result::Result<::std::option::Option<::uuid::Uuid>, ::std::string::String>, - extra: ::std::result::Result< - ::std::collections::HashMap< - ::std::string::String, - super::WebhookSubscriptionResponseMetadataExtraValue, - >, + pub struct UpdateSolanaAccountBody { + account_policy: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + name: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, } - impl ::std::default::Default for WebhookSubscriptionResponseMetadata { + impl ::std::default::Default for UpdateSolanaAccountBody { fn default() -> Self { Self { - secret: Ok(Default::default()), - extra: Err("no value supplied for extra".to_string()), + account_policy: Ok(Default::default()), + name: Ok(Default::default()), } } } - impl WebhookSubscriptionResponseMetadata { - pub fn secret(mut self, value: T) -> Self + impl UpdateSolanaAccountBody { + pub fn account_policy(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option<::uuid::Uuid>>, + T: ::std::convert::TryInto< + ::std::option::Option, + >, T::Error: ::std::fmt::Display, { - self.secret = value - .try_into() - .map_err(|e| format!("error converting supplied value for secret: {}", e)); + self.account_policy = value.try_into().map_err(|e| { + format!("error converting supplied value for account_policy: {}", e) + }); self } - pub fn extra(mut self, value: T) -> Self + pub fn name(mut self, value: T) -> Self where T: ::std::convert::TryInto< - ::std::collections::HashMap< - ::std::string::String, - super::WebhookSubscriptionResponseMetadataExtraValue, - >, + ::std::option::Option, >, T::Error: ::std::fmt::Display, { - self.extra = value + self.name = value .try_into() - .map_err(|e| format!("error converting supplied value for extra: {}", e)); + .map_err(|e| format!("error converting supplied value for name: {}", e)); self } } - impl ::std::convert::TryFrom - for super::WebhookSubscriptionResponseMetadata - { + impl ::std::convert::TryFrom for super::UpdateSolanaAccountBody { type Error = super::error::ConversionError; fn try_from( - value: WebhookSubscriptionResponseMetadata, + value: UpdateSolanaAccountBody, ) -> ::std::result::Result { Ok(Self { - secret: value.secret?, - extra: value.extra?, + account_policy: value.account_policy?, + name: value.name?, }) } } - impl ::std::convert::From - for WebhookSubscriptionResponseMetadata - { - fn from(value: super::WebhookSubscriptionResponseMetadata) -> Self { + impl ::std::convert::From for UpdateSolanaAccountBody { + fn from(value: super::UpdateSolanaAccountBody) -> Self { Self { - secret: Ok(value.secret), - extra: Ok(value.extra), + account_policy: Ok(value.account_policy), + name: Ok(value.name), } } } #[derive(Clone, Debug)] - pub struct WebhookSubscriptionUpdateRequest { - description: ::std::result::Result< - ::std::option::Option, + pub struct UserOperationReceipt { + block_hash: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, - event_types: ::std::result::Result< - ::std::vec::Vec<::std::string::String>, + block_number: ::std::result::Result<::std::option::Option, ::std::string::String>, + gas_used: ::std::result::Result< + ::std::option::Option<::std::string::String>, ::std::string::String, >, - is_enabled: ::std::result::Result, - labels: ::std::result::Result< - ::std::collections::HashMap<::std::string::String, ::std::string::String>, + revert: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, - metadata: ::std::result::Result< - ::std::option::Option, + transaction_hash: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, - target: ::std::result::Result, } - impl ::std::default::Default for WebhookSubscriptionUpdateRequest { + impl ::std::default::Default for UserOperationReceipt { fn default() -> Self { Self { - description: Ok(Default::default()), - event_types: Err("no value supplied for event_types".to_string()), - is_enabled: Err("no value supplied for is_enabled".to_string()), - labels: Ok(Default::default()), - metadata: Ok(Default::default()), - target: Err("no value supplied for target".to_string()), + block_hash: Ok(Default::default()), + block_number: Ok(Default::default()), + gas_used: Ok(Default::default()), + revert: Ok(Default::default()), + transaction_hash: Ok(Default::default()), } } } - impl WebhookSubscriptionUpdateRequest { - pub fn description(mut self, value: T) -> Self + impl UserOperationReceipt { + pub fn block_hash(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option>, + T: ::std::convert::TryInto< + ::std::option::Option, + >, T::Error: ::std::fmt::Display, { - self.description = value + self.block_hash = value .try_into() - .map_err(|e| format!("error converting supplied value for description: {}", e)); + .map_err(|e| format!("error converting supplied value for block_hash: {}", e)); self } - pub fn event_types(mut self, value: T) -> Self + pub fn block_number(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::vec::Vec<::std::string::String>>, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.event_types = value - .try_into() - .map_err(|e| format!("error converting supplied value for event_types: {}", e)); + self.block_number = value.try_into().map_err(|e| { + format!("error converting supplied value for block_number: {}", e) + }); self } - pub fn is_enabled(mut self, value: T) -> Self + pub fn gas_used(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, T::Error: ::std::fmt::Display, { - self.is_enabled = value + self.gas_used = value .try_into() - .map_err(|e| format!("error converting supplied value for is_enabled: {}", e)); + .map_err(|e| format!("error converting supplied value for gas_used: {}", e)); self } - pub fn labels(mut self, value: T) -> Self + pub fn revert(mut self, value: T) -> Self where T: ::std::convert::TryInto< - ::std::collections::HashMap<::std::string::String, ::std::string::String>, + ::std::option::Option, >, T::Error: ::std::fmt::Display, { - self.labels = value - .try_into() - .map_err(|e| format!("error converting supplied value for labels: {}", e)); - self - } - pub fn metadata(mut self, value: T) -> Self - where - T: ::std::convert::TryInto<::std::option::Option>, - T::Error: ::std::fmt::Display, - { - self.metadata = value + self.revert = value .try_into() - .map_err(|e| format!("error converting supplied value for metadata: {}", e)); + .map_err(|e| format!("error converting supplied value for revert: {}", e)); self } - pub fn target(mut self, value: T) -> Self + pub fn transaction_hash(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto< + ::std::option::Option, + >, T::Error: ::std::fmt::Display, { - self.target = value - .try_into() - .map_err(|e| format!("error converting supplied value for target: {}", e)); + self.transaction_hash = value.try_into().map_err(|e| { + format!( + "error converting supplied value for transaction_hash: {}", + e + ) + }); self } } - impl ::std::convert::TryFrom - for super::WebhookSubscriptionUpdateRequest - { + impl ::std::convert::TryFrom for super::UserOperationReceipt { type Error = super::error::ConversionError; fn try_from( - value: WebhookSubscriptionUpdateRequest, + value: UserOperationReceipt, ) -> ::std::result::Result { Ok(Self { - description: value.description?, - event_types: value.event_types?, - is_enabled: value.is_enabled?, - labels: value.labels?, - metadata: value.metadata?, - target: value.target?, + block_hash: value.block_hash?, + block_number: value.block_number?, + gas_used: value.gas_used?, + revert: value.revert?, + transaction_hash: value.transaction_hash?, }) } } - impl ::std::convert::From - for WebhookSubscriptionUpdateRequest - { - fn from(value: super::WebhookSubscriptionUpdateRequest) -> Self { + impl ::std::convert::From for UserOperationReceipt { + fn from(value: super::UserOperationReceipt) -> Self { Self { - description: Ok(value.description), - event_types: Ok(value.event_types), - is_enabled: Ok(value.is_enabled), - labels: Ok(value.labels), - metadata: Ok(value.metadata), - target: Ok(value.target), + block_hash: Ok(value.block_hash), + block_number: Ok(value.block_number), + gas_used: Ok(value.gas_used), + revert: Ok(value.revert), + transaction_hash: Ok(value.transaction_hash), } } } #[derive(Clone, Debug)] - pub struct WebhookTarget { - headers: ::std::result::Result< - ::std::collections::HashMap<::std::string::String, ::std::string::String>, - ::std::string::String, - >, - url: ::std::result::Result, + pub struct UserOperationReceiptRevert { + data: + ::std::result::Result, + message: ::std::result::Result<::std::string::String, ::std::string::String>, } - impl ::std::default::Default for WebhookTarget { + impl ::std::default::Default for UserOperationReceiptRevert { fn default() -> Self { Self { - headers: Ok(Default::default()), - url: Err("no value supplied for url".to_string()), + data: Err("no value supplied for data".to_string()), + message: Err("no value supplied for message".to_string()), } } } - impl WebhookTarget { - pub fn headers(mut self, value: T) -> Self + impl UserOperationReceiptRevert { + pub fn data(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - ::std::collections::HashMap<::std::string::String, ::std::string::String>, - >, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.headers = value + self.data = value .try_into() - .map_err(|e| format!("error converting supplied value for headers: {}", e)); + .map_err(|e| format!("error converting supplied value for data: {}", e)); self } - pub fn url(mut self, value: T) -> Self + pub fn message(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::string::String>, T::Error: ::std::fmt::Display, { - self.url = value + self.message = value .try_into() - .map_err(|e| format!("error converting supplied value for url: {}", e)); + .map_err(|e| format!("error converting supplied value for message: {}", e)); self } } - impl ::std::convert::TryFrom for super::WebhookTarget { + impl ::std::convert::TryFrom for super::UserOperationReceiptRevert { type Error = super::error::ConversionError; fn try_from( - value: WebhookTarget, + value: UserOperationReceiptRevert, ) -> ::std::result::Result { Ok(Self { - headers: value.headers?, - url: value.url?, + data: value.data?, + message: value.message?, }) } } - impl ::std::convert::From for WebhookTarget { - fn from(value: super::WebhookTarget) -> Self { + impl ::std::convert::From for UserOperationReceiptRevert { + fn from(value: super::UserOperationReceiptRevert) -> Self { Self { - headers: Ok(value.headers), - url: Ok(value.url), + data: Ok(value.data), + message: Ok(value.message), } } } #[derive(Clone, Debug)] - pub struct X402DiscoveryMerchantResponse { - pagination: ::std::result::Result< - super::X402DiscoveryMerchantResponsePagination, - ::std::string::String, - >, - pay_to: ::std::result::Result, - resources: ::std::result::Result< - ::std::vec::Vec, - ::std::string::String, - >, - x402_version: ::std::result::Result, + pub struct ValidateEndUserAccessTokenBody { + access_token: ::std::result::Result<::std::string::String, ::std::string::String>, } - impl ::std::default::Default for X402DiscoveryMerchantResponse { + impl ::std::default::Default for ValidateEndUserAccessTokenBody { fn default() -> Self { Self { - pagination: Err("no value supplied for pagination".to_string()), - pay_to: Err("no value supplied for pay_to".to_string()), - resources: Err("no value supplied for resources".to_string()), - x402_version: Err("no value supplied for x402_version".to_string()), + access_token: Err("no value supplied for access_token".to_string()), } } } - impl X402DiscoveryMerchantResponse { - pub fn pagination(mut self, value: T) -> Self + impl ValidateEndUserAccessTokenBody { + pub fn access_token(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::string::String>, T::Error: ::std::fmt::Display, { - self.pagination = value - .try_into() - .map_err(|e| format!("error converting supplied value for pagination: {}", e)); + self.access_token = value.try_into().map_err(|e| { + format!("error converting supplied value for access_token: {}", e) + }); self } - pub fn pay_to(mut self, value: T) -> Self + } + impl ::std::convert::TryFrom + for super::ValidateEndUserAccessTokenBody + { + type Error = super::error::ConversionError; + fn try_from( + value: ValidateEndUserAccessTokenBody, + ) -> ::std::result::Result { + Ok(Self { + access_token: value.access_token?, + }) + } + } + impl ::std::convert::From + for ValidateEndUserAccessTokenBody + { + fn from(value: super::ValidateEndUserAccessTokenBody) -> Self { + Self { + access_token: Ok(value.access_token), + } + } + } + #[derive(Clone, Debug)] + pub struct VerifyX402PaymentBody { + payment_payload: + ::std::result::Result, + payment_requirements: + ::std::result::Result, + x402_version: ::std::result::Result, + } + impl ::std::default::Default for VerifyX402PaymentBody { + fn default() -> Self { + Self { + payment_payload: Err("no value supplied for payment_payload".to_string()), + payment_requirements: Err( + "no value supplied for payment_requirements".to_string() + ), + x402_version: Err("no value supplied for x402_version".to_string()), + } + } + } + impl VerifyX402PaymentBody { + pub fn payment_payload(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.pay_to = value - .try_into() - .map_err(|e| format!("error converting supplied value for pay_to: {}", e)); + self.payment_payload = value.try_into().map_err(|e| { + format!("error converting supplied value for payment_payload: {}", e) + }); self } - pub fn resources(mut self, value: T) -> Self + pub fn payment_requirements(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::vec::Vec>, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.resources = value - .try_into() - .map_err(|e| format!("error converting supplied value for resources: {}", e)); + self.payment_requirements = value.try_into().map_err(|e| { + format!( + "error converting supplied value for payment_requirements: {}", + e + ) + }); self } pub fn x402_version(mut self, value: T) -> Self @@ -79841,1865 +90652,2016 @@ pub mod types { self } } - impl ::std::convert::TryFrom - for super::X402DiscoveryMerchantResponse - { + impl ::std::convert::TryFrom for super::VerifyX402PaymentBody { type Error = super::error::ConversionError; fn try_from( - value: X402DiscoveryMerchantResponse, + value: VerifyX402PaymentBody, ) -> ::std::result::Result { Ok(Self { - pagination: value.pagination?, - pay_to: value.pay_to?, - resources: value.resources?, + payment_payload: value.payment_payload?, + payment_requirements: value.payment_requirements?, x402_version: value.x402_version?, }) } } - impl ::std::convert::From for X402DiscoveryMerchantResponse { - fn from(value: super::X402DiscoveryMerchantResponse) -> Self { + impl ::std::convert::From for VerifyX402PaymentBody { + fn from(value: super::VerifyX402PaymentBody) -> Self { Self { - pagination: Ok(value.pagination), - pay_to: Ok(value.pay_to), - resources: Ok(value.resources), + payment_payload: Ok(value.payment_payload), + payment_requirements: Ok(value.payment_requirements), x402_version: Ok(value.x402_version), } } } #[derive(Clone, Debug)] - pub struct X402DiscoveryMerchantResponsePagination { - limit: ::std::result::Result<::std::option::Option, ::std::string::String>, - offset: ::std::result::Result<::std::option::Option, ::std::string::String>, - total: ::std::result::Result<::std::option::Option, ::std::string::String>, + pub struct VerifyX402PaymentResponse { + invalid_message: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + invalid_reason: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + is_valid: ::std::result::Result, + payer: + ::std::result::Result, } - impl ::std::default::Default for X402DiscoveryMerchantResponsePagination { + impl ::std::default::Default for VerifyX402PaymentResponse { fn default() -> Self { Self { - limit: Ok(Default::default()), - offset: Ok(Default::default()), - total: Ok(Default::default()), + invalid_message: Ok(Default::default()), + invalid_reason: Ok(Default::default()), + is_valid: Err("no value supplied for is_valid".to_string()), + payer: Err("no value supplied for payer".to_string()), } } } - impl X402DiscoveryMerchantResponsePagination { - pub fn limit(mut self, value: T) -> Self + impl VerifyX402PaymentResponse { + pub fn invalid_message(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option>, + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, T::Error: ::std::fmt::Display, { - self.limit = value - .try_into() - .map_err(|e| format!("error converting supplied value for limit: {}", e)); + self.invalid_message = value.try_into().map_err(|e| { + format!("error converting supplied value for invalid_message: {}", e) + }); self } - pub fn offset(mut self, value: T) -> Self + pub fn invalid_reason(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option>, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.offset = value + self.invalid_reason = value.try_into().map_err(|e| { + format!("error converting supplied value for invalid_reason: {}", e) + }); + self + } + pub fn is_valid(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.is_valid = value .try_into() - .map_err(|e| format!("error converting supplied value for offset: {}", e)); + .map_err(|e| format!("error converting supplied value for is_valid: {}", e)); self } - pub fn total(mut self, value: T) -> Self + pub fn payer(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option>, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.total = value + self.payer = value .try_into() - .map_err(|e| format!("error converting supplied value for total: {}", e)); + .map_err(|e| format!("error converting supplied value for payer: {}", e)); self } } - impl ::std::convert::TryFrom - for super::X402DiscoveryMerchantResponsePagination - { + impl ::std::convert::TryFrom for super::VerifyX402PaymentResponse { type Error = super::error::ConversionError; fn try_from( - value: X402DiscoveryMerchantResponsePagination, + value: VerifyX402PaymentResponse, ) -> ::std::result::Result { Ok(Self { - limit: value.limit?, - offset: value.offset?, - total: value.total?, + invalid_message: value.invalid_message?, + invalid_reason: value.invalid_reason?, + is_valid: value.is_valid?, + payer: value.payer?, }) } } - impl ::std::convert::From - for X402DiscoveryMerchantResponsePagination - { - fn from(value: super::X402DiscoveryMerchantResponsePagination) -> Self { + impl ::std::convert::From for VerifyX402PaymentResponse { + fn from(value: super::VerifyX402PaymentResponse) -> Self { Self { - limit: Ok(value.limit), - offset: Ok(value.offset), - total: Ok(value.total), + invalid_message: Ok(value.invalid_message), + invalid_reason: Ok(value.invalid_reason), + is_valid: Ok(value.is_valid), + payer: Ok(value.payer), } } } #[derive(Clone, Debug)] - pub struct X402DiscoveryResource { - accepts: ::std::result::Result< - ::std::vec::Vec, + pub struct WebhookEventListResponse { + events: ::std::result::Result< + ::std::vec::Vec, ::std::string::String, >, - description: ::std::result::Result< - ::std::option::Option<::std::string::String>, + } + impl ::std::default::Default for WebhookEventListResponse { + fn default() -> Self { + Self { + events: Err("no value supplied for events".to_string()), + } + } + } + impl WebhookEventListResponse { + pub fn events(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::vec::Vec>, + T::Error: ::std::fmt::Display, + { + self.events = value + .try_into() + .map_err(|e| format!("error converting supplied value for events: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::WebhookEventListResponse { + type Error = super::error::ConversionError; + fn try_from( + value: WebhookEventListResponse, + ) -> ::std::result::Result { + Ok(Self { + events: value.events?, + }) + } + } + impl ::std::convert::From for WebhookEventListResponse { + fn from(value: super::WebhookEventListResponse) -> Self { + Self { + events: Ok(value.events), + } + } + } + #[derive(Clone, Debug)] + pub struct WebhookEventResponse { + created_at: ::std::result::Result< + ::chrono::DateTime<::chrono::offset::Utc>, ::std::string::String, >, - extensions: ::std::result::Result< - ::serde_json::Map<::std::string::String, ::serde_json::Value>, + event_id: ::std::result::Result<::std::string::String, ::std::string::String>, + event_type_name: ::std::result::Result<::std::string::String, ::std::string::String>, + response: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, - last_updated: ::std::result::Result< + retry_count: ::std::result::Result, + status: ::std::result::Result, + succeeded_at: ::std::result::Result< ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, ::std::string::String, >, - quality: ::std::result::Result< - ::std::option::Option, - ::std::string::String, - >, - resource: ::std::result::Result<::std::string::String, ::std::string::String>, - type_: ::std::result::Result, - x402_version: ::std::result::Result, } - impl ::std::default::Default for X402DiscoveryResource { + impl ::std::default::Default for WebhookEventResponse { fn default() -> Self { Self { - accepts: Ok(Default::default()), - description: Ok(Default::default()), - extensions: Ok(Default::default()), - last_updated: Ok(Default::default()), - quality: Ok(Default::default()), - resource: Err("no value supplied for resource".to_string()), - type_: Err("no value supplied for type_".to_string()), - x402_version: Err("no value supplied for x402_version".to_string()), + created_at: Err("no value supplied for created_at".to_string()), + event_id: Err("no value supplied for event_id".to_string()), + event_type_name: Err("no value supplied for event_type_name".to_string()), + response: Ok(Default::default()), + retry_count: Err("no value supplied for retry_count".to_string()), + status: Err("no value supplied for status".to_string()), + succeeded_at: Ok(Default::default()), } } } - impl X402DiscoveryResource { - pub fn accepts(mut self, value: T) -> Self + impl WebhookEventResponse { + pub fn created_at(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::vec::Vec>, + T: ::std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, T::Error: ::std::fmt::Display, { - self.accepts = value + self.created_at = value .try_into() - .map_err(|e| format!("error converting supplied value for accepts: {}", e)); + .map_err(|e| format!("error converting supplied value for created_at: {}", e)); self } - pub fn description(mut self, value: T) -> Self + pub fn event_id(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T: ::std::convert::TryInto<::std::string::String>, T::Error: ::std::fmt::Display, { - self.description = value + self.event_id = value .try_into() - .map_err(|e| format!("error converting supplied value for description: {}", e)); + .map_err(|e| format!("error converting supplied value for event_id: {}", e)); self } - pub fn extensions(mut self, value: T) -> Self + pub fn event_type_name(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - ::serde_json::Map<::std::string::String, ::serde_json::Value>, - >, + T: ::std::convert::TryInto<::std::string::String>, T::Error: ::std::fmt::Display, { - self.extensions = value - .try_into() - .map_err(|e| format!("error converting supplied value for extensions: {}", e)); + self.event_type_name = value.try_into().map_err(|e| { + format!("error converting supplied value for event_type_name: {}", e) + }); self } - pub fn last_updated(mut self, value: T) -> Self + pub fn response(mut self, value: T) -> Self where T: ::std::convert::TryInto< - ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + ::std::option::Option, >, T::Error: ::std::fmt::Display, { - self.last_updated = value.try_into().map_err(|e| { - format!("error converting supplied value for last_updated: {}", e) - }); - self - } - pub fn quality(mut self, value: T) -> Self - where - T: ::std::convert::TryInto<::std::option::Option>, - T::Error: ::std::fmt::Display, - { - self.quality = value + self.response = value .try_into() - .map_err(|e| format!("error converting supplied value for quality: {}", e)); + .map_err(|e| format!("error converting supplied value for response: {}", e)); self } - pub fn resource(mut self, value: T) -> Self + pub fn retry_count(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::string::String>, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.resource = value + self.retry_count = value .try_into() - .map_err(|e| format!("error converting supplied value for resource: {}", e)); + .map_err(|e| format!("error converting supplied value for retry_count: {}", e)); self } - pub fn type_(mut self, value: T) -> Self + pub fn status(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.type_ = value + self.status = value .try_into() - .map_err(|e| format!("error converting supplied value for type_: {}", e)); + .map_err(|e| format!("error converting supplied value for status: {}", e)); self } - pub fn x402_version(mut self, value: T) -> Self + pub fn succeeded_at(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto< + ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + >, T::Error: ::std::fmt::Display, { - self.x402_version = value.try_into().map_err(|e| { - format!("error converting supplied value for x402_version: {}", e) + self.succeeded_at = value.try_into().map_err(|e| { + format!("error converting supplied value for succeeded_at: {}", e) }); self } } - impl ::std::convert::TryFrom for super::X402DiscoveryResource { + impl ::std::convert::TryFrom for super::WebhookEventResponse { type Error = super::error::ConversionError; fn try_from( - value: X402DiscoveryResource, + value: WebhookEventResponse, ) -> ::std::result::Result { Ok(Self { - accepts: value.accepts?, - description: value.description?, - extensions: value.extensions?, - last_updated: value.last_updated?, - quality: value.quality?, - resource: value.resource?, - type_: value.type_?, - x402_version: value.x402_version?, + created_at: value.created_at?, + event_id: value.event_id?, + event_type_name: value.event_type_name?, + response: value.response?, + retry_count: value.retry_count?, + status: value.status?, + succeeded_at: value.succeeded_at?, }) } } - impl ::std::convert::From for X402DiscoveryResource { - fn from(value: super::X402DiscoveryResource) -> Self { + impl ::std::convert::From for WebhookEventResponse { + fn from(value: super::WebhookEventResponse) -> Self { Self { - accepts: Ok(value.accepts), - description: Ok(value.description), - extensions: Ok(value.extensions), - last_updated: Ok(value.last_updated), - quality: Ok(value.quality), - resource: Ok(value.resource), - type_: Ok(value.type_), - x402_version: Ok(value.x402_version), + created_at: Ok(value.created_at), + event_id: Ok(value.event_id), + event_type_name: Ok(value.event_type_name), + response: Ok(value.response), + retry_count: Ok(value.retry_count), + status: Ok(value.status), + succeeded_at: Ok(value.succeeded_at), } } } #[derive(Clone, Debug)] - pub struct X402DiscoveryResourcesResponse { - items: ::std::result::Result< - ::std::vec::Vec, + pub struct WebhookEventResponseDetail { + body: ::std::result::Result< + ::std::option::Option<::std::string::String>, ::std::string::String, >, - pagination: ::std::result::Result< - super::X402DiscoveryResourcesResponsePagination, + elapsed_time_ms: + ::std::result::Result<::std::option::Option, ::std::string::String>, + error_name: ::std::result::Result< + ::std::option::Option<::std::string::String>, ::std::string::String, >, - x402_version: ::std::result::Result, + http_code: ::std::result::Result<::std::option::Option, ::std::string::String>, } - impl ::std::default::Default for X402DiscoveryResourcesResponse { + impl ::std::default::Default for WebhookEventResponseDetail { fn default() -> Self { Self { - items: Err("no value supplied for items".to_string()), - pagination: Err("no value supplied for pagination".to_string()), - x402_version: Err("no value supplied for x402_version".to_string()), + body: Ok(Default::default()), + elapsed_time_ms: Ok(Default::default()), + error_name: Ok(Default::default()), + http_code: Ok(Default::default()), } } } - impl X402DiscoveryResourcesResponse { - pub fn items(mut self, value: T) -> Self + impl WebhookEventResponseDetail { + pub fn body(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::vec::Vec>, + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, T::Error: ::std::fmt::Display, { - self.items = value + self.body = value .try_into() - .map_err(|e| format!("error converting supplied value for items: {}", e)); + .map_err(|e| format!("error converting supplied value for body: {}", e)); self } - pub fn pagination(mut self, value: T) -> Self + pub fn elapsed_time_ms(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.pagination = value + self.elapsed_time_ms = value.try_into().map_err(|e| { + format!("error converting supplied value for elapsed_time_ms: {}", e) + }); + self + } + pub fn error_name(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.error_name = value .try_into() - .map_err(|e| format!("error converting supplied value for pagination: {}", e)); + .map_err(|e| format!("error converting supplied value for error_name: {}", e)); self } - pub fn x402_version(mut self, value: T) -> Self + pub fn http_code(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.x402_version = value.try_into().map_err(|e| { - format!("error converting supplied value for x402_version: {}", e) - }); + self.http_code = value + .try_into() + .map_err(|e| format!("error converting supplied value for http_code: {}", e)); self } } - impl ::std::convert::TryFrom - for super::X402DiscoveryResourcesResponse - { + impl ::std::convert::TryFrom for super::WebhookEventResponseDetail { type Error = super::error::ConversionError; fn try_from( - value: X402DiscoveryResourcesResponse, + value: WebhookEventResponseDetail, ) -> ::std::result::Result { Ok(Self { - items: value.items?, - pagination: value.pagination?, - x402_version: value.x402_version?, + body: value.body?, + elapsed_time_ms: value.elapsed_time_ms?, + error_name: value.error_name?, + http_code: value.http_code?, }) } } - impl ::std::convert::From - for X402DiscoveryResourcesResponse - { - fn from(value: super::X402DiscoveryResourcesResponse) -> Self { + impl ::std::convert::From for WebhookEventResponseDetail { + fn from(value: super::WebhookEventResponseDetail) -> Self { Self { - items: Ok(value.items), - pagination: Ok(value.pagination), - x402_version: Ok(value.x402_version), + body: Ok(value.body), + elapsed_time_ms: Ok(value.elapsed_time_ms), + error_name: Ok(value.error_name), + http_code: Ok(value.http_code), } } } #[derive(Clone, Debug)] - pub struct X402DiscoveryResourcesResponsePagination { - limit: ::std::result::Result<::std::option::Option, ::std::string::String>, - offset: ::std::result::Result<::std::option::Option, ::std::string::String>, - total: ::std::result::Result<::std::option::Option, ::std::string::String>, + pub struct WebhookSubscriptionListResponse { + next_page_token: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + subscriptions: ::std::result::Result< + ::std::vec::Vec, + ::std::string::String, + >, } - impl ::std::default::Default for X402DiscoveryResourcesResponsePagination { + impl ::std::default::Default for WebhookSubscriptionListResponse { fn default() -> Self { Self { - limit: Ok(Default::default()), - offset: Ok(Default::default()), - total: Ok(Default::default()), + next_page_token: Ok(Default::default()), + subscriptions: Err("no value supplied for subscriptions".to_string()), } } } - impl X402DiscoveryResourcesResponsePagination { - pub fn limit(mut self, value: T) -> Self - where - T: ::std::convert::TryInto<::std::option::Option>, - T::Error: ::std::fmt::Display, - { - self.limit = value - .try_into() - .map_err(|e| format!("error converting supplied value for limit: {}", e)); - self - } - pub fn offset(mut self, value: T) -> Self + impl WebhookSubscriptionListResponse { + pub fn next_page_token(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option>, + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, T::Error: ::std::fmt::Display, { - self.offset = value - .try_into() - .map_err(|e| format!("error converting supplied value for offset: {}", e)); + self.next_page_token = value.try_into().map_err(|e| { + format!("error converting supplied value for next_page_token: {}", e) + }); self } - pub fn total(mut self, value: T) -> Self + pub fn subscriptions(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option>, + T: ::std::convert::TryInto<::std::vec::Vec>, T::Error: ::std::fmt::Display, { - self.total = value - .try_into() - .map_err(|e| format!("error converting supplied value for total: {}", e)); + self.subscriptions = value.try_into().map_err(|e| { + format!("error converting supplied value for subscriptions: {}", e) + }); self } } - impl ::std::convert::TryFrom - for super::X402DiscoveryResourcesResponsePagination + impl ::std::convert::TryFrom + for super::WebhookSubscriptionListResponse { type Error = super::error::ConversionError; fn try_from( - value: X402DiscoveryResourcesResponsePagination, + value: WebhookSubscriptionListResponse, ) -> ::std::result::Result { Ok(Self { - limit: value.limit?, - offset: value.offset?, - total: value.total?, + next_page_token: value.next_page_token?, + subscriptions: value.subscriptions?, }) } } - impl ::std::convert::From - for X402DiscoveryResourcesResponsePagination + impl ::std::convert::From + for WebhookSubscriptionListResponse { - fn from(value: super::X402DiscoveryResourcesResponsePagination) -> Self { + fn from(value: super::WebhookSubscriptionListResponse) -> Self { Self { - limit: Ok(value.limit), - offset: Ok(value.offset), - total: Ok(value.total), + next_page_token: Ok(value.next_page_token), + subscriptions: Ok(value.subscriptions), } } } #[derive(Clone, Debug)] - pub struct X402ExactEvmPayload { - authorization: ::std::result::Result< - super::X402ExactEvmPayloadAuthorization, + pub struct WebhookSubscriptionRequest { + description: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, - signature: - ::std::result::Result, + event_types: ::std::result::Result< + ::std::vec::Vec<::std::string::String>, + ::std::string::String, + >, + is_enabled: ::std::result::Result, + labels: ::std::result::Result< + ::std::collections::HashMap<::std::string::String, ::std::string::String>, + ::std::string::String, + >, + metadata: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + target: ::std::result::Result, } - impl ::std::default::Default for X402ExactEvmPayload { + impl ::std::default::Default for WebhookSubscriptionRequest { fn default() -> Self { Self { - authorization: Err("no value supplied for authorization".to_string()), - signature: Err("no value supplied for signature".to_string()), + description: Ok(Default::default()), + event_types: Err("no value supplied for event_types".to_string()), + is_enabled: Err("no value supplied for is_enabled".to_string()), + labels: Ok(Default::default()), + metadata: Ok(Default::default()), + target: Err("no value supplied for target".to_string()), } } } - impl X402ExactEvmPayload { - pub fn authorization(mut self, value: T) -> Self + impl WebhookSubscriptionRequest { + pub fn description(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.authorization = value.try_into().map_err(|e| { - format!("error converting supplied value for authorization: {}", e) - }); + self.description = value + .try_into() + .map_err(|e| format!("error converting supplied value for description: {}", e)); self } - pub fn signature(mut self, value: T) -> Self + pub fn event_types(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::vec::Vec<::std::string::String>>, T::Error: ::std::fmt::Display, { - self.signature = value + self.event_types = value .try_into() - .map_err(|e| format!("error converting supplied value for signature: {}", e)); + .map_err(|e| format!("error converting supplied value for event_types: {}", e)); + self + } + pub fn is_enabled(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.is_enabled = value + .try_into() + .map_err(|e| format!("error converting supplied value for is_enabled: {}", e)); + self + } + pub fn labels(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + ::std::collections::HashMap<::std::string::String, ::std::string::String>, + >, + T::Error: ::std::fmt::Display, + { + self.labels = value + .try_into() + .map_err(|e| format!("error converting supplied value for labels: {}", e)); + self + } + pub fn metadata(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.metadata = value + .try_into() + .map_err(|e| format!("error converting supplied value for metadata: {}", e)); + self + } + pub fn target(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.target = value + .try_into() + .map_err(|e| format!("error converting supplied value for target: {}", e)); self } } - impl ::std::convert::TryFrom for super::X402ExactEvmPayload { + impl ::std::convert::TryFrom for super::WebhookSubscriptionRequest { type Error = super::error::ConversionError; fn try_from( - value: X402ExactEvmPayload, + value: WebhookSubscriptionRequest, ) -> ::std::result::Result { Ok(Self { - authorization: value.authorization?, - signature: value.signature?, + description: value.description?, + event_types: value.event_types?, + is_enabled: value.is_enabled?, + labels: value.labels?, + metadata: value.metadata?, + target: value.target?, }) } } - impl ::std::convert::From for X402ExactEvmPayload { - fn from(value: super::X402ExactEvmPayload) -> Self { + impl ::std::convert::From for WebhookSubscriptionRequest { + fn from(value: super::WebhookSubscriptionRequest) -> Self { Self { - authorization: Ok(value.authorization), - signature: Ok(value.signature), + description: Ok(value.description), + event_types: Ok(value.event_types), + is_enabled: Ok(value.is_enabled), + labels: Ok(value.labels), + metadata: Ok(value.metadata), + target: Ok(value.target), } } } #[derive(Clone, Debug)] - pub struct X402ExactEvmPayloadAuthorization { - from: ::std::result::Result< - super::X402ExactEvmPayloadAuthorizationFrom, + pub struct WebhookSubscriptionResponse { + created_at: ::std::result::Result< + ::chrono::DateTime<::chrono::offset::Utc>, ::std::string::String, >, - nonce: ::std::result::Result< - super::X402ExactEvmPayloadAuthorizationNonce, + description: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, - to: ::std::result::Result< - super::X402ExactEvmPayloadAuthorizationTo, + event_types: ::std::result::Result< + ::std::vec::Vec<::std::string::String>, + ::std::string::String, + >, + is_enabled: ::std::result::Result, + labels: ::std::result::Result< + ::std::collections::HashMap<::std::string::String, ::std::string::String>, + ::std::string::String, + >, + metadata: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + secret: ::std::result::Result<::uuid::Uuid, ::std::string::String>, + subscription_id: ::std::result::Result<::uuid::Uuid, ::std::string::String>, + target: ::std::result::Result, + updated_at: ::std::result::Result< + ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, ::std::string::String, >, - valid_after: ::std::result::Result<::std::string::String, ::std::string::String>, - valid_before: ::std::result::Result<::std::string::String, ::std::string::String>, - value: ::std::result::Result<::std::string::String, ::std::string::String>, } - impl ::std::default::Default for X402ExactEvmPayloadAuthorization { + impl ::std::default::Default for WebhookSubscriptionResponse { fn default() -> Self { Self { - from: Err("no value supplied for from".to_string()), - nonce: Err("no value supplied for nonce".to_string()), - to: Err("no value supplied for to".to_string()), - valid_after: Err("no value supplied for valid_after".to_string()), - valid_before: Err("no value supplied for valid_before".to_string()), - value: Err("no value supplied for value".to_string()), + created_at: Err("no value supplied for created_at".to_string()), + description: Ok(Default::default()), + event_types: Err("no value supplied for event_types".to_string()), + is_enabled: Err("no value supplied for is_enabled".to_string()), + labels: Ok(Default::default()), + metadata: Ok(Default::default()), + secret: Err("no value supplied for secret".to_string()), + subscription_id: Err("no value supplied for subscription_id".to_string()), + target: Err("no value supplied for target".to_string()), + updated_at: Ok(Default::default()), } } } - impl X402ExactEvmPayloadAuthorization { - pub fn from(mut self, value: T) -> Self + impl WebhookSubscriptionResponse { + pub fn created_at(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, T::Error: ::std::fmt::Display, { - self.from = value + self.created_at = value .try_into() - .map_err(|e| format!("error converting supplied value for from: {}", e)); + .map_err(|e| format!("error converting supplied value for created_at: {}", e)); self } - pub fn nonce(mut self, value: T) -> Self + pub fn description(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.nonce = value + self.description = value .try_into() - .map_err(|e| format!("error converting supplied value for nonce: {}", e)); + .map_err(|e| format!("error converting supplied value for description: {}", e)); self } - pub fn to(mut self, value: T) -> Self + pub fn event_types(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::vec::Vec<::std::string::String>>, T::Error: ::std::fmt::Display, { - self.to = value + self.event_types = value .try_into() - .map_err(|e| format!("error converting supplied value for to: {}", e)); + .map_err(|e| format!("error converting supplied value for event_types: {}", e)); self } - pub fn valid_after(mut self, value: T) -> Self + pub fn is_enabled(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::string::String>, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.valid_after = value + self.is_enabled = value .try_into() - .map_err(|e| format!("error converting supplied value for valid_after: {}", e)); + .map_err(|e| format!("error converting supplied value for is_enabled: {}", e)); self } - pub fn valid_before(mut self, value: T) -> Self + pub fn labels(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::string::String>, + T: ::std::convert::TryInto< + ::std::collections::HashMap<::std::string::String, ::std::string::String>, + >, T::Error: ::std::fmt::Display, { - self.valid_before = value.try_into().map_err(|e| { - format!("error converting supplied value for valid_before: {}", e) + self.labels = value + .try_into() + .map_err(|e| format!("error converting supplied value for labels: {}", e)); + self + } + pub fn metadata(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + ::std::option::Option, + >, + T::Error: ::std::fmt::Display, + { + self.metadata = value + .try_into() + .map_err(|e| format!("error converting supplied value for metadata: {}", e)); + self + } + pub fn secret(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::uuid::Uuid>, + T::Error: ::std::fmt::Display, + { + self.secret = value + .try_into() + .map_err(|e| format!("error converting supplied value for secret: {}", e)); + self + } + pub fn subscription_id(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::uuid::Uuid>, + T::Error: ::std::fmt::Display, + { + self.subscription_id = value.try_into().map_err(|e| { + format!("error converting supplied value for subscription_id: {}", e) }); self } - pub fn value(mut self, value: T) -> Self + pub fn target(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::string::String>, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.value = value + self.target = value .try_into() - .map_err(|e| format!("error converting supplied value for value: {}", e)); + .map_err(|e| format!("error converting supplied value for target: {}", e)); + self + } + pub fn updated_at(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + >, + T::Error: ::std::fmt::Display, + { + self.updated_at = value + .try_into() + .map_err(|e| format!("error converting supplied value for updated_at: {}", e)); self } } - impl ::std::convert::TryFrom - for super::X402ExactEvmPayloadAuthorization - { + impl ::std::convert::TryFrom for super::WebhookSubscriptionResponse { type Error = super::error::ConversionError; fn try_from( - value: X402ExactEvmPayloadAuthorization, + value: WebhookSubscriptionResponse, ) -> ::std::result::Result { Ok(Self { - from: value.from?, - nonce: value.nonce?, - to: value.to?, - valid_after: value.valid_after?, - valid_before: value.valid_before?, - value: value.value?, + created_at: value.created_at?, + description: value.description?, + event_types: value.event_types?, + is_enabled: value.is_enabled?, + labels: value.labels?, + metadata: value.metadata?, + secret: value.secret?, + subscription_id: value.subscription_id?, + target: value.target?, + updated_at: value.updated_at?, }) } } - impl ::std::convert::From - for X402ExactEvmPayloadAuthorization - { - fn from(value: super::X402ExactEvmPayloadAuthorization) -> Self { + impl ::std::convert::From for WebhookSubscriptionResponse { + fn from(value: super::WebhookSubscriptionResponse) -> Self { Self { - from: Ok(value.from), - nonce: Ok(value.nonce), - to: Ok(value.to), - valid_after: Ok(value.valid_after), - valid_before: Ok(value.valid_before), - value: Ok(value.value), + created_at: Ok(value.created_at), + description: Ok(value.description), + event_types: Ok(value.event_types), + is_enabled: Ok(value.is_enabled), + labels: Ok(value.labels), + metadata: Ok(value.metadata), + secret: Ok(value.secret), + subscription_id: Ok(value.subscription_id), + target: Ok(value.target), + updated_at: Ok(value.updated_at), } } } #[derive(Clone, Debug)] - pub struct X402ExactEvmPermit2Payload { - permit2_authorization: ::std::result::Result< - super::X402ExactEvmPermit2PayloadPermit2Authorization, - ::std::string::String, - >, - signature: ::std::result::Result< - super::X402ExactEvmPermit2PayloadSignature, + pub struct WebhookSubscriptionResponseMetadata { + secret: + ::std::result::Result<::std::option::Option<::uuid::Uuid>, ::std::string::String>, + extra: ::std::result::Result< + ::std::collections::HashMap< + ::std::string::String, + super::WebhookSubscriptionResponseMetadataExtraValue, + >, ::std::string::String, >, } - impl ::std::default::Default for X402ExactEvmPermit2Payload { + impl ::std::default::Default for WebhookSubscriptionResponseMetadata { fn default() -> Self { Self { - permit2_authorization: Err( - "no value supplied for permit2_authorization".to_string() - ), - signature: Err("no value supplied for signature".to_string()), + secret: Ok(Default::default()), + extra: Err("no value supplied for extra".to_string()), } } } - impl X402ExactEvmPermit2Payload { - pub fn permit2_authorization(mut self, value: T) -> Self + impl WebhookSubscriptionResponseMetadata { + pub fn secret(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::option::Option<::uuid::Uuid>>, T::Error: ::std::fmt::Display, { - self.permit2_authorization = value.try_into().map_err(|e| { - format!( - "error converting supplied value for permit2_authorization: {}", - e - ) - }); + self.secret = value + .try_into() + .map_err(|e| format!("error converting supplied value for secret: {}", e)); self } - pub fn signature(mut self, value: T) -> Self + pub fn extra(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto< + ::std::collections::HashMap< + ::std::string::String, + super::WebhookSubscriptionResponseMetadataExtraValue, + >, + >, T::Error: ::std::fmt::Display, { - self.signature = value + self.extra = value .try_into() - .map_err(|e| format!("error converting supplied value for signature: {}", e)); + .map_err(|e| format!("error converting supplied value for extra: {}", e)); self } } - impl ::std::convert::TryFrom for super::X402ExactEvmPermit2Payload { + impl ::std::convert::TryFrom + for super::WebhookSubscriptionResponseMetadata + { type Error = super::error::ConversionError; fn try_from( - value: X402ExactEvmPermit2Payload, + value: WebhookSubscriptionResponseMetadata, ) -> ::std::result::Result { Ok(Self { - permit2_authorization: value.permit2_authorization?, - signature: value.signature?, + secret: value.secret?, + extra: value.extra?, }) } } - impl ::std::convert::From for X402ExactEvmPermit2Payload { - fn from(value: super::X402ExactEvmPermit2Payload) -> Self { + impl ::std::convert::From + for WebhookSubscriptionResponseMetadata + { + fn from(value: super::WebhookSubscriptionResponseMetadata) -> Self { Self { - permit2_authorization: Ok(value.permit2_authorization), - signature: Ok(value.signature), + secret: Ok(value.secret), + extra: Ok(value.extra), } } } #[derive(Clone, Debug)] - pub struct X402ExactEvmPermit2PayloadPermit2Authorization { - deadline: ::std::result::Result<::std::string::String, ::std::string::String>, - from: ::std::result::Result< - super::X402ExactEvmPermit2PayloadPermit2AuthorizationFrom, - ::std::string::String, - >, - nonce: ::std::result::Result< - super::X402ExactEvmPermit2PayloadPermit2AuthorizationNonce, + pub struct WebhookSubscriptionUpdateRequest { + description: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, - permitted: ::std::result::Result< - super::X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted, + event_types: ::std::result::Result< + ::std::vec::Vec<::std::string::String>, ::std::string::String, >, - spender: ::std::result::Result< - super::X402ExactEvmPermit2PayloadPermit2AuthorizationSpender, + is_enabled: ::std::result::Result, + labels: ::std::result::Result< + ::std::collections::HashMap<::std::string::String, ::std::string::String>, ::std::string::String, >, - witness: ::std::result::Result< - super::X402ExactEvmPermit2PayloadPermit2AuthorizationWitness, + metadata: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, + target: ::std::result::Result, } - impl ::std::default::Default for X402ExactEvmPermit2PayloadPermit2Authorization { + impl ::std::default::Default for WebhookSubscriptionUpdateRequest { fn default() -> Self { Self { - deadline: Err("no value supplied for deadline".to_string()), - from: Err("no value supplied for from".to_string()), - nonce: Err("no value supplied for nonce".to_string()), - permitted: Err("no value supplied for permitted".to_string()), - spender: Err("no value supplied for spender".to_string()), - witness: Err("no value supplied for witness".to_string()), + description: Ok(Default::default()), + event_types: Err("no value supplied for event_types".to_string()), + is_enabled: Err("no value supplied for is_enabled".to_string()), + labels: Ok(Default::default()), + metadata: Ok(Default::default()), + target: Err("no value supplied for target".to_string()), } } } - impl X402ExactEvmPermit2PayloadPermit2Authorization { - pub fn deadline(mut self, value: T) -> Self + impl WebhookSubscriptionUpdateRequest { + pub fn description(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::string::String>, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.deadline = value + self.description = value .try_into() - .map_err(|e| format!("error converting supplied value for deadline: {}", e)); + .map_err(|e| format!("error converting supplied value for description: {}", e)); self } - pub fn from(mut self, value: T) -> Self + pub fn event_types(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - super::X402ExactEvmPermit2PayloadPermit2AuthorizationFrom, - >, + T: ::std::convert::TryInto<::std::vec::Vec<::std::string::String>>, T::Error: ::std::fmt::Display, { - self.from = value + self.event_types = value .try_into() - .map_err(|e| format!("error converting supplied value for from: {}", e)); + .map_err(|e| format!("error converting supplied value for event_types: {}", e)); self } - pub fn nonce(mut self, value: T) -> Self + pub fn is_enabled(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - super::X402ExactEvmPermit2PayloadPermit2AuthorizationNonce, - >, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.nonce = value + self.is_enabled = value .try_into() - .map_err(|e| format!("error converting supplied value for nonce: {}", e)); + .map_err(|e| format!("error converting supplied value for is_enabled: {}", e)); self } - pub fn permitted(mut self, value: T) -> Self + pub fn labels(mut self, value: T) -> Self where T: ::std::convert::TryInto< - super::X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted, + ::std::collections::HashMap<::std::string::String, ::std::string::String>, >, T::Error: ::std::fmt::Display, { - self.permitted = value + self.labels = value .try_into() - .map_err(|e| format!("error converting supplied value for permitted: {}", e)); + .map_err(|e| format!("error converting supplied value for labels: {}", e)); self } - pub fn spender(mut self, value: T) -> Self + pub fn metadata(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - super::X402ExactEvmPermit2PayloadPermit2AuthorizationSpender, - >, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.spender = value + self.metadata = value .try_into() - .map_err(|e| format!("error converting supplied value for spender: {}", e)); + .map_err(|e| format!("error converting supplied value for metadata: {}", e)); self } - pub fn witness(mut self, value: T) -> Self + pub fn target(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - super::X402ExactEvmPermit2PayloadPermit2AuthorizationWitness, - >, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.witness = value + self.target = value .try_into() - .map_err(|e| format!("error converting supplied value for witness: {}", e)); + .map_err(|e| format!("error converting supplied value for target: {}", e)); self } } - impl ::std::convert::TryFrom - for super::X402ExactEvmPermit2PayloadPermit2Authorization + impl ::std::convert::TryFrom + for super::WebhookSubscriptionUpdateRequest { type Error = super::error::ConversionError; fn try_from( - value: X402ExactEvmPermit2PayloadPermit2Authorization, + value: WebhookSubscriptionUpdateRequest, ) -> ::std::result::Result { Ok(Self { - deadline: value.deadline?, - from: value.from?, - nonce: value.nonce?, - permitted: value.permitted?, - spender: value.spender?, - witness: value.witness?, + description: value.description?, + event_types: value.event_types?, + is_enabled: value.is_enabled?, + labels: value.labels?, + metadata: value.metadata?, + target: value.target?, }) } } - impl ::std::convert::From - for X402ExactEvmPermit2PayloadPermit2Authorization + impl ::std::convert::From + for WebhookSubscriptionUpdateRequest { - fn from(value: super::X402ExactEvmPermit2PayloadPermit2Authorization) -> Self { + fn from(value: super::WebhookSubscriptionUpdateRequest) -> Self { Self { - deadline: Ok(value.deadline), - from: Ok(value.from), - nonce: Ok(value.nonce), - permitted: Ok(value.permitted), - spender: Ok(value.spender), - witness: Ok(value.witness), + description: Ok(value.description), + event_types: Ok(value.event_types), + is_enabled: Ok(value.is_enabled), + labels: Ok(value.labels), + metadata: Ok(value.metadata), + target: Ok(value.target), } } } #[derive(Clone, Debug)] - pub struct X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted { - amount: ::std::result::Result<::std::string::String, ::std::string::String>, - token: ::std::result::Result< - super::X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken, + pub struct WebhookTarget { + headers: ::std::result::Result< + ::std::collections::HashMap<::std::string::String, ::std::string::String>, ::std::string::String, >, + url: ::std::result::Result, } - impl ::std::default::Default for X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted { + impl ::std::default::Default for WebhookTarget { fn default() -> Self { Self { - amount: Err("no value supplied for amount".to_string()), - token: Err("no value supplied for token".to_string()), + headers: Ok(Default::default()), + url: Err("no value supplied for url".to_string()), } } } - impl X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted { - pub fn amount(mut self, value: T) -> Self + impl WebhookTarget { + pub fn headers(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::string::String>, + T: ::std::convert::TryInto< + ::std::collections::HashMap<::std::string::String, ::std::string::String>, + >, T::Error: ::std::fmt::Display, { - self.amount = value + self.headers = value .try_into() - .map_err(|e| format!("error converting supplied value for amount: {}", e)); + .map_err(|e| format!("error converting supplied value for headers: {}", e)); self } - pub fn token(mut self, value: T) -> Self + pub fn url(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - super::X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken, - >, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.token = value + self.url = value .try_into() - .map_err(|e| format!("error converting supplied value for token: {}", e)); + .map_err(|e| format!("error converting supplied value for url: {}", e)); self } } - impl ::std::convert::TryFrom - for super::X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted - { + impl ::std::convert::TryFrom for super::WebhookTarget { type Error = super::error::ConversionError; fn try_from( - value: X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted, + value: WebhookTarget, ) -> ::std::result::Result { Ok(Self { - amount: value.amount?, - token: value.token?, + headers: value.headers?, + url: value.url?, }) } } - impl ::std::convert::From - for X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted - { - fn from(value: super::X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted) -> Self { + impl ::std::convert::From for WebhookTarget { + fn from(value: super::WebhookTarget) -> Self { Self { - amount: Ok(value.amount), - token: Ok(value.token), + headers: Ok(value.headers), + url: Ok(value.url), } } } #[derive(Clone, Debug)] - pub struct X402ExactEvmPermit2PayloadPermit2AuthorizationWitness { - extra: ::std::result::Result< - ::std::option::Option< - super::X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra, - >, + pub struct X402DiscoveryMerchantResponse { + pagination: ::std::result::Result< + super::X402DiscoveryMerchantResponsePagination, ::std::string::String, >, - to: ::std::result::Result< - super::X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo, + pay_to: ::std::result::Result, + resources: ::std::result::Result< + ::std::vec::Vec, ::std::string::String, >, - valid_after: ::std::result::Result<::std::string::String, ::std::string::String>, + x402_version: ::std::result::Result, } - impl ::std::default::Default for X402ExactEvmPermit2PayloadPermit2AuthorizationWitness { + impl ::std::default::Default for X402DiscoveryMerchantResponse { fn default() -> Self { Self { - extra: Ok(Default::default()), - to: Err("no value supplied for to".to_string()), - valid_after: Err("no value supplied for valid_after".to_string()), + pagination: Err("no value supplied for pagination".to_string()), + pay_to: Err("no value supplied for pay_to".to_string()), + resources: Err("no value supplied for resources".to_string()), + x402_version: Err("no value supplied for x402_version".to_string()), } } } - impl X402ExactEvmPermit2PayloadPermit2AuthorizationWitness { - pub fn extra(mut self, value: T) -> Self + impl X402DiscoveryMerchantResponse { + pub fn pagination(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - ::std::option::Option< - super::X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra, - >, - >, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.extra = value + self.pagination = value .try_into() - .map_err(|e| format!("error converting supplied value for extra: {}", e)); + .map_err(|e| format!("error converting supplied value for pagination: {}", e)); self } - pub fn to(mut self, value: T) -> Self + pub fn pay_to(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - super::X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo, - >, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.to = value + self.pay_to = value .try_into() - .map_err(|e| format!("error converting supplied value for to: {}", e)); + .map_err(|e| format!("error converting supplied value for pay_to: {}", e)); self } - pub fn valid_after(mut self, value: T) -> Self + pub fn resources(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::string::String>, + T: ::std::convert::TryInto<::std::vec::Vec>, T::Error: ::std::fmt::Display, { - self.valid_after = value + self.resources = value .try_into() - .map_err(|e| format!("error converting supplied value for valid_after: {}", e)); + .map_err(|e| format!("error converting supplied value for resources: {}", e)); self } - } - impl ::std::convert::TryFrom - for super::X402ExactEvmPermit2PayloadPermit2AuthorizationWitness - { - type Error = super::error::ConversionError; - fn try_from( - value: X402ExactEvmPermit2PayloadPermit2AuthorizationWitness, - ) -> ::std::result::Result { - Ok(Self { - extra: value.extra?, - to: value.to?, - valid_after: value.valid_after?, - }) - } - } - impl ::std::convert::From - for X402ExactEvmPermit2PayloadPermit2AuthorizationWitness - { - fn from(value: super::X402ExactEvmPermit2PayloadPermit2AuthorizationWitness) -> Self { - Self { - extra: Ok(value.extra), - to: Ok(value.to), - valid_after: Ok(value.valid_after), - } - } - } - #[derive(Clone, Debug)] - pub struct X402ExactSolanaPayload { - transaction: ::std::result::Result<::std::string::String, ::std::string::String>, - } - impl ::std::default::Default for X402ExactSolanaPayload { - fn default() -> Self { - Self { - transaction: Err("no value supplied for transaction".to_string()), - } - } - } - impl X402ExactSolanaPayload { - pub fn transaction(mut self, value: T) -> Self + pub fn x402_version(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::string::String>, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.transaction = value - .try_into() - .map_err(|e| format!("error converting supplied value for transaction: {}", e)); + self.x402_version = value.try_into().map_err(|e| { + format!("error converting supplied value for x402_version: {}", e) + }); self } } - impl ::std::convert::TryFrom for super::X402ExactSolanaPayload { + impl ::std::convert::TryFrom + for super::X402DiscoveryMerchantResponse + { type Error = super::error::ConversionError; fn try_from( - value: X402ExactSolanaPayload, + value: X402DiscoveryMerchantResponse, ) -> ::std::result::Result { Ok(Self { - transaction: value.transaction?, + pagination: value.pagination?, + pay_to: value.pay_to?, + resources: value.resources?, + x402_version: value.x402_version?, }) } } - impl ::std::convert::From for X402ExactSolanaPayload { - fn from(value: super::X402ExactSolanaPayload) -> Self { + impl ::std::convert::From for X402DiscoveryMerchantResponse { + fn from(value: super::X402DiscoveryMerchantResponse) -> Self { Self { - transaction: Ok(value.transaction), + pagination: Ok(value.pagination), + pay_to: Ok(value.pay_to), + resources: Ok(value.resources), + x402_version: Ok(value.x402_version), } } } #[derive(Clone, Debug)] - pub struct X402McpError { - code: ::std::result::Result, - data: ::std::result::Result< - ::serde_json::Map<::std::string::String, ::serde_json::Value>, - ::std::string::String, - >, - message: ::std::result::Result<::std::string::String, ::std::string::String>, + pub struct X402DiscoveryMerchantResponsePagination { + limit: ::std::result::Result<::std::option::Option, ::std::string::String>, + offset: ::std::result::Result<::std::option::Option, ::std::string::String>, + total: ::std::result::Result<::std::option::Option, ::std::string::String>, } - impl ::std::default::Default for X402McpError { + impl ::std::default::Default for X402DiscoveryMerchantResponsePagination { fn default() -> Self { Self { - code: Err("no value supplied for code".to_string()), - data: Ok(Default::default()), - message: Err("no value supplied for message".to_string()), + limit: Ok(Default::default()), + offset: Ok(Default::default()), + total: Ok(Default::default()), } } } - impl X402McpError { - pub fn code(mut self, value: T) -> Self + impl X402DiscoveryMerchantResponsePagination { + pub fn limit(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.code = value + self.limit = value .try_into() - .map_err(|e| format!("error converting supplied value for code: {}", e)); + .map_err(|e| format!("error converting supplied value for limit: {}", e)); self } - pub fn data(mut self, value: T) -> Self + pub fn offset(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - ::serde_json::Map<::std::string::String, ::serde_json::Value>, - >, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.data = value + self.offset = value .try_into() - .map_err(|e| format!("error converting supplied value for data: {}", e)); + .map_err(|e| format!("error converting supplied value for offset: {}", e)); self } - pub fn message(mut self, value: T) -> Self + pub fn total(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::string::String>, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.message = value + self.total = value .try_into() - .map_err(|e| format!("error converting supplied value for message: {}", e)); + .map_err(|e| format!("error converting supplied value for total: {}", e)); self } } - impl ::std::convert::TryFrom for super::X402McpError { + impl ::std::convert::TryFrom + for super::X402DiscoveryMerchantResponsePagination + { type Error = super::error::ConversionError; fn try_from( - value: X402McpError, + value: X402DiscoveryMerchantResponsePagination, ) -> ::std::result::Result { Ok(Self { - code: value.code?, - data: value.data?, - message: value.message?, + limit: value.limit?, + offset: value.offset?, + total: value.total?, }) } } - impl ::std::convert::From for X402McpError { - fn from(value: super::X402McpError) -> Self { + impl ::std::convert::From + for X402DiscoveryMerchantResponsePagination + { + fn from(value: super::X402DiscoveryMerchantResponsePagination) -> Self { Self { - code: Ok(value.code), - data: Ok(value.data), - message: Ok(value.message), + limit: Ok(value.limit), + offset: Ok(value.offset), + total: Ok(value.total), } } } #[derive(Clone, Debug)] - pub struct X402McpRequest { - id: ::std::result::Result< - ::std::option::Option, + pub struct X402DiscoveryResource { + accepts: ::std::result::Result< + ::std::vec::Vec, ::std::string::String, >, - jsonrpc: ::std::result::Result, - method: ::std::result::Result<::std::string::String, ::std::string::String>, - params: ::std::result::Result< + description: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + extensions: ::std::result::Result< ::serde_json::Map<::std::string::String, ::serde_json::Value>, ::std::string::String, >, + icon_url: + ::std::result::Result<::std::option::Option, ::std::string::String>, + last_updated: ::std::result::Result< + ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + ::std::string::String, + >, + quality: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + resource: ::std::result::Result<::std::string::String, ::std::string::String>, + service_name: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + tags: ::std::result::Result< + ::std::vec::Vec<::std::string::String>, + ::std::string::String, + >, + type_: ::std::result::Result, + x402_version: ::std::result::Result, } - impl ::std::default::Default for X402McpRequest { + impl ::std::default::Default for X402DiscoveryResource { fn default() -> Self { Self { - id: Ok(Default::default()), - jsonrpc: Err("no value supplied for jsonrpc".to_string()), - method: Err("no value supplied for method".to_string()), - params: Ok(Default::default()), + accepts: Ok(Default::default()), + description: Ok(Default::default()), + extensions: Ok(Default::default()), + icon_url: Ok(Default::default()), + last_updated: Ok(Default::default()), + quality: Ok(Default::default()), + resource: Err("no value supplied for resource".to_string()), + service_name: Ok(Default::default()), + tags: Ok(Default::default()), + type_: Err("no value supplied for type_".to_string()), + x402_version: Err("no value supplied for x402_version".to_string()), } } } - impl X402McpRequest { - pub fn id(mut self, value: T) -> Self + impl X402DiscoveryResource { + pub fn accepts(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option>, + T: ::std::convert::TryInto<::std::vec::Vec>, T::Error: ::std::fmt::Display, { - self.id = value + self.accepts = value .try_into() - .map_err(|e| format!("error converting supplied value for id: {}", e)); + .map_err(|e| format!("error converting supplied value for accepts: {}", e)); self } - pub fn jsonrpc(mut self, value: T) -> Self + pub fn description(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, T::Error: ::std::fmt::Display, { - self.jsonrpc = value + self.description = value .try_into() - .map_err(|e| format!("error converting supplied value for jsonrpc: {}", e)); + .map_err(|e| format!("error converting supplied value for description: {}", e)); self } - pub fn method(mut self, value: T) -> Self + pub fn extensions(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::string::String>, + T: ::std::convert::TryInto< + ::serde_json::Map<::std::string::String, ::serde_json::Value>, + >, T::Error: ::std::fmt::Display, { - self.method = value + self.extensions = value .try_into() - .map_err(|e| format!("error converting supplied value for method: {}", e)); + .map_err(|e| format!("error converting supplied value for extensions: {}", e)); self } - pub fn params(mut self, value: T) -> Self + pub fn icon_url(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - ::serde_json::Map<::std::string::String, ::serde_json::Value>, - >, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.params = value + self.icon_url = value .try_into() - .map_err(|e| format!("error converting supplied value for params: {}", e)); + .map_err(|e| format!("error converting supplied value for icon_url: {}", e)); self } - } - impl ::std::convert::TryFrom for super::X402McpRequest { - type Error = super::error::ConversionError; - fn try_from( - value: X402McpRequest, - ) -> ::std::result::Result { - Ok(Self { - id: value.id?, - jsonrpc: value.jsonrpc?, - method: value.method?, - params: value.params?, - }) - } - } - impl ::std::convert::From for X402McpRequest { - fn from(value: super::X402McpRequest) -> Self { - Self { - id: Ok(value.id), - jsonrpc: Ok(value.jsonrpc), - method: Ok(value.method), - params: Ok(value.params), - } - } - } - #[derive(Clone, Debug)] - pub struct X402McpResponse { - error: ::std::result::Result< - ::std::option::Option, - ::std::string::String, - >, - id: ::std::result::Result< - ::std::option::Option, - ::std::string::String, - >, - jsonrpc: ::std::result::Result, - result: ::std::result::Result< - ::serde_json::Map<::std::string::String, ::serde_json::Value>, - ::std::string::String, - >, - } - impl ::std::default::Default for X402McpResponse { - fn default() -> Self { - Self { - error: Ok(Default::default()), - id: Ok(Default::default()), - jsonrpc: Err("no value supplied for jsonrpc".to_string()), - result: Ok(Default::default()), - } + pub fn last_updated(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + >, + T::Error: ::std::fmt::Display, + { + self.last_updated = value.try_into().map_err(|e| { + format!("error converting supplied value for last_updated: {}", e) + }); + self } - } - impl X402McpResponse { - pub fn error(mut self, value: T) -> Self + pub fn quality(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option>, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.error = value + self.quality = value .try_into() - .map_err(|e| format!("error converting supplied value for error: {}", e)); + .map_err(|e| format!("error converting supplied value for quality: {}", e)); self } - pub fn id(mut self, value: T) -> Self + pub fn resource(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option>, + T: ::std::convert::TryInto<::std::string::String>, T::Error: ::std::fmt::Display, { - self.id = value + self.resource = value .try_into() - .map_err(|e| format!("error converting supplied value for id: {}", e)); + .map_err(|e| format!("error converting supplied value for resource: {}", e)); self } - pub fn jsonrpc(mut self, value: T) -> Self + pub fn service_name(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, T::Error: ::std::fmt::Display, { - self.jsonrpc = value + self.service_name = value.try_into().map_err(|e| { + format!("error converting supplied value for service_name: {}", e) + }); + self + } + pub fn tags(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::vec::Vec<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.tags = value .try_into() - .map_err(|e| format!("error converting supplied value for jsonrpc: {}", e)); + .map_err(|e| format!("error converting supplied value for tags: {}", e)); self } - pub fn result(mut self, value: T) -> Self + pub fn type_(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - ::serde_json::Map<::std::string::String, ::serde_json::Value>, - >, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.result = value + self.type_ = value .try_into() - .map_err(|e| format!("error converting supplied value for result: {}", e)); + .map_err(|e| format!("error converting supplied value for type_: {}", e)); self } - } - impl ::std::convert::TryFrom for super::X402McpResponse { - type Error = super::error::ConversionError; - fn try_from( - value: X402McpResponse, - ) -> ::std::result::Result { + pub fn x402_version(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.x402_version = value.try_into().map_err(|e| { + format!("error converting supplied value for x402_version: {}", e) + }); + self + } + } + impl ::std::convert::TryFrom for super::X402DiscoveryResource { + type Error = super::error::ConversionError; + fn try_from( + value: X402DiscoveryResource, + ) -> ::std::result::Result { Ok(Self { - error: value.error?, - id: value.id?, - jsonrpc: value.jsonrpc?, - result: value.result?, + accepts: value.accepts?, + description: value.description?, + extensions: value.extensions?, + icon_url: value.icon_url?, + last_updated: value.last_updated?, + quality: value.quality?, + resource: value.resource?, + service_name: value.service_name?, + tags: value.tags?, + type_: value.type_?, + x402_version: value.x402_version?, }) } } - impl ::std::convert::From for X402McpResponse { - fn from(value: super::X402McpResponse) -> Self { + impl ::std::convert::From for X402DiscoveryResource { + fn from(value: super::X402DiscoveryResource) -> Self { Self { - error: Ok(value.error), - id: Ok(value.id), - jsonrpc: Ok(value.jsonrpc), - result: Ok(value.result), + accepts: Ok(value.accepts), + description: Ok(value.description), + extensions: Ok(value.extensions), + icon_url: Ok(value.icon_url), + last_updated: Ok(value.last_updated), + quality: Ok(value.quality), + resource: Ok(value.resource), + service_name: Ok(value.service_name), + tags: Ok(value.tags), + type_: Ok(value.type_), + x402_version: Ok(value.x402_version), } } } #[derive(Clone, Debug)] - pub struct X402ResourceInfo { - description: ::std::result::Result< - ::std::option::Option, - ::std::string::String, - >, - mime_type: ::std::result::Result< - ::std::option::Option<::std::string::String>, + pub struct X402DiscoveryResourcesResponse { + items: ::std::result::Result< + ::std::vec::Vec, ::std::string::String, >, - url: ::std::result::Result< - ::std::option::Option<::std::string::String>, + pagination: ::std::result::Result< + super::X402DiscoveryResourcesResponsePagination, ::std::string::String, >, + x402_version: ::std::result::Result, } - impl ::std::default::Default for X402ResourceInfo { + impl ::std::default::Default for X402DiscoveryResourcesResponse { fn default() -> Self { Self { - description: Ok(Default::default()), - mime_type: Ok(Default::default()), - url: Ok(Default::default()), + items: Err("no value supplied for items".to_string()), + pagination: Err("no value supplied for pagination".to_string()), + x402_version: Err("no value supplied for x402_version".to_string()), } } } - impl X402ResourceInfo { - pub fn description(mut self, value: T) -> Self + impl X402DiscoveryResourcesResponse { + pub fn items(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option>, + T: ::std::convert::TryInto<::std::vec::Vec>, T::Error: ::std::fmt::Display, { - self.description = value + self.items = value .try_into() - .map_err(|e| format!("error converting supplied value for description: {}", e)); + .map_err(|e| format!("error converting supplied value for items: {}", e)); self } - pub fn mime_type(mut self, value: T) -> Self + pub fn pagination(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.mime_type = value + self.pagination = value .try_into() - .map_err(|e| format!("error converting supplied value for mime_type: {}", e)); + .map_err(|e| format!("error converting supplied value for pagination: {}", e)); self } - pub fn url(mut self, value: T) -> Self + pub fn x402_version(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.url = value - .try_into() - .map_err(|e| format!("error converting supplied value for url: {}", e)); + self.x402_version = value.try_into().map_err(|e| { + format!("error converting supplied value for x402_version: {}", e) + }); self } } - impl ::std::convert::TryFrom for super::X402ResourceInfo { + impl ::std::convert::TryFrom + for super::X402DiscoveryResourcesResponse + { type Error = super::error::ConversionError; fn try_from( - value: X402ResourceInfo, + value: X402DiscoveryResourcesResponse, ) -> ::std::result::Result { Ok(Self { - description: value.description?, - mime_type: value.mime_type?, - url: value.url?, + items: value.items?, + pagination: value.pagination?, + x402_version: value.x402_version?, }) } } - impl ::std::convert::From for X402ResourceInfo { - fn from(value: super::X402ResourceInfo) -> Self { + impl ::std::convert::From + for X402DiscoveryResourcesResponse + { + fn from(value: super::X402DiscoveryResourcesResponse) -> Self { Self { - description: Ok(value.description), - mime_type: Ok(value.mime_type), - url: Ok(value.url), + items: Ok(value.items), + pagination: Ok(value.pagination), + x402_version: Ok(value.x402_version), } } } #[derive(Clone, Debug)] - pub struct X402ResourceQuality { - l30_days_total_calls: - ::std::result::Result<::std::option::Option, ::std::string::String>, - l30_days_unique_payers: - ::std::result::Result<::std::option::Option, ::std::string::String>, - last_called_at: ::std::result::Result< - ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, - ::std::string::String, - >, + pub struct X402DiscoveryResourcesResponsePagination { + limit: ::std::result::Result<::std::option::Option, ::std::string::String>, + offset: ::std::result::Result<::std::option::Option, ::std::string::String>, + total: ::std::result::Result<::std::option::Option, ::std::string::String>, } - impl ::std::default::Default for X402ResourceQuality { + impl ::std::default::Default for X402DiscoveryResourcesResponsePagination { fn default() -> Self { Self { - l30_days_total_calls: Ok(Default::default()), - l30_days_unique_payers: Ok(Default::default()), - last_called_at: Ok(Default::default()), + limit: Ok(Default::default()), + offset: Ok(Default::default()), + total: Ok(Default::default()), } } } - impl X402ResourceQuality { - pub fn l30_days_total_calls(mut self, value: T) -> Self + impl X402DiscoveryResourcesResponsePagination { + pub fn limit(mut self, value: T) -> Self where T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.l30_days_total_calls = value.try_into().map_err(|e| { - format!( - "error converting supplied value for l30_days_total_calls: {}", - e - ) - }); + self.limit = value + .try_into() + .map_err(|e| format!("error converting supplied value for limit: {}", e)); self } - pub fn l30_days_unique_payers(mut self, value: T) -> Self + pub fn offset(mut self, value: T) -> Self where T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.l30_days_unique_payers = value.try_into().map_err(|e| { - format!( - "error converting supplied value for l30_days_unique_payers: {}", - e - ) - }); + self.offset = value + .try_into() + .map_err(|e| format!("error converting supplied value for offset: {}", e)); self } - pub fn last_called_at(mut self, value: T) -> Self + pub fn total(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, - >, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.last_called_at = value.try_into().map_err(|e| { - format!("error converting supplied value for last_called_at: {}", e) - }); + self.total = value + .try_into() + .map_err(|e| format!("error converting supplied value for total: {}", e)); self } } - impl ::std::convert::TryFrom for super::X402ResourceQuality { + impl ::std::convert::TryFrom + for super::X402DiscoveryResourcesResponsePagination + { type Error = super::error::ConversionError; fn try_from( - value: X402ResourceQuality, + value: X402DiscoveryResourcesResponsePagination, ) -> ::std::result::Result { Ok(Self { - l30_days_total_calls: value.l30_days_total_calls?, - l30_days_unique_payers: value.l30_days_unique_payers?, - last_called_at: value.last_called_at?, + limit: value.limit?, + offset: value.offset?, + total: value.total?, }) } } - impl ::std::convert::From for X402ResourceQuality { - fn from(value: super::X402ResourceQuality) -> Self { + impl ::std::convert::From + for X402DiscoveryResourcesResponsePagination + { + fn from(value: super::X402DiscoveryResourcesResponsePagination) -> Self { Self { - l30_days_total_calls: Ok(value.l30_days_total_calls), - l30_days_unique_payers: Ok(value.l30_days_unique_payers), - last_called_at: Ok(value.last_called_at), + limit: Ok(value.limit), + offset: Ok(value.offset), + total: Ok(value.total), } } } #[derive(Clone, Debug)] - pub struct X402SearchResourcesResponse { - partial_results: ::std::result::Result, - resources: ::std::result::Result< - ::std::vec::Vec, - ::std::string::String, - >, - search_method: ::std::result::Result< - ::std::option::Option, + pub struct X402ExactEvmPayload { + authorization: ::std::result::Result< + super::X402ExactEvmPayloadAuthorization, ::std::string::String, >, - x402_version: ::std::result::Result, + signature: + ::std::result::Result, } - impl ::std::default::Default for X402SearchResourcesResponse { + impl ::std::default::Default for X402ExactEvmPayload { fn default() -> Self { Self { - partial_results: Err("no value supplied for partial_results".to_string()), - resources: Err("no value supplied for resources".to_string()), - search_method: Ok(Default::default()), - x402_version: Err("no value supplied for x402_version".to_string()), + authorization: Err("no value supplied for authorization".to_string()), + signature: Err("no value supplied for signature".to_string()), } } } - impl X402SearchResourcesResponse { - pub fn partial_results(mut self, value: T) -> Self + impl X402ExactEvmPayload { + pub fn authorization(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.partial_results = value.try_into().map_err(|e| { - format!("error converting supplied value for partial_results: {}", e) + self.authorization = value.try_into().map_err(|e| { + format!("error converting supplied value for authorization: {}", e) }); self } - pub fn resources(mut self, value: T) -> Self + pub fn signature(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::vec::Vec>, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.resources = value + self.signature = value .try_into() - .map_err(|e| format!("error converting supplied value for resources: {}", e)); - self - } - pub fn search_method(mut self, value: T) -> Self - where - T: ::std::convert::TryInto< - ::std::option::Option, - >, - T::Error: ::std::fmt::Display, - { - self.search_method = value.try_into().map_err(|e| { - format!("error converting supplied value for search_method: {}", e) - }); - self - } - pub fn x402_version(mut self, value: T) -> Self - where - T: ::std::convert::TryInto, - T::Error: ::std::fmt::Display, - { - self.x402_version = value.try_into().map_err(|e| { - format!("error converting supplied value for x402_version: {}", e) - }); + .map_err(|e| format!("error converting supplied value for signature: {}", e)); self } } - impl ::std::convert::TryFrom for super::X402SearchResourcesResponse { + impl ::std::convert::TryFrom for super::X402ExactEvmPayload { type Error = super::error::ConversionError; fn try_from( - value: X402SearchResourcesResponse, + value: X402ExactEvmPayload, ) -> ::std::result::Result { Ok(Self { - partial_results: value.partial_results?, - resources: value.resources?, - search_method: value.search_method?, - x402_version: value.x402_version?, + authorization: value.authorization?, + signature: value.signature?, }) } } - impl ::std::convert::From for X402SearchResourcesResponse { - fn from(value: super::X402SearchResourcesResponse) -> Self { + impl ::std::convert::From for X402ExactEvmPayload { + fn from(value: super::X402ExactEvmPayload) -> Self { Self { - partial_results: Ok(value.partial_results), - resources: Ok(value.resources), - search_method: Ok(value.search_method), - x402_version: Ok(value.x402_version), + authorization: Ok(value.authorization), + signature: Ok(value.signature), } } } #[derive(Clone, Debug)] - pub struct X402SettlePaymentRejection { - error_message: ::std::result::Result< - ::std::option::Option<::std::string::String>, - ::std::string::String, - >, - error_reason: - ::std::result::Result, - network: ::std::result::Result< - ::std::option::Option<::std::string::String>, + pub struct X402ExactEvmPayloadAuthorization { + from: ::std::result::Result< + super::X402ExactEvmPayloadAuthorizationFrom, ::std::string::String, >, - payer: ::std::result::Result< - ::std::option::Option, + nonce: ::std::result::Result< + super::X402ExactEvmPayloadAuthorizationNonce, ::std::string::String, >, - success: ::std::result::Result, - transaction: ::std::result::Result< - ::std::option::Option, + to: ::std::result::Result< + super::X402ExactEvmPayloadAuthorizationTo, ::std::string::String, >, + valid_after: ::std::result::Result<::std::string::String, ::std::string::String>, + valid_before: ::std::result::Result<::std::string::String, ::std::string::String>, + value: ::std::result::Result<::std::string::String, ::std::string::String>, } - impl ::std::default::Default for X402SettlePaymentRejection { + impl ::std::default::Default for X402ExactEvmPayloadAuthorization { fn default() -> Self { Self { - error_message: Ok(Default::default()), - error_reason: Err("no value supplied for error_reason".to_string()), - network: Ok(Default::default()), - payer: Ok(Default::default()), - success: Err("no value supplied for success".to_string()), - transaction: Ok(Default::default()), + from: Err("no value supplied for from".to_string()), + nonce: Err("no value supplied for nonce".to_string()), + to: Err("no value supplied for to".to_string()), + valid_after: Err("no value supplied for valid_after".to_string()), + valid_before: Err("no value supplied for valid_before".to_string()), + value: Err("no value supplied for value".to_string()), } } } - impl X402SettlePaymentRejection { - pub fn error_message(mut self, value: T) -> Self + impl X402ExactEvmPayloadAuthorization { + pub fn from(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.error_message = value.try_into().map_err(|e| { - format!("error converting supplied value for error_message: {}", e) - }); + self.from = value + .try_into() + .map_err(|e| format!("error converting supplied value for from: {}", e)); self } - pub fn error_reason(mut self, value: T) -> Self + pub fn nonce(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.error_reason = value.try_into().map_err(|e| { - format!("error converting supplied value for error_reason: {}", e) - }); + self.nonce = value + .try_into() + .map_err(|e| format!("error converting supplied value for nonce: {}", e)); self } - pub fn network(mut self, value: T) -> Self + pub fn to(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.network = value + self.to = value .try_into() - .map_err(|e| format!("error converting supplied value for network: {}", e)); + .map_err(|e| format!("error converting supplied value for to: {}", e)); self } - pub fn payer(mut self, value: T) -> Self + pub fn valid_after(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - ::std::option::Option, - >, + T: ::std::convert::TryInto<::std::string::String>, T::Error: ::std::fmt::Display, { - self.payer = value + self.valid_after = value .try_into() - .map_err(|e| format!("error converting supplied value for payer: {}", e)); + .map_err(|e| format!("error converting supplied value for valid_after: {}", e)); self } - pub fn success(mut self, value: T) -> Self + pub fn valid_before(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::string::String>, T::Error: ::std::fmt::Display, { - self.success = value - .try_into() - .map_err(|e| format!("error converting supplied value for success: {}", e)); + self.valid_before = value.try_into().map_err(|e| { + format!("error converting supplied value for valid_before: {}", e) + }); self } - pub fn transaction(mut self, value: T) -> Self + pub fn value(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - ::std::option::Option, - >, + T: ::std::convert::TryInto<::std::string::String>, T::Error: ::std::fmt::Display, { - self.transaction = value + self.value = value .try_into() - .map_err(|e| format!("error converting supplied value for transaction: {}", e)); + .map_err(|e| format!("error converting supplied value for value: {}", e)); self } } - impl ::std::convert::TryFrom for super::X402SettlePaymentRejection { + impl ::std::convert::TryFrom + for super::X402ExactEvmPayloadAuthorization + { type Error = super::error::ConversionError; fn try_from( - value: X402SettlePaymentRejection, + value: X402ExactEvmPayloadAuthorization, ) -> ::std::result::Result { Ok(Self { - error_message: value.error_message?, - error_reason: value.error_reason?, - network: value.network?, - payer: value.payer?, - success: value.success?, - transaction: value.transaction?, + from: value.from?, + nonce: value.nonce?, + to: value.to?, + valid_after: value.valid_after?, + valid_before: value.valid_before?, + value: value.value?, }) } } - impl ::std::convert::From for X402SettlePaymentRejection { - fn from(value: super::X402SettlePaymentRejection) -> Self { + impl ::std::convert::From + for X402ExactEvmPayloadAuthorization + { + fn from(value: super::X402ExactEvmPayloadAuthorization) -> Self { Self { - error_message: Ok(value.error_message), - error_reason: Ok(value.error_reason), - network: Ok(value.network), - payer: Ok(value.payer), - success: Ok(value.success), - transaction: Ok(value.transaction), + from: Ok(value.from), + nonce: Ok(value.nonce), + to: Ok(value.to), + valid_after: Ok(value.valid_after), + valid_before: Ok(value.valid_before), + value: Ok(value.value), } } } #[derive(Clone, Debug)] - pub struct X402SupportedPaymentKind { - extra: ::std::result::Result< - ::serde_json::Map<::std::string::String, ::serde_json::Value>, + pub struct X402ExactEvmPermit2Payload { + permit2_authorization: ::std::result::Result< + super::X402ExactEvmPermit2PayloadPermit2Authorization, ::std::string::String, >, - network: ::std::result::Result< - super::X402SupportedPaymentKindNetwork, + signature: ::std::result::Result< + super::X402ExactEvmPermit2PayloadSignature, ::std::string::String, >, - scheme: - ::std::result::Result, - x402_version: ::std::result::Result, } - impl ::std::default::Default for X402SupportedPaymentKind { + impl ::std::default::Default for X402ExactEvmPermit2Payload { fn default() -> Self { Self { - extra: Ok(Default::default()), - network: Err("no value supplied for network".to_string()), - scheme: Err("no value supplied for scheme".to_string()), - x402_version: Err("no value supplied for x402_version".to_string()), + permit2_authorization: Err( + "no value supplied for permit2_authorization".to_string() + ), + signature: Err("no value supplied for signature".to_string()), } } } - impl X402SupportedPaymentKind { - pub fn extra(mut self, value: T) -> Self - where - T: ::std::convert::TryInto< - ::serde_json::Map<::std::string::String, ::serde_json::Value>, - >, - T::Error: ::std::fmt::Display, - { - self.extra = value - .try_into() - .map_err(|e| format!("error converting supplied value for extra: {}", e)); - self - } - pub fn network(mut self, value: T) -> Self + impl X402ExactEvmPermit2Payload { + pub fn permit2_authorization(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.network = value - .try_into() - .map_err(|e| format!("error converting supplied value for network: {}", e)); + self.permit2_authorization = value.try_into().map_err(|e| { + format!( + "error converting supplied value for permit2_authorization: {}", + e + ) + }); self } - pub fn scheme(mut self, value: T) -> Self + pub fn signature(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.scheme = value + self.signature = value .try_into() - .map_err(|e| format!("error converting supplied value for scheme: {}", e)); - self - } - pub fn x402_version(mut self, value: T) -> Self - where - T: ::std::convert::TryInto, - T::Error: ::std::fmt::Display, - { - self.x402_version = value.try_into().map_err(|e| { - format!("error converting supplied value for x402_version: {}", e) - }); + .map_err(|e| format!("error converting supplied value for signature: {}", e)); self } } - impl ::std::convert::TryFrom for super::X402SupportedPaymentKind { + impl ::std::convert::TryFrom for super::X402ExactEvmPermit2Payload { type Error = super::error::ConversionError; fn try_from( - value: X402SupportedPaymentKind, + value: X402ExactEvmPermit2Payload, ) -> ::std::result::Result { Ok(Self { - extra: value.extra?, - network: value.network?, - scheme: value.scheme?, - x402_version: value.x402_version?, + permit2_authorization: value.permit2_authorization?, + signature: value.signature?, }) } } - impl ::std::convert::From for X402SupportedPaymentKind { - fn from(value: super::X402SupportedPaymentKind) -> Self { + impl ::std::convert::From for X402ExactEvmPermit2Payload { + fn from(value: super::X402ExactEvmPermit2Payload) -> Self { Self { - extra: Ok(value.extra), - network: Ok(value.network), - scheme: Ok(value.scheme), - x402_version: Ok(value.x402_version), + permit2_authorization: Ok(value.permit2_authorization), + signature: Ok(value.signature), } } } #[derive(Clone, Debug)] - pub struct X402V1PaymentPayload { - network: - ::std::result::Result, - payload: - ::std::result::Result, - scheme: ::std::result::Result, - x402_version: ::std::result::Result, - } - impl ::std::default::Default for X402V1PaymentPayload { + pub struct X402ExactEvmPermit2PayloadPermit2Authorization { + deadline: ::std::result::Result<::std::string::String, ::std::string::String>, + from: ::std::result::Result< + super::X402ExactEvmPermit2PayloadPermit2AuthorizationFrom, + ::std::string::String, + >, + nonce: ::std::result::Result< + super::X402ExactEvmPermit2PayloadPermit2AuthorizationNonce, + ::std::string::String, + >, + permitted: ::std::result::Result< + super::X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted, + ::std::string::String, + >, + spender: ::std::result::Result< + super::X402ExactEvmPermit2PayloadPermit2AuthorizationSpender, + ::std::string::String, + >, + witness: ::std::result::Result< + super::X402ExactEvmPermit2PayloadPermit2AuthorizationWitness, + ::std::string::String, + >, + } + impl ::std::default::Default for X402ExactEvmPermit2PayloadPermit2Authorization { fn default() -> Self { Self { - network: Err("no value supplied for network".to_string()), - payload: Err("no value supplied for payload".to_string()), - scheme: Err("no value supplied for scheme".to_string()), - x402_version: Err("no value supplied for x402_version".to_string()), + deadline: Err("no value supplied for deadline".to_string()), + from: Err("no value supplied for from".to_string()), + nonce: Err("no value supplied for nonce".to_string()), + permitted: Err("no value supplied for permitted".to_string()), + spender: Err("no value supplied for spender".to_string()), + witness: Err("no value supplied for witness".to_string()), } } } - impl X402V1PaymentPayload { - pub fn network(mut self, value: T) -> Self + impl X402ExactEvmPermit2PayloadPermit2Authorization { + pub fn deadline(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::string::String>, T::Error: ::std::fmt::Display, { - self.network = value + self.deadline = value .try_into() - .map_err(|e| format!("error converting supplied value for network: {}", e)); + .map_err(|e| format!("error converting supplied value for deadline: {}", e)); self } - pub fn payload(mut self, value: T) -> Self + pub fn from(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto< + super::X402ExactEvmPermit2PayloadPermit2AuthorizationFrom, + >, T::Error: ::std::fmt::Display, { - self.payload = value + self.from = value .try_into() - .map_err(|e| format!("error converting supplied value for payload: {}", e)); + .map_err(|e| format!("error converting supplied value for from: {}", e)); self } - pub fn scheme(mut self, value: T) -> Self + pub fn nonce(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto< + super::X402ExactEvmPermit2PayloadPermit2AuthorizationNonce, + >, T::Error: ::std::fmt::Display, { - self.scheme = value + self.nonce = value .try_into() - .map_err(|e| format!("error converting supplied value for scheme: {}", e)); + .map_err(|e| format!("error converting supplied value for nonce: {}", e)); self } - pub fn x402_version(mut self, value: T) -> Self + pub fn permitted(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto< + super::X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted, + >, T::Error: ::std::fmt::Display, { - self.x402_version = value.try_into().map_err(|e| { - format!("error converting supplied value for x402_version: {}", e) - }); + self.permitted = value + .try_into() + .map_err(|e| format!("error converting supplied value for permitted: {}", e)); + self + } + pub fn spender(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + super::X402ExactEvmPermit2PayloadPermit2AuthorizationSpender, + >, + T::Error: ::std::fmt::Display, + { + self.spender = value + .try_into() + .map_err(|e| format!("error converting supplied value for spender: {}", e)); + self + } + pub fn witness(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + super::X402ExactEvmPermit2PayloadPermit2AuthorizationWitness, + >, + T::Error: ::std::fmt::Display, + { + self.witness = value + .try_into() + .map_err(|e| format!("error converting supplied value for witness: {}", e)); self } } - impl ::std::convert::TryFrom for super::X402V1PaymentPayload { + impl ::std::convert::TryFrom + for super::X402ExactEvmPermit2PayloadPermit2Authorization + { type Error = super::error::ConversionError; fn try_from( - value: X402V1PaymentPayload, + value: X402ExactEvmPermit2PayloadPermit2Authorization, ) -> ::std::result::Result { Ok(Self { - network: value.network?, - payload: value.payload?, - scheme: value.scheme?, - x402_version: value.x402_version?, + deadline: value.deadline?, + from: value.from?, + nonce: value.nonce?, + permitted: value.permitted?, + spender: value.spender?, + witness: value.witness?, }) } } - impl ::std::convert::From for X402V1PaymentPayload { - fn from(value: super::X402V1PaymentPayload) -> Self { + impl ::std::convert::From + for X402ExactEvmPermit2PayloadPermit2Authorization + { + fn from(value: super::X402ExactEvmPermit2PayloadPermit2Authorization) -> Self { Self { - network: Ok(value.network), - payload: Ok(value.payload), - scheme: Ok(value.scheme), - x402_version: Ok(value.x402_version), + deadline: Ok(value.deadline), + from: Ok(value.from), + nonce: Ok(value.nonce), + permitted: Ok(value.permitted), + spender: Ok(value.spender), + witness: Ok(value.witness), } } } #[derive(Clone, Debug)] - pub struct X402V1PaymentRequirements { - asset: - ::std::result::Result, - description: ::std::result::Result, - extra: ::std::result::Result< - ::serde_json::Map<::std::string::String, ::serde_json::Value>, - ::std::string::String, - >, - max_amount_required: - ::std::result::Result<::std::string::String, ::std::string::String>, - max_timeout_seconds: ::std::result::Result, - mime_type: ::std::result::Result<::std::string::String, ::std::string::String>, - network: ::std::result::Result< - super::X402v1PaymentRequirementsNetwork, - ::std::string::String, - >, - output_schema: ::std::result::Result< - ::serde_json::Map<::std::string::String, ::serde_json::Value>, - ::std::string::String, - >, - pay_to: - ::std::result::Result, - resource: ::std::result::Result<::std::string::String, ::std::string::String>, - scheme: ::std::result::Result< - super::X402v1PaymentRequirementsScheme, + pub struct X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted { + amount: ::std::result::Result<::std::string::String, ::std::string::String>, + token: ::std::result::Result< + super::X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken, ::std::string::String, >, } - impl ::std::default::Default for X402V1PaymentRequirements { + impl ::std::default::Default for X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted { fn default() -> Self { Self { - asset: Err("no value supplied for asset".to_string()), - description: Err("no value supplied for description".to_string()), - extra: Ok(Default::default()), - max_amount_required: Err( - "no value supplied for max_amount_required".to_string() - ), - max_timeout_seconds: Err( - "no value supplied for max_timeout_seconds".to_string() - ), - mime_type: Err("no value supplied for mime_type".to_string()), - network: Err("no value supplied for network".to_string()), - output_schema: Ok(Default::default()), - pay_to: Err("no value supplied for pay_to".to_string()), - resource: Err("no value supplied for resource".to_string()), - scheme: Err("no value supplied for scheme".to_string()), + amount: Err("no value supplied for amount".to_string()), + token: Err("no value supplied for token".to_string()), } } } - impl X402V1PaymentRequirements { - pub fn asset(mut self, value: T) -> Self + impl X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted { + pub fn amount(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::string::String>, T::Error: ::std::fmt::Display, { - self.asset = value + self.amount = value .try_into() - .map_err(|e| format!("error converting supplied value for asset: {}", e)); + .map_err(|e| format!("error converting supplied value for amount: {}", e)); self } - pub fn description(mut self, value: T) -> Self + pub fn token(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto< + super::X402ExactEvmPermit2PayloadPermit2AuthorizationPermittedToken, + >, T::Error: ::std::fmt::Display, { - self.description = value + self.token = value .try_into() - .map_err(|e| format!("error converting supplied value for description: {}", e)); + .map_err(|e| format!("error converting supplied value for token: {}", e)); self } + } + impl ::std::convert::TryFrom + for super::X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted + { + type Error = super::error::ConversionError; + fn try_from( + value: X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted, + ) -> ::std::result::Result { + Ok(Self { + amount: value.amount?, + token: value.token?, + }) + } + } + impl ::std::convert::From + for X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted + { + fn from(value: super::X402ExactEvmPermit2PayloadPermit2AuthorizationPermitted) -> Self { + Self { + amount: Ok(value.amount), + token: Ok(value.token), + } + } + } + #[derive(Clone, Debug)] + pub struct X402ExactEvmPermit2PayloadPermit2AuthorizationWitness { + extra: ::std::result::Result< + ::std::option::Option< + super::X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra, + >, + ::std::string::String, + >, + to: ::std::result::Result< + super::X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo, + ::std::string::String, + >, + valid_after: ::std::result::Result<::std::string::String, ::std::string::String>, + } + impl ::std::default::Default for X402ExactEvmPermit2PayloadPermit2AuthorizationWitness { + fn default() -> Self { + Self { + extra: Ok(Default::default()), + to: Err("no value supplied for to".to_string()), + valid_after: Err("no value supplied for valid_after".to_string()), + } + } + } + impl X402ExactEvmPermit2PayloadPermit2AuthorizationWitness { pub fn extra(mut self, value: T) -> Self where T: ::std::convert::TryInto< - ::serde_json::Map<::std::string::String, ::serde_json::Value>, + ::std::option::Option< + super::X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessExtra, + >, >, T::Error: ::std::fmt::Display, { @@ -81708,436 +92670,667 @@ pub mod types { .map_err(|e| format!("error converting supplied value for extra: {}", e)); self } - pub fn max_amount_required(mut self, value: T) -> Self + pub fn to(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::string::String>, + T: ::std::convert::TryInto< + super::X402ExactEvmPermit2PayloadPermit2AuthorizationWitnessTo, + >, T::Error: ::std::fmt::Display, { - self.max_amount_required = value.try_into().map_err(|e| { - format!( - "error converting supplied value for max_amount_required: {}", - e - ) - }); + self.to = value + .try_into() + .map_err(|e| format!("error converting supplied value for to: {}", e)); self } - pub fn max_timeout_seconds(mut self, value: T) -> Self + pub fn valid_after(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::string::String>, T::Error: ::std::fmt::Display, { - self.max_timeout_seconds = value.try_into().map_err(|e| { - format!( - "error converting supplied value for max_timeout_seconds: {}", - e - ) - }); + self.valid_after = value + .try_into() + .map_err(|e| format!("error converting supplied value for valid_after: {}", e)); self } - pub fn mime_type(mut self, value: T) -> Self + } + impl ::std::convert::TryFrom + for super::X402ExactEvmPermit2PayloadPermit2AuthorizationWitness + { + type Error = super::error::ConversionError; + fn try_from( + value: X402ExactEvmPermit2PayloadPermit2AuthorizationWitness, + ) -> ::std::result::Result { + Ok(Self { + extra: value.extra?, + to: value.to?, + valid_after: value.valid_after?, + }) + } + } + impl ::std::convert::From + for X402ExactEvmPermit2PayloadPermit2AuthorizationWitness + { + fn from(value: super::X402ExactEvmPermit2PayloadPermit2AuthorizationWitness) -> Self { + Self { + extra: Ok(value.extra), + to: Ok(value.to), + valid_after: Ok(value.valid_after), + } + } + } + #[derive(Clone, Debug)] + pub struct X402ExactSolanaPayload { + transaction: ::std::result::Result<::std::string::String, ::std::string::String>, + } + impl ::std::default::Default for X402ExactSolanaPayload { + fn default() -> Self { + Self { + transaction: Err("no value supplied for transaction".to_string()), + } + } + } + impl X402ExactSolanaPayload { + pub fn transaction(mut self, value: T) -> Self where T: ::std::convert::TryInto<::std::string::String>, T::Error: ::std::fmt::Display, { - self.mime_type = value + self.transaction = value .try_into() - .map_err(|e| format!("error converting supplied value for mime_type: {}", e)); + .map_err(|e| format!("error converting supplied value for transaction: {}", e)); self } - pub fn network(mut self, value: T) -> Self + } + impl ::std::convert::TryFrom for super::X402ExactSolanaPayload { + type Error = super::error::ConversionError; + fn try_from( + value: X402ExactSolanaPayload, + ) -> ::std::result::Result { + Ok(Self { + transaction: value.transaction?, + }) + } + } + impl ::std::convert::From for X402ExactSolanaPayload { + fn from(value: super::X402ExactSolanaPayload) -> Self { + Self { + transaction: Ok(value.transaction), + } + } + } + #[derive(Clone, Debug)] + pub struct X402McpError { + code: ::std::result::Result, + data: ::std::result::Result< + ::serde_json::Map<::std::string::String, ::serde_json::Value>, + ::std::string::String, + >, + message: ::std::result::Result<::std::string::String, ::std::string::String>, + } + impl ::std::default::Default for X402McpError { + fn default() -> Self { + Self { + code: Err("no value supplied for code".to_string()), + data: Ok(Default::default()), + message: Err("no value supplied for message".to_string()), + } + } + } + impl X402McpError { + pub fn code(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.network = value + self.code = value .try_into() - .map_err(|e| format!("error converting supplied value for network: {}", e)); + .map_err(|e| format!("error converting supplied value for code: {}", e)); self } - pub fn output_schema(mut self, value: T) -> Self + pub fn data(mut self, value: T) -> Self where T: ::std::convert::TryInto< ::serde_json::Map<::std::string::String, ::serde_json::Value>, >, T::Error: ::std::fmt::Display, { - self.output_schema = value.try_into().map_err(|e| { - format!("error converting supplied value for output_schema: {}", e) - }); - self - } - pub fn pay_to(mut self, value: T) -> Self - where - T: ::std::convert::TryInto, - T::Error: ::std::fmt::Display, - { - self.pay_to = value + self.data = value .try_into() - .map_err(|e| format!("error converting supplied value for pay_to: {}", e)); + .map_err(|e| format!("error converting supplied value for data: {}", e)); self } - pub fn resource(mut self, value: T) -> Self + pub fn message(mut self, value: T) -> Self where T: ::std::convert::TryInto<::std::string::String>, T::Error: ::std::fmt::Display, { - self.resource = value - .try_into() - .map_err(|e| format!("error converting supplied value for resource: {}", e)); - self - } - pub fn scheme(mut self, value: T) -> Self - where - T: ::std::convert::TryInto, - T::Error: ::std::fmt::Display, - { - self.scheme = value + self.message = value .try_into() - .map_err(|e| format!("error converting supplied value for scheme: {}", e)); + .map_err(|e| format!("error converting supplied value for message: {}", e)); self } } - impl ::std::convert::TryFrom for super::X402V1PaymentRequirements { + impl ::std::convert::TryFrom for super::X402McpError { type Error = super::error::ConversionError; fn try_from( - value: X402V1PaymentRequirements, + value: X402McpError, ) -> ::std::result::Result { Ok(Self { - asset: value.asset?, - description: value.description?, - extra: value.extra?, - max_amount_required: value.max_amount_required?, - max_timeout_seconds: value.max_timeout_seconds?, - mime_type: value.mime_type?, - network: value.network?, - output_schema: value.output_schema?, - pay_to: value.pay_to?, - resource: value.resource?, - scheme: value.scheme?, + code: value.code?, + data: value.data?, + message: value.message?, }) } } - impl ::std::convert::From for X402V1PaymentRequirements { - fn from(value: super::X402V1PaymentRequirements) -> Self { + impl ::std::convert::From for X402McpError { + fn from(value: super::X402McpError) -> Self { Self { - asset: Ok(value.asset), - description: Ok(value.description), - extra: Ok(value.extra), - max_amount_required: Ok(value.max_amount_required), - max_timeout_seconds: Ok(value.max_timeout_seconds), - mime_type: Ok(value.mime_type), - network: Ok(value.network), - output_schema: Ok(value.output_schema), - pay_to: Ok(value.pay_to), - resource: Ok(value.resource), - scheme: Ok(value.scheme), + code: Ok(value.code), + data: Ok(value.data), + message: Ok(value.message), } } } #[derive(Clone, Debug)] - pub struct X402V2PaymentPayload { - accepted: - ::std::result::Result, - extensions: ::std::result::Result< - ::serde_json::Map<::std::string::String, ::serde_json::Value>, + pub struct X402McpRequest { + id: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, - payload: - ::std::result::Result, - resource: ::std::result::Result< - ::std::option::Option, + jsonrpc: ::std::result::Result, + method: ::std::result::Result<::std::string::String, ::std::string::String>, + params: ::std::result::Result< + ::serde_json::Map<::std::string::String, ::serde_json::Value>, ::std::string::String, >, - x402_version: ::std::result::Result, } - impl ::std::default::Default for X402V2PaymentPayload { + impl ::std::default::Default for X402McpRequest { fn default() -> Self { Self { - accepted: Err("no value supplied for accepted".to_string()), - extensions: Ok(Default::default()), - payload: Err("no value supplied for payload".to_string()), - resource: Ok(Default::default()), - x402_version: Err("no value supplied for x402_version".to_string()), + id: Ok(Default::default()), + jsonrpc: Err("no value supplied for jsonrpc".to_string()), + method: Err("no value supplied for method".to_string()), + params: Ok(Default::default()), } } } - impl X402V2PaymentPayload { - pub fn accepted(mut self, value: T) -> Self + impl X402McpRequest { + pub fn id(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.accepted = value + self.id = value .try_into() - .map_err(|e| format!("error converting supplied value for accepted: {}", e)); + .map_err(|e| format!("error converting supplied value for id: {}", e)); self } - pub fn extensions(mut self, value: T) -> Self + pub fn jsonrpc(mut self, value: T) -> Self where - T: ::std::convert::TryInto< - ::serde_json::Map<::std::string::String, ::serde_json::Value>, - >, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.extensions = value + self.jsonrpc = value .try_into() - .map_err(|e| format!("error converting supplied value for extensions: {}", e)); + .map_err(|e| format!("error converting supplied value for jsonrpc: {}", e)); self } - pub fn payload(mut self, value: T) -> Self + pub fn method(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::string::String>, T::Error: ::std::fmt::Display, { - self.payload = value + self.method = value .try_into() - .map_err(|e| format!("error converting supplied value for payload: {}", e)); + .map_err(|e| format!("error converting supplied value for method: {}", e)); self } - pub fn resource(mut self, value: T) -> Self + pub fn params(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::option::Option>, + T: ::std::convert::TryInto< + ::serde_json::Map<::std::string::String, ::serde_json::Value>, + >, T::Error: ::std::fmt::Display, { - self.resource = value + self.params = value .try_into() - .map_err(|e| format!("error converting supplied value for resource: {}", e)); - self - } - pub fn x402_version(mut self, value: T) -> Self - where - T: ::std::convert::TryInto, - T::Error: ::std::fmt::Display, - { - self.x402_version = value.try_into().map_err(|e| { - format!("error converting supplied value for x402_version: {}", e) - }); + .map_err(|e| format!("error converting supplied value for params: {}", e)); self } } - impl ::std::convert::TryFrom for super::X402V2PaymentPayload { + impl ::std::convert::TryFrom for super::X402McpRequest { type Error = super::error::ConversionError; fn try_from( - value: X402V2PaymentPayload, + value: X402McpRequest, ) -> ::std::result::Result { Ok(Self { - accepted: value.accepted?, - extensions: value.extensions?, - payload: value.payload?, - resource: value.resource?, - x402_version: value.x402_version?, + id: value.id?, + jsonrpc: value.jsonrpc?, + method: value.method?, + params: value.params?, }) } } - impl ::std::convert::From for X402V2PaymentPayload { - fn from(value: super::X402V2PaymentPayload) -> Self { + impl ::std::convert::From for X402McpRequest { + fn from(value: super::X402McpRequest) -> Self { Self { - accepted: Ok(value.accepted), - extensions: Ok(value.extensions), - payload: Ok(value.payload), - resource: Ok(value.resource), - x402_version: Ok(value.x402_version), + id: Ok(value.id), + jsonrpc: Ok(value.jsonrpc), + method: Ok(value.method), + params: Ok(value.params), } } } #[derive(Clone, Debug)] - pub struct X402V2PaymentRequirements { - amount: ::std::result::Result<::std::string::String, ::std::string::String>, - asset: - ::std::result::Result, - extra: ::std::result::Result< - ::serde_json::Map<::std::string::String, ::serde_json::Value>, + pub struct X402McpResponse { + error: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, - max_timeout_seconds: ::std::result::Result, - network: ::std::result::Result<::std::string::String, ::std::string::String>, - pay_to: - ::std::result::Result, - scheme: ::std::result::Result< - super::X402v2PaymentRequirementsScheme, + id: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + jsonrpc: ::std::result::Result, + result: ::std::result::Result< + ::serde_json::Map<::std::string::String, ::serde_json::Value>, ::std::string::String, >, } - impl ::std::default::Default for X402V2PaymentRequirements { + impl ::std::default::Default for X402McpResponse { fn default() -> Self { Self { - amount: Err("no value supplied for amount".to_string()), - asset: Err("no value supplied for asset".to_string()), - extra: Ok(Default::default()), - max_timeout_seconds: Err( - "no value supplied for max_timeout_seconds".to_string() - ), - network: Err("no value supplied for network".to_string()), - pay_to: Err("no value supplied for pay_to".to_string()), - scheme: Err("no value supplied for scheme".to_string()), + error: Ok(Default::default()), + id: Ok(Default::default()), + jsonrpc: Err("no value supplied for jsonrpc".to_string()), + result: Ok(Default::default()), } } } - impl X402V2PaymentRequirements { - pub fn amount(mut self, value: T) -> Self + impl X402McpResponse { + pub fn error(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::string::String>, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.amount = value + self.error = value .try_into() - .map_err(|e| format!("error converting supplied value for amount: {}", e)); + .map_err(|e| format!("error converting supplied value for error: {}", e)); self } - pub fn asset(mut self, value: T) -> Self + pub fn id(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.asset = value + self.id = value .try_into() - .map_err(|e| format!("error converting supplied value for asset: {}", e)); + .map_err(|e| format!("error converting supplied value for id: {}", e)); self } - pub fn extra(mut self, value: T) -> Self + pub fn jsonrpc(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.jsonrpc = value + .try_into() + .map_err(|e| format!("error converting supplied value for jsonrpc: {}", e)); + self + } + pub fn result(mut self, value: T) -> Self where T: ::std::convert::TryInto< ::serde_json::Map<::std::string::String, ::serde_json::Value>, >, T::Error: ::std::fmt::Display, { - self.extra = value + self.result = value .try_into() - .map_err(|e| format!("error converting supplied value for extra: {}", e)); + .map_err(|e| format!("error converting supplied value for result: {}", e)); self } - pub fn max_timeout_seconds(mut self, value: T) -> Self + } + impl ::std::convert::TryFrom for super::X402McpResponse { + type Error = super::error::ConversionError; + fn try_from( + value: X402McpResponse, + ) -> ::std::result::Result { + Ok(Self { + error: value.error?, + id: value.id?, + jsonrpc: value.jsonrpc?, + result: value.result?, + }) + } + } + impl ::std::convert::From for X402McpResponse { + fn from(value: super::X402McpResponse) -> Self { + Self { + error: Ok(value.error), + id: Ok(value.id), + jsonrpc: Ok(value.jsonrpc), + result: Ok(value.result), + } + } + } + #[derive(Clone, Debug)] + pub struct X402ResourceInfo { + description: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + mime_type: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + url: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + } + impl ::std::default::Default for X402ResourceInfo { + fn default() -> Self { + Self { + description: Ok(Default::default()), + mime_type: Ok(Default::default()), + url: Ok(Default::default()), + } + } + } + impl X402ResourceInfo { + pub fn description(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.max_timeout_seconds = value.try_into().map_err(|e| { + self.description = value + .try_into() + .map_err(|e| format!("error converting supplied value for description: {}", e)); + self + } + pub fn mime_type(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.mime_type = value + .try_into() + .map_err(|e| format!("error converting supplied value for mime_type: {}", e)); + self + } + pub fn url(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.url = value + .try_into() + .map_err(|e| format!("error converting supplied value for url: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::X402ResourceInfo { + type Error = super::error::ConversionError; + fn try_from( + value: X402ResourceInfo, + ) -> ::std::result::Result { + Ok(Self { + description: value.description?, + mime_type: value.mime_type?, + url: value.url?, + }) + } + } + impl ::std::convert::From for X402ResourceInfo { + fn from(value: super::X402ResourceInfo) -> Self { + Self { + description: Ok(value.description), + mime_type: Ok(value.mime_type), + url: Ok(value.url), + } + } + } + #[derive(Clone, Debug)] + pub struct X402ResourceQuality { + l30_days_total_calls: + ::std::result::Result<::std::option::Option, ::std::string::String>, + l30_days_unique_payers: + ::std::result::Result<::std::option::Option, ::std::string::String>, + last_called_at: ::std::result::Result< + ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + ::std::string::String, + >, + } + impl ::std::default::Default for X402ResourceQuality { + fn default() -> Self { + Self { + l30_days_total_calls: Ok(Default::default()), + l30_days_unique_payers: Ok(Default::default()), + last_called_at: Ok(Default::default()), + } + } + } + impl X402ResourceQuality { + pub fn l30_days_total_calls(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.l30_days_total_calls = value.try_into().map_err(|e| { format!( - "error converting supplied value for max_timeout_seconds: {}", + "error converting supplied value for l30_days_total_calls: {}", e ) }); self } - pub fn network(mut self, value: T) -> Self + pub fn l30_days_unique_payers(mut self, value: T) -> Self where - T: ::std::convert::TryInto<::std::string::String>, + T: ::std::convert::TryInto<::std::option::Option>, T::Error: ::std::fmt::Display, { - self.network = value - .try_into() - .map_err(|e| format!("error converting supplied value for network: {}", e)); + self.l30_days_unique_payers = value.try_into().map_err(|e| { + format!( + "error converting supplied value for l30_days_unique_payers: {}", + e + ) + }); self } - pub fn pay_to(mut self, value: T) -> Self + pub fn last_called_at(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto< + ::std::option::Option<::chrono::DateTime<::chrono::offset::Utc>>, + >, T::Error: ::std::fmt::Display, { - self.pay_to = value - .try_into() - .map_err(|e| format!("error converting supplied value for pay_to: {}", e)); + self.last_called_at = value.try_into().map_err(|e| { + format!("error converting supplied value for last_called_at: {}", e) + }); self } - pub fn scheme(mut self, value: T) -> Self + } + impl ::std::convert::TryFrom for super::X402ResourceQuality { + type Error = super::error::ConversionError; + fn try_from( + value: X402ResourceQuality, + ) -> ::std::result::Result { + Ok(Self { + l30_days_total_calls: value.l30_days_total_calls?, + l30_days_unique_payers: value.l30_days_unique_payers?, + last_called_at: value.last_called_at?, + }) + } + } + impl ::std::convert::From for X402ResourceQuality { + fn from(value: super::X402ResourceQuality) -> Self { + Self { + l30_days_total_calls: Ok(value.l30_days_total_calls), + l30_days_unique_payers: Ok(value.l30_days_unique_payers), + last_called_at: Ok(value.last_called_at), + } + } + } + #[derive(Clone, Debug)] + pub struct X402SearchResourcesResponse { + partial_results: ::std::result::Result, + resources: ::std::result::Result< + ::std::vec::Vec, + ::std::string::String, + >, + search_method: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + x402_version: ::std::result::Result, + } + impl ::std::default::Default for X402SearchResourcesResponse { + fn default() -> Self { + Self { + partial_results: Err("no value supplied for partial_results".to_string()), + resources: Err("no value supplied for resources".to_string()), + search_method: Ok(Default::default()), + x402_version: Err("no value supplied for x402_version".to_string()), + } + } + } + impl X402SearchResourcesResponse { + pub fn partial_results(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.scheme = value + self.partial_results = value.try_into().map_err(|e| { + format!("error converting supplied value for partial_results: {}", e) + }); + self + } + pub fn resources(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::vec::Vec>, + T::Error: ::std::fmt::Display, + { + self.resources = value .try_into() - .map_err(|e| format!("error converting supplied value for scheme: {}", e)); + .map_err(|e| format!("error converting supplied value for resources: {}", e)); + self + } + pub fn search_method(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + ::std::option::Option, + >, + T::Error: ::std::fmt::Display, + { + self.search_method = value.try_into().map_err(|e| { + format!("error converting supplied value for search_method: {}", e) + }); + self + } + pub fn x402_version(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.x402_version = value.try_into().map_err(|e| { + format!("error converting supplied value for x402_version: {}", e) + }); self } } - impl ::std::convert::TryFrom for super::X402V2PaymentRequirements { + impl ::std::convert::TryFrom for super::X402SearchResourcesResponse { type Error = super::error::ConversionError; fn try_from( - value: X402V2PaymentRequirements, + value: X402SearchResourcesResponse, ) -> ::std::result::Result { Ok(Self { - amount: value.amount?, - asset: value.asset?, - extra: value.extra?, - max_timeout_seconds: value.max_timeout_seconds?, - network: value.network?, - pay_to: value.pay_to?, - scheme: value.scheme?, + partial_results: value.partial_results?, + resources: value.resources?, + search_method: value.search_method?, + x402_version: value.x402_version?, }) } } - impl ::std::convert::From for X402V2PaymentRequirements { - fn from(value: super::X402V2PaymentRequirements) -> Self { + impl ::std::convert::From for X402SearchResourcesResponse { + fn from(value: super::X402SearchResourcesResponse) -> Self { Self { - amount: Ok(value.amount), - asset: Ok(value.asset), - extra: Ok(value.extra), - max_timeout_seconds: Ok(value.max_timeout_seconds), - network: Ok(value.network), - pay_to: Ok(value.pay_to), - scheme: Ok(value.scheme), + partial_results: Ok(value.partial_results), + resources: Ok(value.resources), + search_method: Ok(value.search_method), + x402_version: Ok(value.x402_version), } } } #[derive(Clone, Debug)] - pub struct X402VerifyPaymentRejection { - invalid_message: ::std::result::Result< + pub struct X402SettlePaymentRejection { + error_message: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + error_reason: + ::std::result::Result, + network: ::std::result::Result< ::std::option::Option<::std::string::String>, ::std::string::String, >, - invalid_reason: - ::std::result::Result, - is_valid: ::std::result::Result, payer: ::std::result::Result< - ::std::option::Option, + ::std::option::Option, + ::std::string::String, + >, + success: ::std::result::Result, + transaction: ::std::result::Result< + ::std::option::Option, ::std::string::String, >, } - impl ::std::default::Default for X402VerifyPaymentRejection { + impl ::std::default::Default for X402SettlePaymentRejection { fn default() -> Self { Self { - invalid_message: Ok(Default::default()), - invalid_reason: Err("no value supplied for invalid_reason".to_string()), - is_valid: Err("no value supplied for is_valid".to_string()), + error_message: Ok(Default::default()), + error_reason: Err("no value supplied for error_reason".to_string()), + network: Ok(Default::default()), payer: Ok(Default::default()), + success: Err("no value supplied for success".to_string()), + transaction: Ok(Default::default()), } } } - impl X402VerifyPaymentRejection { - pub fn invalid_message(mut self, value: T) -> Self + impl X402SettlePaymentRejection { + pub fn error_message(mut self, value: T) -> Self where T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, T::Error: ::std::fmt::Display, { - self.invalid_message = value.try_into().map_err(|e| { - format!("error converting supplied value for invalid_message: {}", e) + self.error_message = value.try_into().map_err(|e| { + format!("error converting supplied value for error_message: {}", e) }); self } - pub fn invalid_reason(mut self, value: T) -> Self + pub fn error_reason(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto, T::Error: ::std::fmt::Display, { - self.invalid_reason = value.try_into().map_err(|e| { - format!("error converting supplied value for invalid_reason: {}", e) + self.error_reason = value.try_into().map_err(|e| { + format!("error converting supplied value for error_reason: {}", e) }); self } - pub fn is_valid(mut self, value: T) -> Self + pub fn network(mut self, value: T) -> Self where - T: ::std::convert::TryInto, + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, T::Error: ::std::fmt::Display, { - self.is_valid = value + self.network = value .try_into() - .map_err(|e| format!("error converting supplied value for is_valid: {}", e)); + .map_err(|e| format!("error converting supplied value for network: {}", e)); self } pub fn payer(mut self, value: T) -> Self where T: ::std::convert::TryInto< - ::std::option::Option, + ::std::option::Option, >, T::Error: ::std::fmt::Display, { @@ -82146,58 +93339,807 @@ pub mod types { .map_err(|e| format!("error converting supplied value for payer: {}", e)); self } + pub fn success(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.success = value + .try_into() + .map_err(|e| format!("error converting supplied value for success: {}", e)); + self + } + pub fn transaction(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + ::std::option::Option, + >, + T::Error: ::std::fmt::Display, + { + self.transaction = value + .try_into() + .map_err(|e| format!("error converting supplied value for transaction: {}", e)); + self + } } - impl ::std::convert::TryFrom for super::X402VerifyPaymentRejection { + impl ::std::convert::TryFrom for super::X402SettlePaymentRejection { type Error = super::error::ConversionError; fn try_from( - value: X402VerifyPaymentRejection, + value: X402SettlePaymentRejection, ) -> ::std::result::Result { Ok(Self { - invalid_message: value.invalid_message?, - invalid_reason: value.invalid_reason?, - is_valid: value.is_valid?, + error_message: value.error_message?, + error_reason: value.error_reason?, + network: value.network?, payer: value.payer?, + success: value.success?, + transaction: value.transaction?, }) } } - impl ::std::convert::From for X402VerifyPaymentRejection { - fn from(value: super::X402VerifyPaymentRejection) -> Self { + impl ::std::convert::From for X402SettlePaymentRejection { + fn from(value: super::X402SettlePaymentRejection) -> Self { Self { - invalid_message: Ok(value.invalid_message), - invalid_reason: Ok(value.invalid_reason), - is_valid: Ok(value.is_valid), + error_message: Ok(value.error_message), + error_reason: Ok(value.error_reason), + network: Ok(value.network), payer: Ok(value.payer), + success: Ok(value.success), + transaction: Ok(value.transaction), } } } - } - /// Generation of default values for serde. - pub mod defaults { - pub(super) fn default_u64() -> T - where - T: ::std::convert::TryFrom, - >::Error: ::std::fmt::Debug, - { - T::try_from(V).unwrap() + #[derive(Clone, Debug)] + pub struct X402SupportedPaymentKind { + extra: ::std::result::Result< + ::serde_json::Map<::std::string::String, ::serde_json::Value>, + ::std::string::String, + >, + network: ::std::result::Result< + super::X402SupportedPaymentKindNetwork, + ::std::string::String, + >, + scheme: + ::std::result::Result, + x402_version: ::std::result::Result, } - } - #[derive(Debug)] - pub enum SettleX402PaymentError { - Status400(X402SettlePaymentRejection), - Status402(Error), - Status500(Error), - Status502(Error), - Status503(Error), - } - #[derive(Debug)] - pub enum VerifyX402PaymentError { - Status400(X402VerifyPaymentRejection), - Status500(Error), - Status502(Error), - Status503(Error), - } -} -#[derive(Clone, Debug)] + impl ::std::default::Default for X402SupportedPaymentKind { + fn default() -> Self { + Self { + extra: Ok(Default::default()), + network: Err("no value supplied for network".to_string()), + scheme: Err("no value supplied for scheme".to_string()), + x402_version: Err("no value supplied for x402_version".to_string()), + } + } + } + impl X402SupportedPaymentKind { + pub fn extra(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + ::serde_json::Map<::std::string::String, ::serde_json::Value>, + >, + T::Error: ::std::fmt::Display, + { + self.extra = value + .try_into() + .map_err(|e| format!("error converting supplied value for extra: {}", e)); + self + } + pub fn network(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.network = value + .try_into() + .map_err(|e| format!("error converting supplied value for network: {}", e)); + self + } + pub fn scheme(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.scheme = value + .try_into() + .map_err(|e| format!("error converting supplied value for scheme: {}", e)); + self + } + pub fn x402_version(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.x402_version = value.try_into().map_err(|e| { + format!("error converting supplied value for x402_version: {}", e) + }); + self + } + } + impl ::std::convert::TryFrom for super::X402SupportedPaymentKind { + type Error = super::error::ConversionError; + fn try_from( + value: X402SupportedPaymentKind, + ) -> ::std::result::Result { + Ok(Self { + extra: value.extra?, + network: value.network?, + scheme: value.scheme?, + x402_version: value.x402_version?, + }) + } + } + impl ::std::convert::From for X402SupportedPaymentKind { + fn from(value: super::X402SupportedPaymentKind) -> Self { + Self { + extra: Ok(value.extra), + network: Ok(value.network), + scheme: Ok(value.scheme), + x402_version: Ok(value.x402_version), + } + } + } + #[derive(Clone, Debug)] + pub struct X402V1PaymentPayload { + network: + ::std::result::Result, + payload: + ::std::result::Result, + scheme: ::std::result::Result, + x402_version: ::std::result::Result, + } + impl ::std::default::Default for X402V1PaymentPayload { + fn default() -> Self { + Self { + network: Err("no value supplied for network".to_string()), + payload: Err("no value supplied for payload".to_string()), + scheme: Err("no value supplied for scheme".to_string()), + x402_version: Err("no value supplied for x402_version".to_string()), + } + } + } + impl X402V1PaymentPayload { + pub fn network(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.network = value + .try_into() + .map_err(|e| format!("error converting supplied value for network: {}", e)); + self + } + pub fn payload(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.payload = value + .try_into() + .map_err(|e| format!("error converting supplied value for payload: {}", e)); + self + } + pub fn scheme(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.scheme = value + .try_into() + .map_err(|e| format!("error converting supplied value for scheme: {}", e)); + self + } + pub fn x402_version(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.x402_version = value.try_into().map_err(|e| { + format!("error converting supplied value for x402_version: {}", e) + }); + self + } + } + impl ::std::convert::TryFrom for super::X402V1PaymentPayload { + type Error = super::error::ConversionError; + fn try_from( + value: X402V1PaymentPayload, + ) -> ::std::result::Result { + Ok(Self { + network: value.network?, + payload: value.payload?, + scheme: value.scheme?, + x402_version: value.x402_version?, + }) + } + } + impl ::std::convert::From for X402V1PaymentPayload { + fn from(value: super::X402V1PaymentPayload) -> Self { + Self { + network: Ok(value.network), + payload: Ok(value.payload), + scheme: Ok(value.scheme), + x402_version: Ok(value.x402_version), + } + } + } + #[derive(Clone, Debug)] + pub struct X402V1PaymentRequirements { + asset: + ::std::result::Result, + description: ::std::result::Result, + extra: ::std::result::Result< + ::serde_json::Map<::std::string::String, ::serde_json::Value>, + ::std::string::String, + >, + max_amount_required: + ::std::result::Result<::std::string::String, ::std::string::String>, + max_timeout_seconds: ::std::result::Result, + mime_type: ::std::result::Result<::std::string::String, ::std::string::String>, + network: ::std::result::Result< + super::X402v1PaymentRequirementsNetwork, + ::std::string::String, + >, + output_schema: ::std::result::Result< + ::serde_json::Map<::std::string::String, ::serde_json::Value>, + ::std::string::String, + >, + pay_to: + ::std::result::Result, + resource: ::std::result::Result<::std::string::String, ::std::string::String>, + scheme: ::std::result::Result< + super::X402v1PaymentRequirementsScheme, + ::std::string::String, + >, + } + impl ::std::default::Default for X402V1PaymentRequirements { + fn default() -> Self { + Self { + asset: Err("no value supplied for asset".to_string()), + description: Err("no value supplied for description".to_string()), + extra: Ok(Default::default()), + max_amount_required: Err( + "no value supplied for max_amount_required".to_string() + ), + max_timeout_seconds: Err( + "no value supplied for max_timeout_seconds".to_string() + ), + mime_type: Err("no value supplied for mime_type".to_string()), + network: Err("no value supplied for network".to_string()), + output_schema: Ok(Default::default()), + pay_to: Err("no value supplied for pay_to".to_string()), + resource: Err("no value supplied for resource".to_string()), + scheme: Err("no value supplied for scheme".to_string()), + } + } + } + impl X402V1PaymentRequirements { + pub fn asset(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.asset = value + .try_into() + .map_err(|e| format!("error converting supplied value for asset: {}", e)); + self + } + pub fn description(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.description = value + .try_into() + .map_err(|e| format!("error converting supplied value for description: {}", e)); + self + } + pub fn extra(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + ::serde_json::Map<::std::string::String, ::serde_json::Value>, + >, + T::Error: ::std::fmt::Display, + { + self.extra = value + .try_into() + .map_err(|e| format!("error converting supplied value for extra: {}", e)); + self + } + pub fn max_amount_required(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::string::String>, + T::Error: ::std::fmt::Display, + { + self.max_amount_required = value.try_into().map_err(|e| { + format!( + "error converting supplied value for max_amount_required: {}", + e + ) + }); + self + } + pub fn max_timeout_seconds(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.max_timeout_seconds = value.try_into().map_err(|e| { + format!( + "error converting supplied value for max_timeout_seconds: {}", + e + ) + }); + self + } + pub fn mime_type(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::string::String>, + T::Error: ::std::fmt::Display, + { + self.mime_type = value + .try_into() + .map_err(|e| format!("error converting supplied value for mime_type: {}", e)); + self + } + pub fn network(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.network = value + .try_into() + .map_err(|e| format!("error converting supplied value for network: {}", e)); + self + } + pub fn output_schema(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + ::serde_json::Map<::std::string::String, ::serde_json::Value>, + >, + T::Error: ::std::fmt::Display, + { + self.output_schema = value.try_into().map_err(|e| { + format!("error converting supplied value for output_schema: {}", e) + }); + self + } + pub fn pay_to(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.pay_to = value + .try_into() + .map_err(|e| format!("error converting supplied value for pay_to: {}", e)); + self + } + pub fn resource(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::string::String>, + T::Error: ::std::fmt::Display, + { + self.resource = value + .try_into() + .map_err(|e| format!("error converting supplied value for resource: {}", e)); + self + } + pub fn scheme(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.scheme = value + .try_into() + .map_err(|e| format!("error converting supplied value for scheme: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::X402V1PaymentRequirements { + type Error = super::error::ConversionError; + fn try_from( + value: X402V1PaymentRequirements, + ) -> ::std::result::Result { + Ok(Self { + asset: value.asset?, + description: value.description?, + extra: value.extra?, + max_amount_required: value.max_amount_required?, + max_timeout_seconds: value.max_timeout_seconds?, + mime_type: value.mime_type?, + network: value.network?, + output_schema: value.output_schema?, + pay_to: value.pay_to?, + resource: value.resource?, + scheme: value.scheme?, + }) + } + } + impl ::std::convert::From for X402V1PaymentRequirements { + fn from(value: super::X402V1PaymentRequirements) -> Self { + Self { + asset: Ok(value.asset), + description: Ok(value.description), + extra: Ok(value.extra), + max_amount_required: Ok(value.max_amount_required), + max_timeout_seconds: Ok(value.max_timeout_seconds), + mime_type: Ok(value.mime_type), + network: Ok(value.network), + output_schema: Ok(value.output_schema), + pay_to: Ok(value.pay_to), + resource: Ok(value.resource), + scheme: Ok(value.scheme), + } + } + } + #[derive(Clone, Debug)] + pub struct X402V2PaymentPayload { + accepted: + ::std::result::Result, + extensions: ::std::result::Result< + ::serde_json::Map<::std::string::String, ::serde_json::Value>, + ::std::string::String, + >, + payload: + ::std::result::Result, + resource: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + x402_version: ::std::result::Result, + } + impl ::std::default::Default for X402V2PaymentPayload { + fn default() -> Self { + Self { + accepted: Err("no value supplied for accepted".to_string()), + extensions: Ok(Default::default()), + payload: Err("no value supplied for payload".to_string()), + resource: Ok(Default::default()), + x402_version: Err("no value supplied for x402_version".to_string()), + } + } + } + impl X402V2PaymentPayload { + pub fn accepted(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.accepted = value + .try_into() + .map_err(|e| format!("error converting supplied value for accepted: {}", e)); + self + } + pub fn extensions(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + ::serde_json::Map<::std::string::String, ::serde_json::Value>, + >, + T::Error: ::std::fmt::Display, + { + self.extensions = value + .try_into() + .map_err(|e| format!("error converting supplied value for extensions: {}", e)); + self + } + pub fn payload(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.payload = value + .try_into() + .map_err(|e| format!("error converting supplied value for payload: {}", e)); + self + } + pub fn resource(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.resource = value + .try_into() + .map_err(|e| format!("error converting supplied value for resource: {}", e)); + self + } + pub fn x402_version(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.x402_version = value.try_into().map_err(|e| { + format!("error converting supplied value for x402_version: {}", e) + }); + self + } + } + impl ::std::convert::TryFrom for super::X402V2PaymentPayload { + type Error = super::error::ConversionError; + fn try_from( + value: X402V2PaymentPayload, + ) -> ::std::result::Result { + Ok(Self { + accepted: value.accepted?, + extensions: value.extensions?, + payload: value.payload?, + resource: value.resource?, + x402_version: value.x402_version?, + }) + } + } + impl ::std::convert::From for X402V2PaymentPayload { + fn from(value: super::X402V2PaymentPayload) -> Self { + Self { + accepted: Ok(value.accepted), + extensions: Ok(value.extensions), + payload: Ok(value.payload), + resource: Ok(value.resource), + x402_version: Ok(value.x402_version), + } + } + } + #[derive(Clone, Debug)] + pub struct X402V2PaymentRequirements { + amount: ::std::result::Result<::std::string::String, ::std::string::String>, + asset: + ::std::result::Result, + extra: ::std::result::Result< + ::serde_json::Map<::std::string::String, ::serde_json::Value>, + ::std::string::String, + >, + max_timeout_seconds: ::std::result::Result, + network: ::std::result::Result<::std::string::String, ::std::string::String>, + pay_to: + ::std::result::Result, + scheme: ::std::result::Result< + super::X402v2PaymentRequirementsScheme, + ::std::string::String, + >, + } + impl ::std::default::Default for X402V2PaymentRequirements { + fn default() -> Self { + Self { + amount: Err("no value supplied for amount".to_string()), + asset: Err("no value supplied for asset".to_string()), + extra: Ok(Default::default()), + max_timeout_seconds: Err( + "no value supplied for max_timeout_seconds".to_string() + ), + network: Err("no value supplied for network".to_string()), + pay_to: Err("no value supplied for pay_to".to_string()), + scheme: Err("no value supplied for scheme".to_string()), + } + } + } + impl X402V2PaymentRequirements { + pub fn amount(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::string::String>, + T::Error: ::std::fmt::Display, + { + self.amount = value + .try_into() + .map_err(|e| format!("error converting supplied value for amount: {}", e)); + self + } + pub fn asset(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.asset = value + .try_into() + .map_err(|e| format!("error converting supplied value for asset: {}", e)); + self + } + pub fn extra(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + ::serde_json::Map<::std::string::String, ::serde_json::Value>, + >, + T::Error: ::std::fmt::Display, + { + self.extra = value + .try_into() + .map_err(|e| format!("error converting supplied value for extra: {}", e)); + self + } + pub fn max_timeout_seconds(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.max_timeout_seconds = value.try_into().map_err(|e| { + format!( + "error converting supplied value for max_timeout_seconds: {}", + e + ) + }); + self + } + pub fn network(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::string::String>, + T::Error: ::std::fmt::Display, + { + self.network = value + .try_into() + .map_err(|e| format!("error converting supplied value for network: {}", e)); + self + } + pub fn pay_to(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.pay_to = value + .try_into() + .map_err(|e| format!("error converting supplied value for pay_to: {}", e)); + self + } + pub fn scheme(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.scheme = value + .try_into() + .map_err(|e| format!("error converting supplied value for scheme: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::X402V2PaymentRequirements { + type Error = super::error::ConversionError; + fn try_from( + value: X402V2PaymentRequirements, + ) -> ::std::result::Result { + Ok(Self { + amount: value.amount?, + asset: value.asset?, + extra: value.extra?, + max_timeout_seconds: value.max_timeout_seconds?, + network: value.network?, + pay_to: value.pay_to?, + scheme: value.scheme?, + }) + } + } + impl ::std::convert::From for X402V2PaymentRequirements { + fn from(value: super::X402V2PaymentRequirements) -> Self { + Self { + amount: Ok(value.amount), + asset: Ok(value.asset), + extra: Ok(value.extra), + max_timeout_seconds: Ok(value.max_timeout_seconds), + network: Ok(value.network), + pay_to: Ok(value.pay_to), + scheme: Ok(value.scheme), + } + } + } + #[derive(Clone, Debug)] + pub struct X402VerifyPaymentRejection { + invalid_message: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + invalid_reason: + ::std::result::Result, + is_valid: ::std::result::Result, + payer: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + } + impl ::std::default::Default for X402VerifyPaymentRejection { + fn default() -> Self { + Self { + invalid_message: Ok(Default::default()), + invalid_reason: Err("no value supplied for invalid_reason".to_string()), + is_valid: Err("no value supplied for is_valid".to_string()), + payer: Ok(Default::default()), + } + } + } + impl X402VerifyPaymentRejection { + pub fn invalid_message(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.invalid_message = value.try_into().map_err(|e| { + format!("error converting supplied value for invalid_message: {}", e) + }); + self + } + pub fn invalid_reason(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.invalid_reason = value.try_into().map_err(|e| { + format!("error converting supplied value for invalid_reason: {}", e) + }); + self + } + pub fn is_valid(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.is_valid = value + .try_into() + .map_err(|e| format!("error converting supplied value for is_valid: {}", e)); + self + } + pub fn payer(mut self, value: T) -> Self + where + T: ::std::convert::TryInto< + ::std::option::Option, + >, + T::Error: ::std::fmt::Display, + { + self.payer = value + .try_into() + .map_err(|e| format!("error converting supplied value for payer: {}", e)); + self + } + } + impl ::std::convert::TryFrom for super::X402VerifyPaymentRejection { + type Error = super::error::ConversionError; + fn try_from( + value: X402VerifyPaymentRejection, + ) -> ::std::result::Result { + Ok(Self { + invalid_message: value.invalid_message?, + invalid_reason: value.invalid_reason?, + is_valid: value.is_valid?, + payer: value.payer?, + }) + } + } + impl ::std::convert::From for X402VerifyPaymentRejection { + fn from(value: super::X402VerifyPaymentRejection) -> Self { + Self { + invalid_message: Ok(value.invalid_message), + invalid_reason: Ok(value.invalid_reason), + is_valid: Ok(value.is_valid), + payer: Ok(value.payer), + } + } + } + } + /// Generation of default values for serde. + pub mod defaults { + pub(super) fn default_u64() -> T + where + T: ::std::convert::TryFrom, + >::Error: ::std::fmt::Debug, + { + T::try_from(V).unwrap() + } + pub(super) fn transfer_request_amount_type() -> super::TransferRequestAmountType { + super::TransferRequestAmountType::Source + } + } + #[derive(Debug)] + pub enum SettleX402PaymentError { + Status400(X402SettlePaymentRejection), + Status402(Error), + Status500(Error), + Status502(Error), + Status503(Error), + } + #[derive(Debug)] + pub enum VerifyX402PaymentError { + Status400(X402VerifyPaymentRejection), + Status500(Error), + Status502(Error), + Status503(Error), + } +} +#[derive(Clone, Debug)] /**Client for Coinbase Developer Platform APIs The Coinbase Developer Platform APIs - leading the world's transition onchain. @@ -82263,6 +94205,106 @@ impl ClientInfo<()> for Client { } impl ClientHooks<()> for &Client {} impl Client { + /**List accounts + + List all accounts. The API will return all accounts that the API Key has Permissions to access. You can filter the results by using query parameters, which will be treated as a single conjunction (i.e. AND). Results are sorted by creation date in descending order (newest first). + + Sends a `GET` request to `/v2/accounts` + + Arguments: + - `page_size`: The number of resources to return per page. + - `page_token`: The token for the next page of resources, if any. + - `type_`: Filter accounts by account type. When omitted, accounts of any type are returned. Combined with `owner` using AND. + ```ignore + let response = client.list_foundation_accounts() + .page_size(page_size) + .page_token(page_token) + .type_(type_) + .send() + .await; + ```*/ + pub fn list_foundation_accounts(&self) -> builder::ListFoundationAccounts<'_> { + builder::ListFoundationAccounts::new(self) + } + /**Create account + + Create an account for your Entity. Support for creating Customer-owned accounts is in development. + + Sends a `POST` request to `/v2/accounts` + + Arguments: + - `x_idempotency_key`: An optional string request header for making requests safely retryable. + When included, duplicate requests with the same key will return identical responses. + Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + + - `body` + ```ignore + let response = client.create_foundation_account() + .x_idempotency_key(x_idempotency_key) + .body(body) + .send() + .await; + ```*/ + pub fn create_foundation_account(&self) -> builder::CreateFoundationAccount<'_> { + builder::CreateFoundationAccount::new(self) + } + /**Get account + + Get an account by its ID. + + Sends a `GET` request to `/v2/accounts/{accountId}` + + Arguments: + - `account_id`: The ID of the account to retrieve. + ```ignore + let response = client.get_foundation_account_by_id() + .account_id(account_id) + .send() + .await; + ```*/ + pub fn get_foundation_account_by_id(&self) -> builder::GetFoundationAccountById<'_> { + builder::GetFoundationAccountById::new(self) + } + /**List balances for account + + List the balances for an account. Results are sorted by native-fiat equivalent balance in descending order. + + Sends a `GET` request to `/v2/accounts/{accountId}/balances` + + Arguments: + - `account_id`: The unique identifier of the account. + - `page_size`: The number of resources to return per page. + - `page_token`: The token for the next page of resources, if any. + ```ignore + let response = client.list_balances() + .account_id(account_id) + .page_size(page_size) + .page_token(page_token) + .send() + .await; + ```*/ + pub fn list_balances(&self) -> builder::ListBalances<'_> { + builder::ListBalances::new(self) + } + /**Get balance for account + + Get the balance for an account by asset. + + Sends a `GET` request to `/v2/accounts/{accountId}/balances/{asset}` + + Arguments: + - `account_id`: The unique identifier of the account. + - `asset`: The symbol of the asset. + ```ignore + let response = client.get_balance_by_asset() + .account_id(account_id) + .asset(asset) + .send() + .await; + ```*/ + pub fn get_balance_by_asset(&self) -> builder::GetBalanceByAsset<'_> { + builder::GetBalanceByAsset::new(self) + } /**List EVM token balances Lists the token balances of an EVM address on a given network. The balances include ERC-20 tokens and the native gas token (usually ETH). The response is paginated, and by default, returns 20 balances per page. @@ -82387,7 +94429,7 @@ impl Client { pub fn run_sql_query(&self) -> builder::RunSqlQuery<'_> { builder::RunSqlQuery::new(self) } - /**Get schemas details + /**Get schema details Retrieve the schema information for the available tables in the SQL API's indexed data. @@ -82503,7 +94545,7 @@ impl Client { pub fn create_webhook_subscription(&self) -> builder::CreateWebhookSubscription<'_> { builder::CreateWebhookSubscription::new(self) } - /**Get webhook subscription details + /**Get webhook subscription Retrieve detailed information about a specific webhook subscription including configuration, status, creation timestamp, and webhook signature secret. @@ -82622,7 +94664,73 @@ impl Client { pub fn list_webhook_subscription_events(&self) -> builder::ListWebhookSubscriptionEvents<'_> { builder::ListWebhookSubscriptionEvents::new(self) } - /**Get account-scoped delegation for an end user account + /**List deposit destinations + + List deposit destinations. You can optionally filter the results by type, account ID, network, or cryptocurrency address. Results are sorted by creation date in descending order (newest first). + + Sends a `GET` request to `/v2/deposit-destinations` + + Arguments: + - `account_id`: Filter deposit destinations by account ID. + - `address`: Filter deposit destinations by the cryptocurrency address. + - `network`: Filter deposit destinations by network. + - `page_size`: The number of resources to return per page. + - `page_token`: The token for the next page of resources, if any. + - `type_`: Filter deposit destinations by type. + ```ignore + let response = client.list_deposit_destinations() + .account_id(account_id) + .address(address) + .network(network) + .page_size(page_size) + .page_token(page_token) + .type_(type_) + .send() + .await; + ```*/ + pub fn list_deposit_destinations(&self) -> builder::ListDepositDestinations<'_> { + builder::ListDepositDestinations::new(self) + } + /**Create deposit destination + + Create a new deposit destination for an account. A deposit destination is a cryptocurrency address that can be used to receive funds. The address will be generated for the specified network. + + Sends a `POST` request to `/v2/deposit-destinations` + + Arguments: + - `x_idempotency_key`: An optional string request header for making requests safely retryable. + When included, duplicate requests with the same key will return identical responses. + Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + + - `body` + ```ignore + let response = client.create_deposit_destination() + .x_idempotency_key(x_idempotency_key) + .body(body) + .send() + .await; + ```*/ + pub fn create_deposit_destination(&self) -> builder::CreateDepositDestination<'_> { + builder::CreateDepositDestination::new(self) + } + /**Get deposit destination + + Get a specific deposit destination by its ID. + + Sends a `GET` request to `/v2/deposit-destinations/{depositDestinationId}` + + Arguments: + - `deposit_destination_id`: The ID of the deposit address to retrieve. + ```ignore + let response = client.get_deposit_destination_by_id() + .deposit_destination_id(deposit_destination_id) + .send() + .await; + ```*/ + pub fn get_deposit_destination_by_id(&self) -> builder::GetDepositDestinationById<'_> { + builder::GetDepositDestinationById::new(self) + } + /**Get account-scoped delegation for end user Returns the active account-scoped delegation for the specified end user account, if one exists. Useful for showing delegation status in a UI. When the address corresponds to an EVM Smart Account, this returns the delegation for the Smart Account's owner EOA. @@ -82646,7 +94754,7 @@ impl Client { ) -> builder::GetDelegationForEndUserAccount<'_> { builder::GetDelegationForEndUserAccount::new(self) } - /**Create account-scoped delegation for an end user account + /**Create account-scoped delegation for end user Creates an account-scoped delegation that allows a developer to sign on behalf of an end user for a single blockchain account (identified by its address) for the specified duration. The end user must be authenticated to authorize this delegation. Multiple account-scoped delegations may exist concurrently for a single end user (one per canonical account address). Account-scoped and user-scoped delegations cannot coexist for the same user. @@ -82683,7 +94791,7 @@ impl Client { ) -> builder::CreateDelegationForEndUserAccount<'_> { builder::CreateDelegationForEndUserAccount::new(self) } - /**Revoke account-scoped delegation for an end user account + /**Revoke account-scoped delegation for end user Revokes the active account-scoped delegation for the specified end user account. Other account-scoped delegations for the same user are unaffected. This operation can be performed by the end user themselves or by a developer using their API key. When the address corresponds to an EVM Smart Account, this revokes the delegation for the Smart Account's owner EOA. @@ -82825,7 +94933,7 @@ impl Client { ) -> builder::CreateEvmEip7702DelegationWithEndUserAccount<'_> { builder::CreateEvmEip7702DelegationWithEndUserAccount::new(self) } - /**Send a transaction with end user EVM account + /**Send transaction via end user EVM account Signs a transaction with the given end user EVM account and sends it to the indicated supported network. This API handles nonce management and gas estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). @@ -82888,7 +94996,7 @@ impl Client { ) -> builder::SendEvmTransactionWithEndUserAccount<'_> { builder::SendEvmTransactionWithEndUserAccount::new(self) } - /**Sign an EIP-191 message with end user EVM account + /**Sign EIP-191 message via end user EVM account Signs an [EIP-191](https://eips.ethereum.org/EIPS/eip-191) message with the given end user EVM account. @@ -82928,7 +95036,7 @@ impl Client { ) -> builder::SignEvmMessageWithEndUserAccount<'_> { builder::SignEvmMessageWithEndUserAccount::new(self) } - /**Sign a transaction with end user EVM account + /**Sign transaction via end user EVM account Signs a transaction with the given end user EVM account. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). @@ -82969,7 +95077,7 @@ impl Client { ) -> builder::SignEvmTransactionWithEndUserAccount<'_> { builder::SignEvmTransactionWithEndUserAccount::new(self) } - /**Sign EIP-712 typed data with end user EVM account + /**Sign EIP-712 typed data via end user EVM account Signs [EIP-712](https://eips.ethereum.org/EIPS/eip-712) typed data with the given end user EVM account. @@ -83007,7 +95115,7 @@ impl Client { ) -> builder::SignEvmTypedDataWithEndUserAccount<'_> { builder::SignEvmTypedDataWithEndUserAccount::new(self) } - /**Send a user operation for end user Smart Account + /**Send user operation for end user Smart Account Prepares, signs, and sends a user operation for an end user's Smart Account. @@ -83090,7 +95198,7 @@ impl Client { ) -> builder::SendEvmAssetWithEndUserAccount<'_> { builder::SendEvmAssetWithEndUserAccount::new(self) } - /**Send a transaction with end user Solana account + /**Send transaction via end user Solana account Signs a transaction with the given end user Solana account and sends it to the indicated supported network. The API handles recent blockhash management and fee estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. @@ -83141,7 +95249,7 @@ impl Client { ) -> builder::SendSolanaTransactionWithEndUserAccount<'_> { builder::SendSolanaTransactionWithEndUserAccount::new(self) } - /**Sign a Base64 encoded message + /**Sign Base64-encoded message Signs an arbitrary Base64 encoded message with the given Solana account. **WARNING:** Never sign a message that you didn't generate as it may put your funds at risk. @@ -83180,7 +95288,7 @@ impl Client { ) -> builder::SignSolanaMessageWithEndUserAccount<'_> { builder::SignSolanaMessageWithEndUserAccount::new(self) } - /**Sign a transaction with end user Solana account + /**Sign transaction via end user Solana account Signs a transaction with the given end user Solana account. The unsigned transaction should be serialized into a byte array and then encoded as base64. @@ -83290,7 +95398,7 @@ impl Client { pub fn list_end_users(&self) -> builder::ListEndUsers<'_> { builder::ListEndUsers::new(self) } - /**Create an end user + /**Create end user Creates an end user. An end user is an entity that can own CDP EVM accounts, EVM smart accounts, and/or Solana accounts. 1 or more authentication methods must be associated with an end user. By default, no accounts are created unless the optional `evmAccount` and/or `solanaAccount` fields are provided. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. @@ -83335,7 +95443,7 @@ impl Client { pub fn validate_end_user_access_token(&self) -> builder::ValidateEndUserAccessToken<'_> { builder::ValidateEndUserAccessToken::new(self) } - /**Import a private key for an end user + /**Import end user private key Imports an existing private key for an end user into the developer's CDP Project. The private key must be encrypted using the CDP SDK's encryption scheme before being sent to this endpoint. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. @@ -83401,7 +95509,7 @@ impl Client { pub fn lookup_end_user(&self) -> builder::LookupEndUser<'_> { builder::LookupEndUser::new(self) } - /**Get an end user + /**Get end user Gets an end user by ID. @@ -83420,7 +95528,7 @@ impl Client { pub fn get_end_user(&self) -> builder::GetEndUser<'_> { builder::GetEndUser::new(self) } - /**Add an EVM account to an end user + /**Add EVM account to end user Adds a new EVM EOA account to an existing end user. End users can have up to 10 EVM accounts. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. @@ -83450,7 +95558,7 @@ impl Client { pub fn add_end_user_evm_account(&self) -> builder::AddEndUserEvmAccount<'_> { builder::AddEndUserEvmAccount::new(self) } - /**Add an EVM smart account to an end user + /**Add EVM smart account to end user Creates an EVM smart account for an existing end user. The backend will create a new EVM EOA account to serve as the owner of the smart account. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. @@ -83480,7 +95588,7 @@ impl Client { pub fn add_end_user_evm_smart_account(&self) -> builder::AddEndUserEvmSmartAccount<'_> { builder::AddEndUserEvmSmartAccount::new(self) } - /**Add a Solana account to an end user + /**Add Solana account to end user Adds a new Solana account to an existing end user. End users can have up to 10 Solana accounts. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. @@ -83530,7 +95638,7 @@ impl Client { pub fn list_evm_accounts(&self) -> builder::ListEvmAccounts<'_> { builder::ListEvmAccounts::new(self) } - /**Create an EVM account + /**Create EVM account Creates a new EVM account. @@ -83557,7 +95665,7 @@ impl Client { pub fn create_evm_account(&self) -> builder::CreateEvmAccount<'_> { builder::CreateEvmAccount::new(self) } - /**Get an EVM account by name + /**Get EVM account by name Gets an EVM account by its name. @@ -83574,7 +95682,7 @@ impl Client { pub fn get_evm_account_by_name(&self) -> builder::GetEvmAccountByName<'_> { builder::GetEvmAccountByName::new(self) } - /**Export an EVM account by name + /**Export EVM account by name Export an existing EVM account's private key by its name. It is important to store the private key in a secure place after it's exported. @@ -83603,7 +95711,7 @@ impl Client { pub fn export_evm_account_by_name(&self) -> builder::ExportEvmAccountByName<'_> { builder::ExportEvmAccountByName::new(self) } - /**Import an EVM account + /**Import EVM account Import an existing EVM account into the developer's CDP Project. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. @@ -83630,7 +95738,7 @@ impl Client { pub fn import_evm_account(&self) -> builder::ImportEvmAccount<'_> { builder::ImportEvmAccount::new(self) } - /**Get an EVM account by address + /**Get EVM account by address Gets an EVM account by its address. @@ -83647,7 +95755,7 @@ impl Client { pub fn get_evm_account(&self) -> builder::GetEvmAccount<'_> { builder::GetEvmAccount::new(self) } - /**Update an EVM account + /**Update EVM account Updates an existing EVM account. Use this to update the account's name or account-level policy. @@ -83708,7 +95816,7 @@ impl Client { pub fn create_evm_eip7702_delegation(&self) -> builder::CreateEvmEip7702Delegation<'_> { builder::CreateEvmEip7702Delegation::new(self) } - /**Export an EVM account + /**Export EVM account Export an existing EVM account's private key. It is important to store the private key in a secure place after it's exported. @@ -83737,7 +95845,7 @@ impl Client { pub fn export_evm_account(&self) -> builder::ExportEvmAccount<'_> { builder::ExportEvmAccount::new(self) } - /**Send a transaction + /**Send transaction Signs a transaction with the given EVM account and sends it to the indicated supported network. This API handles nonce management and gas estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). @@ -83791,7 +95899,7 @@ impl Client { pub fn send_evm_transaction(&self) -> builder::SendEvmTransaction<'_> { builder::SendEvmTransaction::new(self) } - /**Sign a hash + /**Sign hash Signs an arbitrary 32 byte hash with the given EVM account. @@ -83820,7 +95928,7 @@ impl Client { pub fn sign_evm_hash(&self) -> builder::SignEvmHash<'_> { builder::SignEvmHash::new(self) } - /**Sign an EIP-191 message + /**Sign EIP-191 message Signs an [EIP-191](https://eips.ethereum.org/EIPS/eip-191) message with the given EVM account. @@ -83851,7 +95959,7 @@ impl Client { pub fn sign_evm_message(&self) -> builder::SignEvmMessage<'_> { builder::SignEvmMessage::new(self) } - /**Sign a transaction + /**Sign transaction Signs a transaction with the given EVM account. The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). @@ -83912,7 +96020,7 @@ impl Client { pub fn sign_evm_typed_data(&self) -> builder::SignEvmTypedData<'_> { builder::SignEvmTypedData::new(self) } - /**Get EIP-7702 delegation operation for an operationID + /**Get EIP-7702 delegation operation by ID Returns the EIP-7702 delegation operation. Use the delegationOperationId returned by the Create EIP-7702 delegation endpoint to poll for operation completion. @@ -83980,7 +96088,7 @@ impl Client { pub fn list_evm_smart_accounts(&self) -> builder::ListEvmSmartAccounts<'_> { builder::ListEvmSmartAccounts::new(self) } - /**Create a Smart Account + /**Create Smart Account Creates a new Smart Account. @@ -84002,7 +96110,7 @@ impl Client { pub fn create_evm_smart_account(&self) -> builder::CreateEvmSmartAccount<'_> { builder::CreateEvmSmartAccount::new(self) } - /**Get a Smart Account by name + /**Get Smart Account by name Gets a Smart Account by its name. @@ -84019,7 +96127,7 @@ impl Client { pub fn get_evm_smart_account_by_name(&self) -> builder::GetEvmSmartAccountByName<'_> { builder::GetEvmSmartAccountByName::new(self) } - /**Get a Smart Account by address + /**Get Smart Account by address Gets a Smart Account by its address. @@ -84036,7 +96144,7 @@ impl Client { pub fn get_evm_smart_account(&self) -> builder::GetEvmSmartAccount<'_> { builder::GetEvmSmartAccount::new(self) } - /**Update an EVM Smart Account + /**Update EVM Smart Account Updates an existing EVM smart account. Use this to update the smart account's name. @@ -84055,7 +96163,7 @@ impl Client { pub fn update_evm_smart_account(&self) -> builder::UpdateEvmSmartAccount<'_> { builder::UpdateEvmSmartAccount::new(self) } - /**Create a spend permission + /**Create spend permission Creates a spend permission for the given smart account address. @@ -84105,7 +96213,7 @@ impl Client { pub fn list_spend_permissions(&self) -> builder::ListSpendPermissions<'_> { builder::ListSpendPermissions::new(self) } - /**Revoke a spend permission + /**Revoke spend permission Revokes an existing spend permission. @@ -84134,7 +96242,7 @@ impl Client { pub fn revoke_spend_permission(&self) -> builder::RevokeSpendPermission<'_> { builder::RevokeSpendPermission::new(self) } - /**Prepare a user operation + /**Prepare user operation Prepares a new user operation on a Smart Account for a specific network. @@ -84153,7 +96261,7 @@ impl Client { pub fn prepare_user_operation(&self) -> builder::PrepareUserOperation<'_> { builder::PrepareUserOperation::new(self) } - /**Prepare and send a user operation for EVM Smart Account + /**Prepare and send user operation Prepares, signs, and sends a user operation for an EVM Smart Account. This API can be used only if the owner on Smart Account is a CDP EVM Account. @@ -84182,7 +96290,7 @@ impl Client { pub fn prepare_and_send_user_operation(&self) -> builder::PrepareAndSendUserOperation<'_> { builder::PrepareAndSendUserOperation::new(self) } - /**Get a user operation + /**Get user operation Gets a user operation by its hash. @@ -84201,7 +96309,7 @@ impl Client { pub fn get_user_operation(&self) -> builder::GetUserOperation<'_> { builder::GetUserOperation::new(self) } - /**Send a user operation + /**Send user operation Sends a user operation with a signature. The payload to sign must be the `userOpHash` field of the user operation. This hash should be signed directly (not using `personal_sign` or EIP-191 message hashing). @@ -84225,7 +96333,7 @@ impl Client { pub fn send_user_operation(&self) -> builder::SendUserOperation<'_> { builder::SendUserOperation::new(self) } - /**Create a swap quote + /**Create swap quote Create a swap quote, which includes the payload to sign as well as the transaction data needed to execute the swap. The developer is responsible for signing the payload and submitting the transaction to the network in order to execute the swap. @@ -84247,7 +96355,7 @@ impl Client { pub fn create_evm_swap_quote(&self) -> builder::CreateEvmSwapQuote<'_> { builder::CreateEvmSwapQuote::new(self) } - /**Get a price estimate for a swap + /**Get swap price estimate Get a price estimate for a swap between two tokens on an EVM network. @@ -84386,48 +96494,612 @@ impl Client { ### 3. One-Click Onramp URL with Quote **Required**: One-Click Onramp parameters + `paymentMethod`, `country`, `subdivision` - **Returns**: Complete pricing quote and one-click onramp URL. Both `session` and `quote` objects will be included in the response. + **Returns**: Complete pricing quote and one-click onramp URL. Both `session` and `quote` objects will be included in the response. + + **Note**: Only one of `paymentAmount` or `purchaseAmount` should be provided, not both. Providing both will result in an error. When `paymentAmount` is provided, the quote shows how much crypto the user will receive for the specified fiat amount (fee-inclusive). When `purchaseAmount` is provided, the quote shows how much fiat the user needs to pay for the specified crypto amount (fee-exclusive). + + Sends a `POST` request to `/v2/onramp/sessions` + + ```ignore + let response = client.create_onramp_session() + .body(body) + .send() + .await; + ```*/ + pub fn create_onramp_session(&self) -> builder::CreateOnrampSession<'_> { + builder::CreateOnrampSession::new(self) + } + /**List payment methods + + List payment methods linked to your entity. Payment methods represent external financial instruments that can be used as a target for transfers. The list will not include disabled or deleted payment methods. + + **Currently Supported Types:** + - `fedwire`: Domestic USD wire transfers + - `swift`: International wire transfers + - `sepa`: SEPA EUR transfers + + **Note:** Payment methods are created and verified through your linked CDP entity. Currently, fetching payment methods is only supported for Prime investment vehicles linked to CDP. + + Sends a `GET` request to `/v2/payment-methods` + + Arguments: + - `page_size`: The number of resources to return per page. + - `page_token`: The token for the next page of resources, if any. + ```ignore + let response = client.list_payment_methods() + .page_size(page_size) + .page_token(page_token) + .send() + .await; + ```*/ + pub fn list_payment_methods(&self) -> builder::ListPaymentMethods<'_> { + builder::ListPaymentMethods::new(self) + } + /**Get payment method + + Get details of a specific payment method by its ID. Returns 404 if the payment method is not found or not owned by the requesting entity. + + Sends a `GET` request to `/v2/payment-methods/{paymentMethodId}` + + Arguments: + - `payment_method_id`: The unique identifier of the payment method. + ```ignore + let response = client.get_payment_method() + .payment_method_id(payment_method_id) + .send() + .await; + ```*/ + pub fn get_payment_method(&self) -> builder::GetPaymentMethod<'_> { + builder::GetPaymentMethod::new(self) + } + /**List policies + + Lists the policies belonging to the developer's CDP Project. Use the `scope` parameter to filter the policies by scope. + The response is paginated, and by default, returns 20 policies per page. + + Sends a `GET` request to `/v2/policy-engine/policies` + + Arguments: + - `page_size`: The number of resources to return per page. + - `page_token`: The token for the next page of resources, if any. + - `scope`: The scope of the policies to return. If `project`, the response will include exactly one policy, which is the project-level policy. If `account`, the response will include all account-level policies for the developer's CDP Project. + ```ignore + let response = client.list_policies() + .page_size(page_size) + .page_token(page_token) + .scope(scope) + .send() + .await; + ```*/ + pub fn list_policies(&self) -> builder::ListPolicies<'_> { + builder::ListPolicies::new(self) + } + /**Create policy + + Create a policy that can be used to govern the behavior of accounts. + + Sends a `POST` request to `/v2/policy-engine/policies` + + Arguments: + - `x_idempotency_key`: An optional string request header for making requests safely retryable. + When included, duplicate requests with the same key will return identical responses. + Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + + - `body` + ```ignore + let response = client.create_policy() + .x_idempotency_key(x_idempotency_key) + .body(body) + .send() + .await; + ```*/ + pub fn create_policy(&self) -> builder::CreatePolicy<'_> { + builder::CreatePolicy::new(self) + } + /**Get policy by ID + + Get a policy by its ID. + + Sends a `GET` request to `/v2/policy-engine/policies/{policyId}` + + Arguments: + - `policy_id`: The ID of the policy to get. + ```ignore + let response = client.get_policy_by_id() + .policy_id(policy_id) + .send() + .await; + ```*/ + pub fn get_policy_by_id(&self) -> builder::GetPolicyById<'_> { + builder::GetPolicyById::new(self) + } + /**Update policy + + Updates a policy by its ID. This will have the effect of applying the updated policy to all accounts that are currently using it. + + Sends a `PUT` request to `/v2/policy-engine/policies/{policyId}` + + Arguments: + - `policy_id`: The ID of the policy to update. + - `x_idempotency_key`: An optional string request header for making requests safely retryable. + When included, duplicate requests with the same key will return identical responses. + Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + + - `body` + ```ignore + let response = client.update_policy() + .policy_id(policy_id) + .x_idempotency_key(x_idempotency_key) + .body(body) + .send() + .await; + ```*/ + pub fn update_policy(&self) -> builder::UpdatePolicy<'_> { + builder::UpdatePolicy::new(self) + } + /**Delete policy + + Delete a policy by its ID. This will have the effect of removing the policy from all accounts that are currently using it. + + Sends a `DELETE` request to `/v2/policy-engine/policies/{policyId}` + + Arguments: + - `policy_id`: The ID of the policy to delete. + - `x_idempotency_key`: An optional string request header for making requests safely retryable. + When included, duplicate requests with the same key will return identical responses. + Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + + ```ignore + let response = client.delete_policy() + .policy_id(policy_id) + .x_idempotency_key(x_idempotency_key) + .send() + .await; + ```*/ + pub fn delete_policy(&self) -> builder::DeletePolicy<'_> { + builder::DeletePolicy::new(self) + } + /**List Solana accounts + + Lists the Solana accounts belonging to the developer. + The response is paginated, and by default, returns 20 accounts per page. + + If a name is provided, the response will contain only the account with that name. + + Sends a `GET` request to `/v2/solana/accounts` + + Arguments: + - `page_size`: The number of resources to return per page. + - `page_token`: The token for the next page of resources, if any. + ```ignore + let response = client.list_solana_accounts() + .page_size(page_size) + .page_token(page_token) + .send() + .await; + ```*/ + pub fn list_solana_accounts(&self) -> builder::ListSolanaAccounts<'_> { + builder::ListSolanaAccounts::new(self) + } + /**Create Solana account + + Creates a new Solana account. + + Sends a `POST` request to `/v2/solana/accounts` + + Arguments: + - `x_idempotency_key`: An optional string request header for making requests safely retryable. + When included, duplicate requests with the same key will return identical responses. + Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + + - `x_wallet_auth`: A JWT signed using your Wallet Secret, encoded in base64. Refer to the + [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) + section of our Authentication docs for more details on how to generate your Wallet Token. + + - `body` + ```ignore + let response = client.create_solana_account() + .x_idempotency_key(x_idempotency_key) + .x_wallet_auth(x_wallet_auth) + .body(body) + .send() + .await; + ```*/ + pub fn create_solana_account(&self) -> builder::CreateSolanaAccount<'_> { + builder::CreateSolanaAccount::new(self) + } + /**Get Solana account by name + + Gets a Solana account by its name. + + Sends a `GET` request to `/v2/solana/accounts/by-name/{name}` + + Arguments: + - `name`: The name of the Solana account. + ```ignore + let response = client.get_solana_account_by_name() + .name(name) + .send() + .await; + ```*/ + pub fn get_solana_account_by_name(&self) -> builder::GetSolanaAccountByName<'_> { + builder::GetSolanaAccountByName::new(self) + } + /**Export Solana account by name + + Export an existing Solana account's private key by its name. It is important to store the private key in a secure place after it's exported. + + Sends a `POST` request to `/v2/solana/accounts/export/by-name/{name}` + + Arguments: + - `name`: The name of the Solana account. + - `x_idempotency_key`: An optional string request header for making requests safely retryable. + When included, duplicate requests with the same key will return identical responses. + Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + + - `x_wallet_auth`: A JWT signed using your Wallet Secret, encoded in base64. Refer to the + [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) + section of our Authentication docs for more details on how to generate your Wallet Token. + + - `body` + ```ignore + let response = client.export_solana_account_by_name() + .name(name) + .x_idempotency_key(x_idempotency_key) + .x_wallet_auth(x_wallet_auth) + .body(body) + .send() + .await; + ```*/ + pub fn export_solana_account_by_name(&self) -> builder::ExportSolanaAccountByName<'_> { + builder::ExportSolanaAccountByName::new(self) + } + /**Import Solana account + + Import an existing Solana account into the developer's CDP Project. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. + + Sends a `POST` request to `/v2/solana/accounts/import` + + Arguments: + - `x_idempotency_key`: An optional string request header for making requests safely retryable. + When included, duplicate requests with the same key will return identical responses. + Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + + - `x_wallet_auth`: A JWT signed using your Wallet Secret, encoded in base64. Refer to the + [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) + section of our Authentication docs for more details on how to generate your Wallet Token. + + - `body` + ```ignore + let response = client.import_solana_account() + .x_idempotency_key(x_idempotency_key) + .x_wallet_auth(x_wallet_auth) + .body(body) + .send() + .await; + ```*/ + pub fn import_solana_account(&self) -> builder::ImportSolanaAccount<'_> { + builder::ImportSolanaAccount::new(self) + } + /**Send Solana transaction + + Signs and sends a single Solana transaction using multiple Solana accounts. The transaction may contain contain several instructions, each of which may require signatures from different account keys. + + The transaction should be serialized into a byte array and base64 encoded. The API handles recent blockhash management and fee estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. + + **Transaction types** + + The following transaction types are supported: + * [Legacy transactions](https://solana.com/developers/guides/advanced/versions#current-transaction-versions) + * [Versioned transactions](https://solana.com/developers/guides/advanced/versions) + + **Instruction Batching** + + To batch multiple operations, include multiple instructions within a single transaction. All instructions within a transaction are executed atomically - if any instruction fails, the entire transaction fails and is rolled back. + + **Network Support** + + The following Solana networks are supported: + * `solana` - Solana Mainnet + * `solana-devnet` - Solana Devnet + + The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. + + Sends a `POST` request to `/v2/solana/accounts/send/transaction` + + Arguments: + - `x_idempotency_key`: An optional string request header for making requests safely retryable. + When included, duplicate requests with the same key will return identical responses. + Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + + - `x_wallet_auth`: A JWT signed using your Wallet Secret, encoded in base64. Refer to the + [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) + section of our Authentication docs for more details on how to generate your Wallet Token. + + - `body` + ```ignore + let response = client.send_solana_transaction() + .x_idempotency_key(x_idempotency_key) + .x_wallet_auth(x_wallet_auth) + .body(body) + .send() + .await; + ```*/ + pub fn send_solana_transaction(&self) -> builder::SendSolanaTransaction<'_> { + builder::SendSolanaTransaction::new(self) + } + /**Get Solana account by address + + Gets a Solana account by its address. + + Sends a `GET` request to `/v2/solana/accounts/{address}` + + Arguments: + - `address`: The base58 encoded address of the Solana account. + ```ignore + let response = client.get_solana_account() + .address(address) + .send() + .await; + ```*/ + pub fn get_solana_account(&self) -> builder::GetSolanaAccount<'_> { + builder::GetSolanaAccount::new(self) + } + /**Update Solana account + + Updates an existing Solana account. Use this to update the account's name or account-level policy. + + Sends a `PUT` request to `/v2/solana/accounts/{address}` + + Arguments: + - `address`: The base58 encoded address of the Solana account. + - `x_idempotency_key`: An optional string request header for making requests safely retryable. + When included, duplicate requests with the same key will return identical responses. + Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + + - `body` + ```ignore + let response = client.update_solana_account() + .address(address) + .x_idempotency_key(x_idempotency_key) + .body(body) + .send() + .await; + ```*/ + pub fn update_solana_account(&self) -> builder::UpdateSolanaAccount<'_> { + builder::UpdateSolanaAccount::new(self) + } + /**Export Solana account + + Export an existing Solana account's private key. It is important to store the private key in a secure place after it's exported. + + Sends a `POST` request to `/v2/solana/accounts/{address}/export` + + Arguments: + - `address`: The base58 encoded address of the Solana account. + - `x_idempotency_key`: An optional string request header for making requests safely retryable. + When included, duplicate requests with the same key will return identical responses. + Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + + - `x_wallet_auth`: A JWT signed using your Wallet Secret, encoded in base64. Refer to the + [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) + section of our Authentication docs for more details on how to generate your Wallet Token. + + - `body` + ```ignore + let response = client.export_solana_account() + .address(address) + .x_idempotency_key(x_idempotency_key) + .x_wallet_auth(x_wallet_auth) + .body(body) + .send() + .await; + ```*/ + pub fn export_solana_account(&self) -> builder::ExportSolanaAccount<'_> { + builder::ExportSolanaAccount::new(self) + } + /**Sign message + + Signs an arbitrary message with the given Solana account. + + **WARNING:** Never sign a message that you didn't generate, as it can be an arbitrary transaction. For example, it might send all of your funds to an attacker. + + Sends a `POST` request to `/v2/solana/accounts/{address}/sign/message` + + Arguments: + - `address`: The base58 encoded address of the Solana account. + - `x_idempotency_key`: An optional string request header for making requests safely retryable. + When included, duplicate requests with the same key will return identical responses. + Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + + - `x_wallet_auth`: A JWT signed using your Wallet Secret, encoded in base64. Refer to the + [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) + section of our Authentication docs for more details on how to generate your Wallet Token. + + - `body` + ```ignore + let response = client.sign_solana_message() + .address(address) + .x_idempotency_key(x_idempotency_key) + .x_wallet_auth(x_wallet_auth) + .body(body) + .send() + .await; + ```*/ + pub fn sign_solana_message(&self) -> builder::SignSolanaMessage<'_> { + builder::SignSolanaMessage::new(self) + } + /**Sign transaction + + Signs a transaction with the given Solana account. + The unsigned transaction should be serialized into a byte array and then encoded as base64. + + **Transaction types** + + The following transaction types are supported: + * [Legacy transactions](https://solana-labs.github.io/solana-web3.js/classes/Transaction.html) + * [Versioned transactions](https://solana-labs.github.io/solana-web3.js/classes/VersionedTransaction.html) + + The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. + + Sends a `POST` request to `/v2/solana/accounts/{address}/sign/transaction` + + Arguments: + - `address`: The base58 encoded address of the Solana account. + - `x_idempotency_key`: An optional string request header for making requests safely retryable. + When included, duplicate requests with the same key will return identical responses. + Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + + - `x_wallet_auth`: A JWT signed using your Wallet Secret, encoded in base64. Refer to the + [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) + section of our Authentication docs for more details on how to generate your Wallet Token. + + - `body` + ```ignore + let response = client.sign_solana_transaction() + .address(address) + .x_idempotency_key(x_idempotency_key) + .x_wallet_auth(x_wallet_auth) + .body(body) + .send() + .await; + ```*/ + pub fn sign_solana_transaction(&self) -> builder::SignSolanaTransaction<'_> { + builder::SignSolanaTransaction::new(self) + } + /**Request funds on Solana devnet + + Request funds from the CDP Faucet on Solana devnet. + + Faucets are available for SOL, USDC, and CBTUSD. + + To prevent abuse, we enforce rate limits within a rolling 24-hour window to control the amount of funds that can be requested. + These limits are applied at both the CDP Project level and the blockchain address level. + A single blockchain address cannot exceed the specified limits, even if multiple users submit requests to the same address. + + | Token | Amount per Faucet Request |Rolling 24-hour window Rate Limits| + |:-----: |:-------------------------:|:--------------------------------:| + | SOL | 0.00125 SOL | 0.0125 SOL | + | USDC | 1 USDC | 10 USDC | + | CBTUSD | 1 CBTUSD | 10 CBTUSD | + + + Sends a `POST` request to `/v2/solana/faucet` + + ```ignore + let response = client.request_solana_faucet() + .body(body) + .send() + .await; + ```*/ + pub fn request_solana_faucet(&self) -> builder::RequestSolanaFaucet<'_> { + builder::RequestSolanaFaucet::new(self) + } + /**List Solana token balances + + Lists the token balances of a Solana address on a given network. The balances include SPL tokens and the native SOL token. The response is paginated, and by default, returns 20 balances per page. - **Note**: Only one of `paymentAmount` or `purchaseAmount` should be provided, not both. Providing both will result in an error. When `paymentAmount` is provided, the quote shows how much crypto the user will receive for the specified fiat amount (fee-inclusive). When `purchaseAmount` is provided, the quote shows how much fiat the user needs to pay for the specified crypto amount (fee-exclusive). + **Note:** This endpoint is still under development and does not yet provide strong availability or freshness guarantees. Freshness and availability of new token balances will improve over the coming weeks. - Sends a `POST` request to `/v2/onramp/sessions` + Sends a `GET` request to `/v2/solana/token-balances/{network}/{address}` + Arguments: + - `network`: The human-readable network name to get the balances for. + - `address`: The base58 encoded Solana address to get balances for. + - `page_size`: The number of balances to return per page. + - `page_token`: The token for the next page of balances. Will be empty if there are no more balances to fetch. ```ignore - let response = client.create_onramp_session() - .body(body) + let response = client.list_solana_token_balances() + .network(network) + .address(address) + .page_size(page_size) + .page_token(page_token) .send() .await; ```*/ - pub fn create_onramp_session(&self) -> builder::CreateOnrampSession<'_> { - builder::CreateOnrampSession::new(self) + pub fn list_solana_token_balances(&self) -> builder::ListSolanaTokenBalances<'_> { + builder::ListSolanaTokenBalances::new(self) } - /**List policies + /**List transfers - Lists the policies belonging to the developer's CDP Project. Use the `scope` parameter to filter the policies by scope. - The response is paginated, and by default, returns 20 policies per page. + List transfers for your organization. Use this to view and monitor your transfer activity. - Sends a `GET` request to `/v2/policy-engine/policies` + **Status Filtering**: Filter by specific status to efficiently manage transfers: + * `?status=processing` - Monitor active transfers. + * `?status=quoted` - Find transfers awaiting execution. + * `?status=failed` - Review failed transfers for troubleshooting. + * `?status=completed` - Find completed transfers. + + **Account Filtering**: Filter by account ID to find transfers involving a specific account: + * `?accountId=` - All transfers where the account is either source or target (OR semantics). + * `?sourceAccountId=` - Only transfers where the account is the source (outbound). + * `?targetAccountId=` - Only transfers where the account is the target (inbound). + Providing `accountId` together with `sourceAccountId` or `targetAccountId` is a validation error and returns HTTP 400. + + **Date Range Filtering**: Filter by creation or last-updated time for reconciliation: + * `?createdAfter=2026-01-01T00:00:00Z&createdBefore=2026-01-31T23:59:59Z` - Transfers created within a date range. + * `?updatedAfter=2026-01-01T00:00:00Z` - Transfers updated since a given time. Useful for incremental sync. + + **Asset Filtering**: Filter by source or target asset symbol: + * `?sourceAsset=usd` - Transfers funded from a USD account. + * `?targetAsset=usdc` - Transfers delivering USDC to the target. + + **Other Filters**: + * `?sourceAddress=0x...` - Transfers from a specific on-chain source address. + * `?targetAddress=0x...` - Transfers to a specific on-chain destination address. + * `?targetEmail=user@example.com` - Transfers to a specific email recipient. + * `?transferId=transfer_...` - Look up a single transfer by ID; bypasses pagination. + + Sends a `GET` request to `/v2/transfers` Arguments: + - `account_id`: Filter transfers by account ID. Returns transfers where the specified account is either the source or target (OR semantics). Cannot be combined with `sourceAccountId` or `targetAccountId`. + - `created_after`: Filter transfers to those created at or after this datetime (inclusive). ISO 8601 format. + - `created_before`: Filter transfers to those created at or before this datetime (inclusive). ISO 8601 format. - `page_size`: The number of resources to return per page. - `page_token`: The token for the next page of resources, if any. - - `scope`: The scope of the policies to return. If `project`, the response will include exactly one policy, which is the project-level policy. If `account`, the response will include all account-level policies for the developer's CDP Project. + - `source_account_id`: Filter transfers by source account ID. Returns only transfers where the specified account is the source. Cannot be combined with `accountId`. + - `source_address`: Filter transfers by the on-chain address of the source. + - `source_asset`: Filter transfers by source asset symbol (e.g., `usd`, `usdc`). + - `status`: Filter transfers by status. Useful for building dashboards, monitoring active transfers, or finding transfers needing action. + - `target_account_id`: Filter transfers by target account ID. Returns only transfers where the specified account is the target. Cannot be combined with `accountId`. + - `target_address`: Filter transfers by the on-chain destination address of the target. + - `target_asset`: Filter transfers by target asset symbol (e.g., `usdc`, `eth`). + - `target_email`: Filter transfers by the email address of the target recipient. + - `transfer_id`: Filter to a specific transfer by ID. When provided, returns only the matching transfer and bypasses pagination. + - `updated_after`: Filter transfers to those updated at or after this datetime (inclusive). ISO 8601 format. Useful for incremental sync — poll for transfers that changed state since your last check. + - `updated_before`: Filter transfers to those updated at or before this datetime (inclusive). ISO 8601 format. ```ignore - let response = client.list_policies() + let response = client.list_transfers() + .account_id(account_id) + .created_after(created_after) + .created_before(created_before) .page_size(page_size) .page_token(page_token) - .scope(scope) + .source_account_id(source_account_id) + .source_address(source_address) + .source_asset(source_asset) + .status(status) + .target_account_id(target_account_id) + .target_address(target_address) + .target_asset(target_asset) + .target_email(target_email) + .transfer_id(transfer_id) + .updated_after(updated_after) + .updated_before(updated_before) .send() .await; ```*/ - pub fn list_policies(&self) -> builder::ListPolicies<'_> { - builder::ListPolicies::new(self) + pub fn list_transfers(&self) -> builder::ListTransfers<'_> { + builder::ListTransfers::new(self) } - /**Create a policy + /**Create transfer - Create a policy that can be used to govern the behavior of accounts. + Create a new transfer to move funds from a source to a target. + All transfers first transition to `quoted`. If `execute: false`, the transfer stays quoted until you call `/v2/transfers/{transferId}/execute`. + If `execute: true`, quoted status emits momentarily before the transfer moves to `processing`, where execution proceeds. Subscribe to the transfers webhook to follow progress in real time instead of polling. - Sends a `POST` request to `/v2/policy-engine/policies` + Sends a `POST` request to `/v2/transfers` Arguments: - `x_idempotency_key`: An optional string request header for making requests safely retryable. @@ -84436,678 +97108,1524 @@ impl Client { - `body` ```ignore - let response = client.create_policy() + let response = client.create_transfer() .x_idempotency_key(x_idempotency_key) .body(body) .send() .await; ```*/ - pub fn create_policy(&self) -> builder::CreatePolicy<'_> { - builder::CreatePolicy::new(self) + pub fn create_transfer(&self) -> builder::CreateTransfer<'_> { + builder::CreateTransfer::new(self) } - /**Get a policy by ID + /**Get transfer - Get a policy by its ID. + Get a transfer by its ID. - Sends a `GET` request to `/v2/policy-engine/policies/{policyId}` + Sends a `GET` request to `/v2/transfers/{transferId}` Arguments: - - `policy_id`: The ID of the policy to get. + - `transfer_id`: The unique identifier of the transfer. ```ignore - let response = client.get_policy_by_id() - .policy_id(policy_id) + let response = client.get_transfer_by_id() + .transfer_id(transfer_id) .send() .await; ```*/ - pub fn get_policy_by_id(&self) -> builder::GetPolicyById<'_> { - builder::GetPolicyById::new(self) + pub fn get_transfer_by_id(&self) -> builder::GetTransferById<'_> { + builder::GetTransferById::new(self) } - /**Update a policy + /**Execute transfer - Updates a policy by its ID. This will have the effect of applying the updated policy to all accounts that are currently using it. + Executes a transfer which was created using the Create a transfer endpoint. - Sends a `PUT` request to `/v2/policy-engine/policies/{policyId}` + Sends a `POST` request to `/v2/transfers/{transferId}/execute` Arguments: - - `policy_id`: The ID of the policy to update. + - `transfer_id`: The ID of the transfer. - `x_idempotency_key`: An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. - - `body` ```ignore - let response = client.update_policy() - .policy_id(policy_id) + let response = client.execute_fund_transfer() + .transfer_id(transfer_id) .x_idempotency_key(x_idempotency_key) - .body(body) .send() .await; ```*/ - pub fn update_policy(&self) -> builder::UpdatePolicy<'_> { - builder::UpdatePolicy::new(self) + pub fn execute_fund_transfer(&self) -> builder::ExecuteFundTransfer<'_> { + builder::ExecuteFundTransfer::new(self) } - /**Delete a policy + /**Submit deposit travel rule information - Delete a policy by its ID. This will have the effect of removing the policy from all accounts that are currently using it. + Submit travel rule information for a deposit transfer held pending compliance review. - Sends a `DELETE` request to `/v2/policy-engine/policies/{policyId}` + Required fields vary by jurisdiction and may include originator name, address, date of birth, personal ID, and VASP information. + + If the submitted information satisfies all jurisdictional requirements, `status` will be `completed` and the transfer will proceed. Otherwise, `status` will be `incomplete` and `missingFields` will indicate which fields still need to be provided. + + Sends a `POST` request to `/v2/transfers/{transferId}/travel-rule` Arguments: - - `policy_id`: The ID of the policy to delete. + - `transfer_id`: The unique identifier of the transfer. - `x_idempotency_key`: An optional string request header for making requests safely retryable. When included, duplicate requests with the same key will return identical responses. Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + - `body` ```ignore - let response = client.delete_policy() - .policy_id(policy_id) + let response = client.submit_deposit_travel_rule() + .transfer_id(transfer_id) .x_idempotency_key(x_idempotency_key) + .body(body) .send() .await; ```*/ - pub fn delete_policy(&self) -> builder::DeletePolicy<'_> { - builder::DeletePolicy::new(self) + pub fn submit_deposit_travel_rule(&self) -> builder::SubmitDepositTravelRule<'_> { + builder::SubmitDepositTravelRule::new(self) } - /**List Solana accounts or get account by name - - Lists the Solana accounts belonging to the developer. - The response is paginated, and by default, returns 20 accounts per page. + /**Handle MCP JSON-RPC request - If a name is provided, the response will contain only the account with that name. + Handles JSON-RPC requests for the Model Context Protocol (MCP). Supports MCP methods for discovering x402 payment resources and tools. - Sends a `GET` request to `/v2/solana/accounts` + Sends a `POST` request to `/v2/x402/discovery/mcp` - Arguments: - - `page_size`: The number of resources to return per page. - - `page_token`: The token for the next page of resources, if any. ```ignore - let response = client.list_solana_accounts() - .page_size(page_size) - .page_token(page_token) + let response = client.post_x402_discovery_mcp() + .body(body) .send() .await; ```*/ - pub fn list_solana_accounts(&self) -> builder::ListSolanaAccounts<'_> { - builder::ListSolanaAccounts::new(self) + pub fn post_x402_discovery_mcp(&self) -> builder::PostX402DiscoveryMcp<'_> { + builder::PostX402DiscoveryMcp::new(self) } - /**Create a Solana account + /**List merchant discovery info - Creates a new Solana account. + Gets x402 merchant discovery information for a given merchant payment address. + This endpoint returns all active x402 resources associated with the specified `payTo` address, allowing clients to discover what payment-gated resources a merchant exposes and their corresponding payment requirements. + The response is paginated, and by default, returns 20 items per page. - Sends a `POST` request to `/v2/solana/accounts` + Sends a `GET` request to `/v2/x402/discovery/merchant` Arguments: - - `x_idempotency_key`: An optional string request header for making requests safely retryable. - When included, duplicate requests with the same key will return identical responses. - Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. - - - `x_wallet_auth`: A JWT signed using your Wallet Secret, encoded in base64. Refer to the - [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) - section of our Authentication docs for more details on how to generate your Wallet Token. - - - `body` + - `limit`: The number of resources to return per page. + - `offset`: The offset of the first resource to return. + - `pay_to`: The merchant's payment address to look up. + This is the onchain address that payment requirements route funds to. ```ignore - let response = client.create_solana_account() - .x_idempotency_key(x_idempotency_key) - .x_wallet_auth(x_wallet_auth) - .body(body) + let response = client.list_x402_discovery_merchant() + .limit(limit) + .offset(offset) + .pay_to(pay_to) .send() .await; ```*/ - pub fn create_solana_account(&self) -> builder::CreateSolanaAccount<'_> { - builder::CreateSolanaAccount::new(self) + pub fn list_x402_discovery_merchant(&self) -> builder::ListX402DiscoveryMerchant<'_> { + builder::ListX402DiscoveryMerchant::new(self) } - /**Get a Solana account by name + /**List x402 resources - Gets a Solana account by its name. + Lists all active discovered x402 resources. + This endpoint returns resources that have been discovered and cached by the x402 facilitator, including their payment requirements and metadata. + The response is paginated, and by default, returns 100 items per page. - Sends a `GET` request to `/v2/solana/accounts/by-name/{name}` + Sends a `GET` request to `/v2/x402/discovery/resources` Arguments: - - `name`: The name of the Solana account. + - `limit`: The number of discovered x402 resources to return per page. + - `offset`: The offset of the first discovered x402 resource to return. + - `type_`: Filter by protocol type (e.g., "http", "mcp"). + Currently, the only supported protocol type is "http". ```ignore - let response = client.get_solana_account_by_name() - .name(name) + let response = client.list_x402_discovery_resources() + .limit(limit) + .offset(offset) + .type_(type_) .send() .await; ```*/ - pub fn get_solana_account_by_name(&self) -> builder::GetSolanaAccountByName<'_> { - builder::GetSolanaAccountByName::new(self) + pub fn list_x402_discovery_resources(&self) -> builder::ListX402DiscoveryResources<'_> { + builder::ListX402DiscoveryResources::new(self) } - /**Export a Solana account by name + /**Search x402 resources - Export an existing Solana account's private key by its name. It is important to store the private key in a secure place after it's exported. + Searches for active x402 resources using a text query and optional filters. + Supports both text-based and vector-based search depending on availability. Results are sorted by relevance and quality score. + Legacy network names (e.g., `base`, `base-sepolia`, `solana`) are automatically normalized to their CAIP-2 equivalents. + The response is limited to 20 items per request. If more results exist, `partialResults` will be `true`. - Sends a `POST` request to `/v2/solana/accounts/export/by-name/{name}` + Sends a `GET` request to `/v2/x402/discovery/search` Arguments: - - `name`: The name of the Solana account. - - `x_idempotency_key`: An optional string request header for making requests safely retryable. - When included, duplicate requests with the same key will return identical responses. - Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. - - - `x_wallet_auth`: A JWT signed using your Wallet Secret, encoded in base64. Refer to the - [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) - section of our Authentication docs for more details on how to generate your Wallet Token. - - - `body` + - `asset`: Filter results by asset address. + For EVM networks, provide a 0x-prefixed EVM address. For Solana networks, provide a base58-encoded address. + Matching is case-insensitive. + - `extensions`: Filter results to resources that support the specified protocol extensions. Can be specified multiple times to filter by multiple extensions. + - `limit`: Maximum number of resources to return. Must be a positive integer no greater than 20. + Defaults to 20. + - `max_usd_price`: Filter results to resources with a USD price at or below this value. + - `network`: Filter results by network in CAIP-2 format (e.g., `eip155:8453`) or legacy name (e.g., `base`, `base-sepolia`, `solana`). + Legacy names are normalized to their CAIP-2 equivalents before filtering. + - `pay_to`: Filter results by the merchant's payment address. + For EVM networks, provide a 0x-prefixed EVM address. For Solana networks, provide a base58-encoded address. + - `query`: Full-text or semantic search query to find matching resources. + - `scheme`: Filter results by payment scheme (e.g., `exact`). + - `url_substring`: Filter results to resources whose URL contains this value (case-insensitive substring match against the resource URL). + Useful for narrowing results to a specific domain, subdomain, or path segment. Combine with `query` to perform semantic search restricted to a URL subset. + Tip: include enough of the URL to disambiguate (e.g. `api.example.com` rather than `example`) — a short substring may also match resources whose path contains the same string. ```ignore - let response = client.export_solana_account_by_name() - .name(name) - .x_idempotency_key(x_idempotency_key) - .x_wallet_auth(x_wallet_auth) - .body(body) + let response = client.search_x402_resources() + .asset(asset) + .extensions(extensions) + .limit(limit) + .max_usd_price(max_usd_price) + .network(network) + .pay_to(pay_to) + .query(query) + .scheme(scheme) + .url_substring(url_substring) .send() .await; ```*/ - pub fn export_solana_account_by_name(&self) -> builder::ExportSolanaAccountByName<'_> { - builder::ExportSolanaAccountByName::new(self) + pub fn search_x402_resources(&self) -> builder::SearchX402Resources<'_> { + builder::SearchX402Resources::new(self) } - /**Import a Solana account - - Import an existing Solana account into the developer's CDP Project. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. - - Sends a `POST` request to `/v2/solana/accounts/import` + /**Settle payment - Arguments: - - `x_idempotency_key`: An optional string request header for making requests safely retryable. - When included, duplicate requests with the same key will return identical responses. - Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + Settle an x402 protocol payment with a specific scheme and network. - - `x_wallet_auth`: A JWT signed using your Wallet Secret, encoded in base64. Refer to the - [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) - section of our Authentication docs for more details on how to generate your Wallet Token. + Sends a `POST` request to `/v2/x402/settle` - - `body` ```ignore - let response = client.import_solana_account() - .x_idempotency_key(x_idempotency_key) - .x_wallet_auth(x_wallet_auth) + let response = client.settle_x402_payment() .body(body) .send() .await; ```*/ - pub fn import_solana_account(&self) -> builder::ImportSolanaAccount<'_> { - builder::ImportSolanaAccount::new(self) + pub fn settle_x402_payment(&self) -> builder::SettleX402Payment<'_> { + builder::SettleX402Payment::new(self) } - /**Send a Solana transaction - - Signs and sends a single Solana transaction using multiple Solana accounts. The transaction may contain contain several instructions, each of which may require signatures from different account keys. - - The transaction should be serialized into a byte array and base64 encoded. The API handles recent blockhash management and fee estimation, leaving the developer to provide only the minimal set of fields necessary to send the transaction. - - **Transaction types** - - The following transaction types are supported: - * [Legacy transactions](https://solana.com/developers/guides/advanced/versions#current-transaction-versions) - * [Versioned transactions](https://solana.com/developers/guides/advanced/versions) - - **Instruction Batching** - - To batch multiple operations, include multiple instructions within a single transaction. All instructions within a transaction are executed atomically - if any instruction fails, the entire transaction fails and is rolled back. - - **Network Support** - - The following Solana networks are supported: - * `solana` - Solana Mainnet - * `solana-devnet` - Solana Devnet - - The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. - - Sends a `POST` request to `/v2/solana/accounts/send/transaction` + /**Get supported payment schemes and networks - Arguments: - - `x_idempotency_key`: An optional string request header for making requests safely retryable. - When included, duplicate requests with the same key will return identical responses. - Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + Get the supported x402 protocol payment schemes and networks that the facilitator is able to verify and settle payments for. - - `x_wallet_auth`: A JWT signed using your Wallet Secret, encoded in base64. Refer to the - [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) - section of our Authentication docs for more details on how to generate your Wallet Token. + Sends a `GET` request to `/v2/x402/supported` - - `body` ```ignore - let response = client.send_solana_transaction() - .x_idempotency_key(x_idempotency_key) - .x_wallet_auth(x_wallet_auth) - .body(body) + let response = client.supported_x402_payment_kinds() .send() .await; ```*/ - pub fn send_solana_transaction(&self) -> builder::SendSolanaTransaction<'_> { - builder::SendSolanaTransaction::new(self) + pub fn supported_x402_payment_kinds(&self) -> builder::SupportedX402PaymentKinds<'_> { + builder::SupportedX402PaymentKinds::new(self) } - /**Get a Solana account by address + /**Verify payment - Gets a Solana account by its address. + Verify an x402 protocol payment with a specific scheme and network. - Sends a `GET` request to `/v2/solana/accounts/{address}` + Sends a `POST` request to `/v2/x402/verify` - Arguments: - - `address`: The base58 encoded address of the Solana account. ```ignore - let response = client.get_solana_account() - .address(address) + let response = client.verify_x402_payment() + .body(body) .send() .await; ```*/ - pub fn get_solana_account(&self) -> builder::GetSolanaAccount<'_> { - builder::GetSolanaAccount::new(self) + pub fn verify_x402_payment(&self) -> builder::VerifyX402Payment<'_> { + builder::VerifyX402Payment::new(self) + } +} +/// Types for composing operation parameters. +#[allow(clippy::all)] +pub mod builder { + use super::types; + #[allow(unused_imports)] + use super::{ + encode_path, ByteStream, ClientHooks, ClientInfo, Error, OperationInfo, RequestBuilderExt, + ResponseValue, + }; + /**Builder for [`Client::list_foundation_accounts`] + + [`Client::list_foundation_accounts`]: super::Client::list_foundation_accounts*/ + #[derive(Debug, Clone)] + pub struct ListFoundationAccounts<'a> { + client: &'a super::Client, + page_size: Result, String>, + page_token: Result, String>, + type_: Result, String>, + } + impl<'a> ListFoundationAccounts<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + page_size: Ok(None), + page_token: Ok(None), + type_: Ok(None), + } + } + pub fn page_size(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.page_size = value + .try_into() + .map(Some) + .map_err(|_| "conversion to `i64` for page_size failed".to_string()); + self + } + pub fn page_token(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.page_token = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for page_token failed".to_string() + }); + self + } + pub fn type_(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.type_ = value + .try_into() + .map(Some) + .map_err(|_| "conversion to `AccountType` for type_ failed".to_string()); + self + } + ///Sends a `GET` request to `/v2/accounts` + pub async fn send( + self, + ) -> Result, Error> + { + let Self { + client, + page_size, + page_token, + type_, + } = self; + let page_size = page_size.map_err(Error::InvalidRequest)?; + let page_token = page_token.map_err(Error::InvalidRequest)?; + let type_ = type_.map_err(Error::InvalidRequest)?; + let url = format!("{}/v2/accounts", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + #[allow(unused_mut)] + let mut request = client + .client + .get(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .query(&progenitor_middleware_client::QueryParam::new( + "pageSize", &page_size, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "pageToken", + &page_token, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "type", &type_, + )) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "list_foundation_accounts", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 200u16 => ResponseValue::from_response::(response).await, + 400u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + _ => Err(Error::UnexpectedResponse(response)), + } + } + } + /**Builder for [`Client::create_foundation_account`] + + [`Client::create_foundation_account`]: super::Client::create_foundation_account*/ + #[derive(Debug, Clone)] + pub struct CreateFoundationAccount<'a> { + client: &'a super::Client, + x_idempotency_key: Result, String>, + body: Result, + } + impl<'a> CreateFoundationAccount<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + x_idempotency_key: Ok(None), + body: Ok(::std::default::Default::default()), + } + } + pub fn x_idempotency_key(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.x_idempotency_key = value + .try_into() + .map(Some) + .map_err(|_| { + "conversion to `CreateFoundationAccountXIdempotencyKey` for x_idempotency_key failed" + .to_string() + }); + self + } + pub fn body(mut self, value: V) -> Self + where + V: std::convert::TryInto, + >::Error: std::fmt::Display, + { + self.body = value.try_into().map(From::from).map_err(|s| { + format!( + "conversion to `CreateAccountRequest` for body failed: {}", + s + ) + }); + self + } + pub fn body_map(mut self, f: F) -> Self + where + F: std::ops::FnOnce( + types::builder::CreateAccountRequest, + ) -> types::builder::CreateAccountRequest, + { + self.body = self.body.map(f); + self + } + ///Sends a `POST` request to `/v2/accounts` + pub async fn send(self) -> Result, Error> { + let Self { + client, + x_idempotency_key, + body, + } = self; + let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; + let body = body + .and_then(|v| types::CreateAccountRequest::try_from(v).map_err(|e| e.to_string())) + .map_err(Error::InvalidRequest)?; + let url = format!("{}/v2/accounts", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(2usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + if let Some(value) = x_idempotency_key { + header_map.append("X-Idempotency-Key", value.to_string().try_into()?); + } + #[allow(unused_mut)] + let mut request = client + .client + .post(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .json(&body) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "create_foundation_account", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 200u16 => ResponseValue::from_response::(response).await, + 400u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 422u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 503u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + _ => Err(Error::UnexpectedResponse(response)), + } + } + } + /**Builder for [`Client::get_foundation_account_by_id`] + + [`Client::get_foundation_account_by_id`]: super::Client::get_foundation_account_by_id*/ + #[derive(Debug, Clone)] + pub struct GetFoundationAccountById<'a> { + client: &'a super::Client, + account_id: Result, + } + impl<'a> GetFoundationAccountById<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + account_id: Err("account_id was not initialized".to_string()), + } + } + pub fn account_id(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.account_id = value + .try_into() + .map_err(|_| "conversion to `AccountId` for account_id failed".to_string()); + self + } + ///Sends a `GET` request to `/v2/accounts/{accountId}` + pub async fn send(self) -> Result, Error> { + let Self { client, account_id } = self; + let account_id = account_id.map_err(Error::InvalidRequest)?; + let url = format!( + "{}/v2/accounts/{}", + client.baseurl, + encode_path(&account_id.to_string()), + ); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + #[allow(unused_mut)] + let mut request = client + .client + .get(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "get_foundation_account_by_id", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 200u16 => ResponseValue::from_response::(response).await, + 400u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 404u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + _ => Err(Error::UnexpectedResponse(response)), + } + } } - /**Update a Solana account - - Updates an existing Solana account. Use this to update the account's name or account-level policy. - - Sends a `PUT` request to `/v2/solana/accounts/{address}` - - Arguments: - - `address`: The base58 encoded address of the Solana account. - - `x_idempotency_key`: An optional string request header for making requests safely retryable. - When included, duplicate requests with the same key will return identical responses. - Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. + /**Builder for [`Client::list_balances`] - - `body` - ```ignore - let response = client.update_solana_account() - .address(address) - .x_idempotency_key(x_idempotency_key) - .body(body) - .send() - .await; - ```*/ - pub fn update_solana_account(&self) -> builder::UpdateSolanaAccount<'_> { - builder::UpdateSolanaAccount::new(self) + [`Client::list_balances`]: super::Client::list_balances*/ + #[derive(Debug, Clone)] + pub struct ListBalances<'a> { + client: &'a super::Client, + account_id: Result, + page_size: Result, String>, + page_token: Result, String>, } - /**Export an Solana account - - Export an existing Solana account's private key. It is important to store the private key in a secure place after it's exported. - - Sends a `POST` request to `/v2/solana/accounts/{address}/export` - - Arguments: - - `address`: The base58 encoded address of the Solana account. - - `x_idempotency_key`: An optional string request header for making requests safely retryable. - When included, duplicate requests with the same key will return identical responses. - Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. - - - `x_wallet_auth`: A JWT signed using your Wallet Secret, encoded in base64. Refer to the - [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) - section of our Authentication docs for more details on how to generate your Wallet Token. - - - `body` - ```ignore - let response = client.export_solana_account() - .address(address) - .x_idempotency_key(x_idempotency_key) - .x_wallet_auth(x_wallet_auth) - .body(body) - .send() - .await; - ```*/ - pub fn export_solana_account(&self) -> builder::ExportSolanaAccount<'_> { - builder::ExportSolanaAccount::new(self) + impl<'a> ListBalances<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + account_id: Err("account_id was not initialized".to_string()), + page_size: Ok(None), + page_token: Ok(None), + } + } + pub fn account_id(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.account_id = value + .try_into() + .map_err(|_| "conversion to `AccountId` for account_id failed".to_string()); + self + } + pub fn page_size(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.page_size = value + .try_into() + .map(Some) + .map_err(|_| "conversion to `i64` for page_size failed".to_string()); + self + } + pub fn page_token(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.page_token = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for page_token failed".to_string() + }); + self + } + ///Sends a `GET` request to `/v2/accounts/{accountId}/balances` + pub async fn send( + self, + ) -> Result, Error> { + let Self { + client, + account_id, + page_size, + page_token, + } = self; + let account_id = account_id.map_err(Error::InvalidRequest)?; + let page_size = page_size.map_err(Error::InvalidRequest)?; + let page_token = page_token.map_err(Error::InvalidRequest)?; + let url = format!( + "{}/v2/accounts/{}/balances", + client.baseurl, + encode_path(&account_id.to_string()), + ); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + #[allow(unused_mut)] + let mut request = client + .client + .get(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .query(&progenitor_middleware_client::QueryParam::new( + "pageSize", &page_size, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "pageToken", + &page_token, + )) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "list_balances", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 200u16 => ResponseValue::from_response::(response).await, + 400u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 401u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 404u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 500u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 503u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + _ => Err(Error::UnexpectedResponse(response)), + } + } } - /**Sign a message - - Signs an arbitrary message with the given Solana account. - - **WARNING:** Never sign a message that you didn't generate, as it can be an arbitrary transaction. For example, it might send all of your funds to an attacker. - - Sends a `POST` request to `/v2/solana/accounts/{address}/sign/message` + /**Builder for [`Client::get_balance_by_asset`] - Arguments: - - `address`: The base58 encoded address of the Solana account. - - `x_idempotency_key`: An optional string request header for making requests safely retryable. - When included, duplicate requests with the same key will return identical responses. - Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. - - - `x_wallet_auth`: A JWT signed using your Wallet Secret, encoded in base64. Refer to the - [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) - section of our Authentication docs for more details on how to generate your Wallet Token. - - - `body` - ```ignore - let response = client.sign_solana_message() - .address(address) - .x_idempotency_key(x_idempotency_key) - .x_wallet_auth(x_wallet_auth) - .body(body) - .send() - .await; - ```*/ - pub fn sign_solana_message(&self) -> builder::SignSolanaMessage<'_> { - builder::SignSolanaMessage::new(self) + [`Client::get_balance_by_asset`]: super::Client::get_balance_by_asset*/ + #[derive(Debug, Clone)] + pub struct GetBalanceByAsset<'a> { + client: &'a super::Client, + account_id: Result, + asset: Result, } - /**Sign a transaction - - Signs a transaction with the given Solana account. - The unsigned transaction should be serialized into a byte array and then encoded as base64. - - **Transaction types** - - The following transaction types are supported: - * [Legacy transactions](https://solana-labs.github.io/solana-web3.js/classes/Transaction.html) - * [Versioned transactions](https://solana-labs.github.io/solana-web3.js/classes/VersionedTransaction.html) - - The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. - - Sends a `POST` request to `/v2/solana/accounts/{address}/sign/transaction` - - Arguments: - - `address`: The base58 encoded address of the Solana account. - - `x_idempotency_key`: An optional string request header for making requests safely retryable. - When included, duplicate requests with the same key will return identical responses. - Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/idempotency) for more information on using idempotency keys. - - - `x_wallet_auth`: A JWT signed using your Wallet Secret, encoded in base64. Refer to the - [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) - section of our Authentication docs for more details on how to generate your Wallet Token. - - - `body` - ```ignore - let response = client.sign_solana_transaction() - .address(address) - .x_idempotency_key(x_idempotency_key) - .x_wallet_auth(x_wallet_auth) - .body(body) - .send() - .await; - ```*/ - pub fn sign_solana_transaction(&self) -> builder::SignSolanaTransaction<'_> { - builder::SignSolanaTransaction::new(self) + impl<'a> GetBalanceByAsset<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + account_id: Err("account_id was not initialized".to_string()), + asset: Err("asset was not initialized".to_string()), + } + } + pub fn account_id(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.account_id = value + .try_into() + .map_err(|_| "conversion to `AccountId` for account_id failed".to_string()); + self + } + pub fn asset(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.asset = value + .try_into() + .map_err(|_| "conversion to `Asset` for asset failed".to_string()); + self + } + ///Sends a `GET` request to `/v2/accounts/{accountId}/balances/{asset}` + pub async fn send(self) -> Result, Error> { + let Self { + client, + account_id, + asset, + } = self; + let account_id = account_id.map_err(Error::InvalidRequest)?; + let asset = asset.map_err(Error::InvalidRequest)?; + let url = format!( + "{}/v2/accounts/{}/balances/{}", + client.baseurl, + encode_path(&account_id.to_string()), + encode_path(&asset.to_string()), + ); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + #[allow(unused_mut)] + let mut request = client + .client + .get(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "get_balance_by_asset", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 200u16 => ResponseValue::from_response::(response).await, + 400u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 401u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 404u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 500u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 503u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + _ => Err(Error::UnexpectedResponse(response)), + } + } } - /**Request funds on Solana devnet - - Request funds from the CDP Faucet on Solana devnet. - - Faucets are available for SOL, USDC, and CBTUSD. - - To prevent abuse, we enforce rate limits within a rolling 24-hour window to control the amount of funds that can be requested. - These limits are applied at both the CDP Project level and the blockchain address level. - A single blockchain address cannot exceed the specified limits, even if multiple users submit requests to the same address. - - | Token | Amount per Faucet Request |Rolling 24-hour window Rate Limits| - |:-----: |:-------------------------:|:--------------------------------:| - | SOL | 0.00125 SOL | 0.0125 SOL | - | USDC | 1 USDC | 10 USDC | - | CBTUSD | 1 CBTUSD | 10 CBTUSD | - - - Sends a `POST` request to `/v2/solana/faucet` + /**Builder for [`Client::list_data_token_balances`] - ```ignore - let response = client.request_solana_faucet() - .body(body) - .send() - .await; - ```*/ - pub fn request_solana_faucet(&self) -> builder::RequestSolanaFaucet<'_> { - builder::RequestSolanaFaucet::new(self) + [`Client::list_data_token_balances`]: super::Client::list_data_token_balances*/ + #[derive(Debug, Clone)] + pub struct ListDataTokenBalances<'a> { + client: &'a super::Client, + network: Result, + address: Result, + page_size: Result, String>, + page_token: Result, String>, } - /**List Solana token balances - - Lists the token balances of a Solana address on a given network. The balances include SPL tokens and the native SOL token. The response is paginated, and by default, returns 20 balances per page. - - **Note:** This endpoint is still under development and does not yet provide strong availability or freshness guarantees. Freshness and availability of new token balances will improve over the coming weeks. - - Sends a `GET` request to `/v2/solana/token-balances/{network}/{address}` + impl<'a> ListDataTokenBalances<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + network: Err("network was not initialized".to_string()), + address: Err("address was not initialized".to_string()), + page_size: Ok(None), + page_token: Ok(None), + } + } + pub fn network(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.network = value.try_into().map_err(|_| { + "conversion to `ListEvmTokenBalancesNetwork` for network failed".to_string() + }); + self + } + pub fn address(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.address = value.try_into().map_err(|_| { + "conversion to `ListDataTokenBalancesAddress` for address failed".to_string() + }); + self + } + pub fn page_size(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.page_size = value + .try_into() + .map(Some) + .map_err(|_| "conversion to `i64` for page_size failed".to_string()); + self + } + pub fn page_token(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.page_token = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for page_token failed".to_string() + }); + self + } + ///Sends a `GET` request to `/v2/data/evm/token-balances/{network}/{address}` + pub async fn send( + self, + ) -> Result, Error> + { + let Self { + client, + network, + address, + page_size, + page_token, + } = self; + let network = network.map_err(Error::InvalidRequest)?; + let address = address.map_err(Error::InvalidRequest)?; + let page_size = page_size.map_err(Error::InvalidRequest)?; + let page_token = page_token.map_err(Error::InvalidRequest)?; + let url = format!( + "{}/v2/data/evm/token-balances/{}/{}", + client.baseurl, + encode_path(&network.to_string()), + encode_path(&address.to_string()), + ); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + #[allow(unused_mut)] + let mut request = client + .client + .get(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .query(&progenitor_middleware_client::QueryParam::new( + "pageSize", &page_size, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "pageToken", + &page_token, + )) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "list_data_token_balances", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 200u16 => ResponseValue::from_response::(response).await, + 400u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 404u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 500u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 502u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 503u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + _ => Err(Error::UnexpectedResponse(response)), + } + } + } + /**Builder for [`Client::list_tokens_for_account`] - Arguments: - - `network`: The human-readable network name to get the balances for. - - `address`: The base58 encoded Solana address to get balances for. - - `page_size`: The number of balances to return per page. - - `page_token`: The token for the next page of balances. Will be empty if there are no more balances to fetch. - ```ignore - let response = client.list_solana_token_balances() - .network(network) - .address(address) - .page_size(page_size) - .page_token(page_token) - .send() - .await; - ```*/ - pub fn list_solana_token_balances(&self) -> builder::ListSolanaTokenBalances<'_> { - builder::ListSolanaTokenBalances::new(self) + [`Client::list_tokens_for_account`]: super::Client::list_tokens_for_account*/ + #[derive(Debug, Clone)] + pub struct ListTokensForAccount<'a> { + client: &'a super::Client, + network: Result, + address: Result, + } + impl<'a> ListTokensForAccount<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + network: Err("network was not initialized".to_string()), + address: Err("address was not initialized".to_string()), + } + } + pub fn network(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.network = value.try_into().map_err(|_| { + "conversion to `ListTokensForAccountNetwork` for network failed".to_string() + }); + self + } + pub fn address(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.address = value.try_into().map_err(|_| { + "conversion to `ListTokensForAccountAddress` for address failed".to_string() + }); + self + } + ///Sends a `GET` request to `/v2/data/evm/token-ownership/{network}/{address}` + pub async fn send( + self, + ) -> Result, Error> + { + let Self { + client, + network, + address, + } = self; + let network = network.map_err(Error::InvalidRequest)?; + let address = address.map_err(Error::InvalidRequest)?; + let url = format!( + "{}/v2/data/evm/token-ownership/{}/{}", + client.baseurl, + encode_path(&network.to_string()), + encode_path(&address.to_string()), + ); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + #[allow(unused_mut)] + let mut request = client + .client + .get(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "list_tokens_for_account", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 200u16 => ResponseValue::from_response::(response).await, + 400u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 401u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 429u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 500u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + _ => Err(Error::UnexpectedResponse(response)), + } + } } - /**Handle MCP JSON-RPC request - - Handles JSON-RPC requests for the Model Context Protocol (MCP). Supports MCP methods for discovering x402 payment resources and tools. - - Sends a `POST` request to `/v2/x402/discovery/mcp` + /**Builder for [`Client::get_sql_grammar`] - ```ignore - let response = client.post_x402_discovery_mcp() - .body(body) - .send() - .await; - ```*/ - pub fn post_x402_discovery_mcp(&self) -> builder::PostX402DiscoveryMcp<'_> { - builder::PostX402DiscoveryMcp::new(self) + [`Client::get_sql_grammar`]: super::Client::get_sql_grammar*/ + #[derive(Debug, Clone)] + pub struct GetSqlGrammar<'a> { + client: &'a super::Client, } - /**List merchant discovery info - - Gets x402 merchant discovery information for a given merchant payment address. - This endpoint returns all active x402 resources associated with the specified `payTo` address, allowing clients to discover what payment-gated resources a merchant exposes and their corresponding payment requirements. - The response is paginated, and by default, returns 20 items per page. - - Sends a `GET` request to `/v2/x402/discovery/merchant` - - Arguments: - - `limit`: The number of resources to return per page. - - `offset`: The offset of the first resource to return. - - `pay_to`: The merchant's payment address to look up. - This is the onchain address that payment requirements route funds to. - ```ignore - let response = client.list_x402_discovery_merchant() - .limit(limit) - .offset(offset) - .pay_to(pay_to) - .send() - .await; - ```*/ - pub fn list_x402_discovery_merchant(&self) -> builder::ListX402DiscoveryMerchant<'_> { - builder::ListX402DiscoveryMerchant::new(self) + impl<'a> GetSqlGrammar<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { client: client } + } + ///Sends a `GET` request to `/v2/data/query/grammar` + pub async fn send( + self, + ) -> Result, Error> { + let Self { client } = self; + let url = format!("{}/v2/data/query/grammar", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + #[allow(unused_mut)] + let mut request = client + .client + .get(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "get_sql_grammar", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 200u16 => ResponseValue::from_response::(response).await, + 401u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 429u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 500u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 504u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + _ => Err(Error::UnexpectedResponse(response)), + } + } } - /**List discovered x402 resources - - Lists all active discovered x402 resources. - This endpoint returns resources that have been discovered and cached by the x402 facilitator, including their payment requirements and metadata. - The response is paginated, and by default, returns 100 items per page. - - Sends a `GET` request to `/v2/x402/discovery/resources` + /**Builder for [`Client::run_sql_query`] - Arguments: - - `limit`: The number of discovered x402 resources to return per page. - - `offset`: The offset of the first discovered x402 resource to return. - - `type_`: Filter by protocol type (e.g., "http", "mcp"). - Currently, the only supported protocol type is "http". - ```ignore - let response = client.list_x402_discovery_resources() - .limit(limit) - .offset(offset) - .type_(type_) - .send() - .await; - ```*/ - pub fn list_x402_discovery_resources(&self) -> builder::ListX402DiscoveryResources<'_> { - builder::ListX402DiscoveryResources::new(self) + [`Client::run_sql_query`]: super::Client::run_sql_query*/ + #[derive(Debug, Clone)] + pub struct RunSqlQuery<'a> { + client: &'a super::Client, + body: Result, } - /**Search x402 resources - - Searches for active x402 resources using a text query and optional filters. - Supports both text-based and vector-based search depending on availability. Results are sorted by relevance and quality score. - Legacy network names (e.g., `base`, `base-sepolia`, `solana`) are automatically normalized to their CAIP-2 equivalents. - The response is limited to 20 items per request. If more results exist, `partialResults` will be `true`. - - Sends a `GET` request to `/v2/x402/discovery/search` - - Arguments: - - `asset`: Filter results by asset address. - For EVM networks, provide a 0x-prefixed EVM address. For Solana networks, provide a base58-encoded address. - Matching is case-insensitive. - - `extensions`: Filter results to resources that support the specified protocol extensions. Can be specified multiple times to filter by multiple extensions. - - `limit`: Maximum number of resources to return. Must be a positive integer no greater than 20. - Defaults to 20. - - `max_usd_price`: Filter results to resources with a USD price at or below this value. - - `network`: Filter results by network in CAIP-2 format (e.g., `eip155:8453`) or legacy name (e.g., `base`, `base-sepolia`, `solana`). - Legacy names are normalized to their CAIP-2 equivalents before filtering. - - `pay_to`: Filter results by the merchant's payment address. - For EVM networks, provide a 0x-prefixed EVM address. For Solana networks, provide a base58-encoded address. - - `query`: Full-text or semantic search query to find matching resources. - - `scheme`: Filter results by payment scheme (e.g., `exact`). - - `url_substring`: Filter results to resources whose URL contains this value (case-insensitive substring match against the resource URL). - Useful for narrowing results to a specific domain, subdomain, or path segment. Combine with `query` to perform semantic search restricted to a URL subset. - Tip: include enough of the URL to disambiguate (e.g. `api.example.com` rather than `example`) — a short substring may also match resources whose path contains the same string. - ```ignore - let response = client.search_x402_resources() - .asset(asset) - .extensions(extensions) - .limit(limit) - .max_usd_price(max_usd_price) - .network(network) - .pay_to(pay_to) - .query(query) - .scheme(scheme) - .url_substring(url_substring) - .send() - .await; - ```*/ - pub fn search_x402_resources(&self) -> builder::SearchX402Resources<'_> { - builder::SearchX402Resources::new(self) + impl<'a> RunSqlQuery<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + body: Ok(::std::default::Default::default()), + } + } + pub fn body(mut self, value: V) -> Self + where + V: std::convert::TryInto, + >::Error: std::fmt::Display, + { + self.body = value + .try_into() + .map(From::from) + .map_err(|s| format!("conversion to `OnchainDataQuery` for body failed: {}", s)); + self + } + pub fn body_map(mut self, f: F) -> Self + where + F: std::ops::FnOnce( + types::builder::OnchainDataQuery, + ) -> types::builder::OnchainDataQuery, + { + self.body = self.body.map(f); + self + } + ///Sends a `POST` request to `/v2/data/query/run` + pub async fn send( + self, + ) -> Result, Error> { + let Self { client, body } = self; + let body = body + .and_then(|v| types::OnchainDataQuery::try_from(v).map_err(|e| e.to_string())) + .map_err(Error::InvalidRequest)?; + let url = format!("{}/v2/data/query/run", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + #[allow(unused_mut)] + let mut request = client + .client + .post(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .json(&body) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "run_sql_query", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 200u16 => ResponseValue::from_response::(response).await, + 400u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 401u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 402u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 408u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 429u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 499u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 500u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 504u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + _ => Err(Error::UnexpectedResponse(response)), + } + } } - /**Settle a payment - - Settle an x402 protocol payment with a specific scheme and network. - - Sends a `POST` request to `/v2/x402/settle` + /**Builder for [`Client::get_sql_schema`] - ```ignore - let response = client.settle_x402_payment() - .body(body) - .send() - .await; - ```*/ - pub fn settle_x402_payment(&self) -> builder::SettleX402Payment<'_> { - builder::SettleX402Payment::new(self) + [`Client::get_sql_schema`]: super::Client::get_sql_schema*/ + #[derive(Debug, Clone)] + pub struct GetSqlSchema<'a> { + client: &'a super::Client, + database: Result, String>, + table: Result, String>, } - /**Get supported payment schemes and networks - - Get the supported x402 protocol payment schemes and networks that the facilitator is able to verify and settle payments for. - - Sends a `GET` request to `/v2/x402/supported` - - ```ignore - let response = client.supported_x402_payment_kinds() - .send() - .await; - ```*/ - pub fn supported_x402_payment_kinds(&self) -> builder::SupportedX402PaymentKinds<'_> { - builder::SupportedX402PaymentKinds::new(self) + impl<'a> GetSqlSchema<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + database: Ok(None), + table: Ok(None), + } + } + pub fn database(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.database = value.try_into().map(Some).map_err(|_| { + "conversion to `GetSqlSchemaDatabase` for database failed".to_string() + }); + self + } + pub fn table(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.table = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for table failed".to_string() + }); + self + } + ///Sends a `GET` request to `/v2/data/query/schema` + pub async fn send( + self, + ) -> Result, Error> { + let Self { + client, + database, + table, + } = self; + let database = database.map_err(Error::InvalidRequest)?; + let table = table.map_err(Error::InvalidRequest)?; + let url = format!("{}/v2/data/query/schema", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + #[allow(unused_mut)] + let mut request = client + .client + .get(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .query(&progenitor_middleware_client::QueryParam::new( + "database", &database, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "table", &table, + )) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "get_sql_schema", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 200u16 => ResponseValue::from_response::(response).await, + 401u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 500u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + _ => Err(Error::UnexpectedResponse(response)), + } + } } - /**Verify a payment - - Verify an x402 protocol payment with a specific scheme and network. - - Sends a `POST` request to `/v2/x402/verify` + /**Builder for [`Client::list_webhook_subscriptions`] - ```ignore - let response = client.verify_x402_payment() - .body(body) - .send() - .await; - ```*/ - pub fn verify_x402_payment(&self) -> builder::VerifyX402Payment<'_> { - builder::VerifyX402Payment::new(self) + [`Client::list_webhook_subscriptions`]: super::Client::list_webhook_subscriptions*/ + #[derive(Debug, Clone)] + pub struct ListWebhookSubscriptions<'a> { + client: &'a super::Client, + page_size: Result, String>, + page_token: Result, String>, } -} -/// Types for composing operation parameters. -#[allow(clippy::all)] -pub mod builder { - use super::types; - #[allow(unused_imports)] - use super::{ - encode_path, ByteStream, ClientHooks, ClientInfo, Error, OperationInfo, RequestBuilderExt, - ResponseValue, - }; - /**Builder for [`Client::list_data_token_balances`] + impl<'a> ListWebhookSubscriptions<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + page_size: Ok(None), + page_token: Ok(None), + } + } + pub fn page_size(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::num::NonZeroU64>, + { + self.page_size = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: num :: NonZeroU64` for page_size failed".to_string() + }); + self + } + pub fn page_token(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.page_token = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for page_token failed".to_string() + }); + self + } + ///Sends a `GET` request to `/v2/data/webhooks/subscriptions` + pub async fn send( + self, + ) -> Result, Error> + { + let Self { + client, + page_size, + page_token, + } = self; + let page_size = page_size.map_err(Error::InvalidRequest)?; + let page_token = page_token.map_err(Error::InvalidRequest)?; + let url = format!("{}/v2/data/webhooks/subscriptions", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + #[allow(unused_mut)] + let mut request = client + .client + .get(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .query(&progenitor_middleware_client::QueryParam::new( + "pageSize", &page_size, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "pageToken", + &page_token, + )) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "list_webhook_subscriptions", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 200u16 => ResponseValue::from_response::(response).await, + 400u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 401u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 429u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 500u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + _ => Err(Error::UnexpectedResponse(response)), + } + } + } + /**Builder for [`Client::create_webhook_subscription`] - [`Client::list_data_token_balances`]: super::Client::list_data_token_balances*/ + [`Client::create_webhook_subscription`]: super::Client::create_webhook_subscription*/ #[derive(Debug, Clone)] - pub struct ListDataTokenBalances<'a> { + pub struct CreateWebhookSubscription<'a> { client: &'a super::Client, - network: Result, - address: Result, - page_size: Result, String>, - page_token: Result, String>, + body: Result, } - impl<'a> ListDataTokenBalances<'a> { + impl<'a> CreateWebhookSubscription<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - network: Err("network was not initialized".to_string()), - address: Err("address was not initialized".to_string()), - page_size: Ok(None), - page_token: Ok(None), + body: Ok(::std::default::Default::default()), } } - pub fn network(mut self, value: V) -> Self + pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, + >::Error: + std::fmt::Display, { - self.network = value.try_into().map_err(|_| { - "conversion to `ListEvmTokenBalancesNetwork` for network failed".to_string() + self.body = value.try_into().map(From::from).map_err(|s| { + format!( + "conversion to `WebhookSubscriptionRequest` for body failed: {}", + s + ) }); self } - pub fn address(mut self, value: V) -> Self + pub fn body_map(mut self, f: F) -> Self where - V: std::convert::TryInto, + F: std::ops::FnOnce( + types::builder::WebhookSubscriptionRequest, + ) -> types::builder::WebhookSubscriptionRequest, { - self.address = value.try_into().map_err(|_| { - "conversion to `ListDataTokenBalancesAddress` for address failed".to_string() + self.body = self.body.map(f); + self + } + ///Sends a `POST` request to `/v2/data/webhooks/subscriptions` + pub async fn send( + self, + ) -> Result, Error> + { + let Self { client, body } = self; + let body = body + .and_then(|v| { + types::WebhookSubscriptionRequest::try_from(v).map_err(|e| e.to_string()) + }) + .map_err(Error::InvalidRequest)?; + let url = format!("{}/v2/data/webhooks/subscriptions", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + #[allow(unused_mut)] + let mut request = client + .client + .post(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .json(&body) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "create_webhook_subscription", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 201u16 => ResponseValue::from_response::(response).await, + 400u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 401u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 429u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 500u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + _ => Err(Error::UnexpectedResponse(response)), + } + } + } + /**Builder for [`Client::get_webhook_subscription`] + + [`Client::get_webhook_subscription`]: super::Client::get_webhook_subscription*/ + #[derive(Debug, Clone)] + pub struct GetWebhookSubscription<'a> { + client: &'a super::Client, + subscription_id: Result<::uuid::Uuid, String>, + } + impl<'a> GetWebhookSubscription<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + subscription_id: Err("subscription_id was not initialized".to_string()), + } + } + pub fn subscription_id(mut self, value: V) -> Self + where + V: std::convert::TryInto<::uuid::Uuid>, + { + self.subscription_id = value.try_into().map_err(|_| { + "conversion to `:: uuid :: Uuid` for subscription_id failed".to_string() }); self } - pub fn page_size(mut self, value: V) -> Self + ///Sends a `GET` request to `/v2/data/webhooks/subscriptions/{subscriptionId}` + pub async fn send( + self, + ) -> Result, Error> + { + let Self { + client, + subscription_id, + } = self; + let subscription_id = subscription_id.map_err(Error::InvalidRequest)?; + let url = format!( + "{}/v2/data/webhooks/subscriptions/{}", + client.baseurl, + encode_path(&subscription_id.to_string()), + ); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + #[allow(unused_mut)] + let mut request = client + .client + .get(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "get_webhook_subscription", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 200u16 => ResponseValue::from_response::(response).await, + 401u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 404u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 429u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 500u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + _ => Err(Error::UnexpectedResponse(response)), + } + } + } + /**Builder for [`Client::update_webhook_subscription`] + + [`Client::update_webhook_subscription`]: super::Client::update_webhook_subscription*/ + #[derive(Debug, Clone)] + pub struct UpdateWebhookSubscription<'a> { + client: &'a super::Client, + subscription_id: Result<::uuid::Uuid, String>, + body: Result, + } + impl<'a> UpdateWebhookSubscription<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + subscription_id: Err("subscription_id was not initialized".to_string()), + body: Ok(::std::default::Default::default()), + } + } + pub fn subscription_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto<::uuid::Uuid>, { - self.page_size = value - .try_into() - .map(Some) - .map_err(|_| "conversion to `i64` for page_size failed".to_string()); + self.subscription_id = value.try_into().map_err(|_| { + "conversion to `:: uuid :: Uuid` for subscription_id failed".to_string() + }); self } - pub fn page_token(mut self, value: V) -> Self + pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto<::std::string::String>, + V: std::convert::TryInto, + >::Error: + std::fmt::Display, { - self.page_token = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: string :: String` for page_token failed".to_string() + self.body = value.try_into().map(From::from).map_err(|s| { + format!( + "conversion to `WebhookSubscriptionUpdateRequest` for body failed: {}", + s + ) }); self } - ///Sends a `GET` request to `/v2/data/evm/token-balances/{network}/{address}` + pub fn body_map(mut self, f: F) -> Self + where + F: std::ops::FnOnce( + types::builder::WebhookSubscriptionUpdateRequest, + ) -> types::builder::WebhookSubscriptionUpdateRequest, + { + self.body = self.body.map(f); + self + } + ///Sends a `PUT` request to `/v2/data/webhooks/subscriptions/{subscriptionId}` pub async fn send( self, - ) -> Result, Error> + ) -> Result, Error> { let Self { client, - network, - address, - page_size, - page_token, + subscription_id, + body, } = self; - let network = network.map_err(Error::InvalidRequest)?; - let address = address.map_err(Error::InvalidRequest)?; - let page_size = page_size.map_err(Error::InvalidRequest)?; - let page_token = page_token.map_err(Error::InvalidRequest)?; + let subscription_id = subscription_id.map_err(Error::InvalidRequest)?; + let body = body + .and_then(|v| { + types::WebhookSubscriptionUpdateRequest::try_from(v).map_err(|e| e.to_string()) + }) + .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/data/evm/token-balances/{}/{}", + "{}/v2/data/webhooks/subscriptions/{}", client.baseurl, - encode_path(&network.to_string()), - encode_path(&address.to_string()), + encode_path(&subscription_id.to_string()), ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( @@ -85117,22 +98635,16 @@ pub mod builder { #[allow(unused_mut)] let mut request = client .client - .get(url) + .put(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) - .query(&progenitor_middleware_client::QueryParam::new( - "pageSize", &page_size, - )) - .query(&progenitor_middleware_client::QueryParam::new( - "pageToken", - &page_token, - )) + .json(&body) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "list_data_token_balances", + operation_id: "update_webhook_subscription", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -85143,74 +98655,196 @@ pub mod builder { 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 401u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 429u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 502u16 => Err(Error::ErrorResponse( + _ => Err(Error::UnexpectedResponse(response)), + } + } + } + /**Builder for [`Client::delete_webhook_subscription`] + + [`Client::delete_webhook_subscription`]: super::Client::delete_webhook_subscription*/ + #[derive(Debug, Clone)] + pub struct DeleteWebhookSubscription<'a> { + client: &'a super::Client, + subscription_id: Result<::uuid::Uuid, String>, + } + impl<'a> DeleteWebhookSubscription<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + subscription_id: Err("subscription_id was not initialized".to_string()), + } + } + pub fn subscription_id(mut self, value: V) -> Self + where + V: std::convert::TryInto<::uuid::Uuid>, + { + self.subscription_id = value.try_into().map_err(|_| { + "conversion to `:: uuid :: Uuid` for subscription_id failed".to_string() + }); + self + } + ///Sends a `DELETE` request to `/v2/data/webhooks/subscriptions/{subscriptionId}` + pub async fn send(self) -> Result, Error> { + let Self { + client, + subscription_id, + } = self; + let subscription_id = subscription_id.map_err(Error::InvalidRequest)?; + let url = format!( + "{}/v2/data/webhooks/subscriptions/{}", + client.baseurl, + encode_path(&subscription_id.to_string()), + ); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + #[allow(unused_mut)] + let mut request = client + .client + .delete(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "delete_webhook_subscription", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 204u16 => Ok(ResponseValue::empty(response)), + 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 503u16 => Err(Error::ErrorResponse( + 404u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 429u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::list_tokens_for_account`] + /**Builder for [`Client::list_webhook_subscription_events`] - [`Client::list_tokens_for_account`]: super::Client::list_tokens_for_account*/ + [`Client::list_webhook_subscription_events`]: super::Client::list_webhook_subscription_events*/ #[derive(Debug, Clone)] - pub struct ListTokensForAccount<'a> { + pub struct ListWebhookSubscriptionEvents<'a> { client: &'a super::Client, - network: Result, - address: Result, + subscription_id: Result<::uuid::Uuid, String>, + event_id: Result, String>, + event_type_names: Result, String>, + max_created_at: Result>, String>, + min_created_at: Result>, String>, } - impl<'a> ListTokensForAccount<'a> { + impl<'a> ListWebhookSubscriptionEvents<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - network: Err("network was not initialized".to_string()), - address: Err("address was not initialized".to_string()), + subscription_id: Err("subscription_id was not initialized".to_string()), + event_id: Ok(None), + event_type_names: Ok(None), + max_created_at: Ok(None), + min_created_at: Ok(None), } } - pub fn network(mut self, value: V) -> Self + pub fn subscription_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto<::uuid::Uuid>, { - self.network = value.try_into().map_err(|_| { - "conversion to `ListTokensForAccountNetwork` for network failed".to_string() + self.subscription_id = value.try_into().map_err(|_| { + "conversion to `:: uuid :: Uuid` for subscription_id failed".to_string() }); self } - pub fn address(mut self, value: V) -> Self + pub fn event_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto<::uuid::Uuid>, { - self.address = value.try_into().map_err(|_| { - "conversion to `ListTokensForAccountAddress` for address failed".to_string() + self.event_id = value + .try_into() + .map(Some) + .map_err(|_| "conversion to `:: uuid :: Uuid` for event_id failed".to_string()); + self + } + pub fn event_type_names(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.event_type_names = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for event_type_names failed".to_string() }); self } - ///Sends a `GET` request to `/v2/data/evm/token-ownership/{network}/{address}` + pub fn max_created_at(mut self, value: V) -> Self + where + V: std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, + { + self.max_created_at = value + .try_into() + .map(Some) + .map_err(|_| { + "conversion to `:: chrono :: DateTime < :: chrono :: offset :: Utc >` for max_created_at failed" + .to_string() + }); + self + } + pub fn min_created_at(mut self, value: V) -> Self + where + V: std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, + { + self.min_created_at = value + .try_into() + .map(Some) + .map_err(|_| { + "conversion to `:: chrono :: DateTime < :: chrono :: offset :: Utc >` for min_created_at failed" + .to_string() + }); + self + } + ///Sends a `GET` request to `/v2/data/webhooks/subscriptions/{subscriptionId}/events` pub async fn send( self, - ) -> Result, Error> - { + ) -> Result, Error> { let Self { client, - network, - address, + subscription_id, + event_id, + event_type_names, + max_created_at, + min_created_at, } = self; - let network = network.map_err(Error::InvalidRequest)?; - let address = address.map_err(Error::InvalidRequest)?; + let subscription_id = subscription_id.map_err(Error::InvalidRequest)?; + let event_id = event_id.map_err(Error::InvalidRequest)?; + let event_type_names = event_type_names.map_err(Error::InvalidRequest)?; + let max_created_at = max_created_at.map_err(Error::InvalidRequest)?; + let min_created_at = min_created_at.map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/data/evm/token-ownership/{}/{}", + "{}/v2/data/webhooks/subscriptions/{}/events", client.baseurl, - encode_path(&network.to_string()), - encode_path(&address.to_string()), + encode_path(&subscription_id.to_string()), ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( @@ -85225,10 +98859,25 @@ pub mod builder { ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) + .query(&progenitor_middleware_client::QueryParam::new( + "eventId", &event_id, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "eventTypeNames", + &event_type_names, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "maxCreatedAt", + &max_created_at, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "minCreatedAt", + &min_created_at, + )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "list_tokens_for_account", + operation_id: "list_webhook_subscription_events", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -85242,6 +98891,9 @@ pub mod builder { 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 404u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 429u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -85252,23 +98904,109 @@ pub mod builder { } } } - /**Builder for [`Client::get_sql_grammar`] + /**Builder for [`Client::list_deposit_destinations`] - [`Client::get_sql_grammar`]: super::Client::get_sql_grammar*/ + [`Client::list_deposit_destinations`]: super::Client::list_deposit_destinations*/ #[derive(Debug, Clone)] - pub struct GetSqlGrammar<'a> { + pub struct ListDepositDestinations<'a> { client: &'a super::Client, + account_id: Result, String>, + address: Result, String>, + network: Result, String>, + page_size: Result, String>, + page_token: Result, String>, + type_: Result, String>, } - impl<'a> GetSqlGrammar<'a> { + impl<'a> ListDepositDestinations<'a> { pub fn new(client: &'a super::Client) -> Self { - Self { client: client } + Self { + client: client, + account_id: Ok(None), + address: Ok(None), + network: Ok(None), + page_size: Ok(None), + page_token: Ok(None), + type_: Ok(None), + } + } + pub fn account_id(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.account_id = value + .try_into() + .map(Some) + .map_err(|_| "conversion to `AccountId` for account_id failed".to_string()); + self + } + pub fn address(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.address = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for address failed".to_string() + }); + self + } + pub fn network(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.network = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for network failed".to_string() + }); + self + } + pub fn page_size(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.page_size = value + .try_into() + .map(Some) + .map_err(|_| "conversion to `i64` for page_size failed".to_string()); + self + } + pub fn page_token(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.page_token = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for page_token failed".to_string() + }); + self } - ///Sends a `GET` request to `/v2/data/query/grammar` + pub fn type_(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.type_ = value + .try_into() + .map(Some) + .map_err(|_| "conversion to `DepositDestinationType` for type_ failed".to_string()); + self + } + ///Sends a `GET` request to `/v2/deposit-destinations` pub async fn send( self, - ) -> Result, Error> { - let Self { client } = self; - let url = format!("{}/v2/data/query/grammar", client.baseurl,); + ) -> Result, Error> + { + let Self { + client, + account_id, + address, + network, + page_size, + page_token, + type_, + } = self; + let account_id = account_id.map_err(Error::InvalidRequest)?; + let address = address.map_err(Error::InvalidRequest)?; + let network = network.map_err(Error::InvalidRequest)?; + let page_size = page_size.map_err(Error::InvalidRequest)?; + let page_token = page_token.map_err(Error::InvalidRequest)?; + let type_ = type_.map_err(Error::InvalidRequest)?; + let url = format!("{}/v2/deposit-destinations", client.baseurl,); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), @@ -85282,10 +99020,30 @@ pub mod builder { ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) + .query(&progenitor_middleware_client::QueryParam::new( + "accountId", + &account_id, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "address", &address, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "network", &network, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "pageSize", &page_size, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "pageToken", + &page_token, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "type", &type_, + )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "get_sql_grammar", + operation_id: "list_deposit_destinations", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -85293,71 +99051,78 @@ pub mod builder { let response = result?; match response.status().as_u16() { 200u16 => ResponseValue::from_response::(response).await, - 401u16 => Err(Error::ErrorResponse( + 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 429u16 => Err(Error::ErrorResponse( + 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 504u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::run_sql_query`] + /**Builder for [`Client::create_deposit_destination`] - [`Client::run_sql_query`]: super::Client::run_sql_query*/ + [`Client::create_deposit_destination`]: super::Client::create_deposit_destination*/ #[derive(Debug, Clone)] - pub struct RunSqlQuery<'a> { + pub struct CreateDepositDestination<'a> { client: &'a super::Client, - body: Result, + x_idempotency_key: Result, String>, + body: Result, } - impl<'a> RunSqlQuery<'a> { + impl<'a> CreateDepositDestination<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - body: Ok(::std::default::Default::default()), + x_idempotency_key: Ok(None), + body: Err("body was not initialized".to_string()), } } - pub fn body(mut self, value: V) -> Self + pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto, { - self.body = value + self.x_idempotency_key = value .try_into() - .map(From::from) - .map_err(|s| format!("conversion to `OnchainDataQuery` for body failed: {}", s)); + .map(Some) + .map_err(|_| { + "conversion to `CreateDepositDestinationXIdempotencyKey` for x_idempotency_key failed" + .to_string() + }); self } - pub fn body_map(mut self, f: F) -> Self + pub fn body(mut self, value: V) -> Self where - F: std::ops::FnOnce( - types::builder::OnchainDataQuery, - ) -> types::builder::OnchainDataQuery, + V: std::convert::TryInto, { - self.body = self.body.map(f); + self.body = value.try_into().map_err(|_| { + "conversion to `CreateDepositDestinationRequest` for body failed".to_string() + }); self } - ///Sends a `POST` request to `/v2/data/query/run` + ///Sends a `POST` request to `/v2/deposit-destinations` pub async fn send( self, - ) -> Result, Error> { - let Self { client, body } = self; - let body = body - .and_then(|v| types::OnchainDataQuery::try_from(v).map_err(|e| e.to_string())) - .map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/data/query/run", client.baseurl,); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + ) -> Result, Error> { + let Self { + client, + x_idempotency_key, + body, + } = self; + let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; + let body = body.map_err(Error::InvalidRequest)?; + let url = format!("{}/v2/deposit-destinations", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(2usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); + if let Some(value) = x_idempotency_key { + header_map.append("X-Idempotency-Key", value.to_string().try_into()?); + } #[allow(unused_mut)] let mut request = client .client @@ -85370,89 +99135,76 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "run_sql_query", + operation_id: "create_deposit_destination", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 200u16 => ResponseValue::from_response::(response).await, + 201u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 402u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 408u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 429u16 => Err(Error::ErrorResponse( + 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 499u16 => Err(Error::ErrorResponse( + 422u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 504u16 => Err(Error::ErrorResponse( + 503u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::get_sql_schema`] + /**Builder for [`Client::get_deposit_destination_by_id`] - [`Client::get_sql_schema`]: super::Client::get_sql_schema*/ + [`Client::get_deposit_destination_by_id`]: super::Client::get_deposit_destination_by_id*/ #[derive(Debug, Clone)] - pub struct GetSqlSchema<'a> { + pub struct GetDepositDestinationById<'a> { client: &'a super::Client, - database: Result, String>, - table: Result, String>, + deposit_destination_id: Result, } - impl<'a> GetSqlSchema<'a> { + impl<'a> GetDepositDestinationById<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - database: Ok(None), - table: Ok(None), + deposit_destination_id: Err( + "deposit_destination_id was not initialized".to_string() + ), } } - pub fn database(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.database = value.try_into().map(Some).map_err(|_| { - "conversion to `GetSqlSchemaDatabase` for database failed".to_string() - }); - self - } - pub fn table(mut self, value: V) -> Self + pub fn deposit_destination_id(mut self, value: V) -> Self where - V: std::convert::TryInto<::std::string::String>, + V: std::convert::TryInto, { - self.table = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: string :: String` for table failed".to_string() + self.deposit_destination_id = value.try_into().map_err(|_| { + "conversion to `DepositDestinationId` for deposit_destination_id failed".to_string() }); self } - ///Sends a `GET` request to `/v2/data/query/schema` + ///Sends a `GET` request to `/v2/deposit-destinations/{depositDestinationId}` pub async fn send( self, - ) -> Result, Error> { + ) -> Result, Error> { let Self { client, - database, - table, + deposit_destination_id, } = self; - let database = database.map_err(Error::InvalidRequest)?; - let table = table.map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/data/query/schema", client.baseurl,); + let deposit_destination_id = deposit_destination_id.map_err(Error::InvalidRequest)?; + let url = format!( + "{}/v2/deposit-destinations/{}", + client.baseurl, + encode_path(&deposit_destination_id.to_string()), + ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), @@ -85466,16 +99218,10 @@ pub mod builder { ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) - .query(&progenitor_middleware_client::QueryParam::new( - "database", &database, - )) - .query(&progenitor_middleware_client::QueryParam::new( - "table", &table, - )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "get_sql_schema", + operation_id: "get_deposit_destination_by_id", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -85483,9 +99229,15 @@ pub mod builder { let response = result?; match response.status().as_u16() { 200u16 => ResponseValue::from_response::(response).await, + 400u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 404u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -85493,54 +99245,74 @@ pub mod builder { } } } - /**Builder for [`Client::list_webhook_subscriptions`] + /**Builder for [`Client::get_delegation_for_end_user_account`] - [`Client::list_webhook_subscriptions`]: super::Client::list_webhook_subscriptions*/ + [`Client::get_delegation_for_end_user_account`]: super::Client::get_delegation_for_end_user_account*/ #[derive(Debug, Clone)] - pub struct ListWebhookSubscriptions<'a> { + pub struct GetDelegationForEndUserAccount<'a> { client: &'a super::Client, - page_size: Result, String>, - page_token: Result, String>, + user_id: Result, + address: Result, + project_id: Result, String>, } - impl<'a> ListWebhookSubscriptions<'a> { + impl<'a> GetDelegationForEndUserAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - page_size: Ok(None), - page_token: Ok(None), + user_id: Err("user_id was not initialized".to_string()), + address: Err("address was not initialized".to_string()), + project_id: Ok(None), } } - pub fn page_size(mut self, value: V) -> Self + pub fn user_id(mut self, value: V) -> Self where - V: std::convert::TryInto<::std::num::NonZeroU64>, + V: std::convert::TryInto, { - self.page_size = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: num :: NonZeroU64` for page_size failed".to_string() + self.user_id = value.try_into().map_err(|_| { + "conversion to `GetDelegationForEndUserAccountUserId` for user_id failed" + .to_string() }); self } - pub fn page_token(mut self, value: V) -> Self + pub fn address(mut self, value: V) -> Self where - V: std::convert::TryInto<::std::string::String>, + V: std::convert::TryInto, { - self.page_token = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: string :: String` for page_token failed".to_string() + self.address = value + .try_into() + .map_err(|_| "conversion to `BlockchainAddress` for address failed".to_string()); + self + } + pub fn project_id(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.project_id = value.try_into().map(Some).map_err(|_| { + "conversion to `GetDelegationForEndUserAccountProjectId` for project_id failed" + .to_string() }); self } - ///Sends a `GET` request to `/v2/data/webhooks/subscriptions` + ///Sends a `GET` request to `/v2/embedded-wallet-api/end-users/{userId}/address/{address}/delegation` pub async fn send( self, - ) -> Result, Error> + ) -> Result, Error> { let Self { client, - page_size, - page_token, + user_id, + address, + project_id, } = self; - let page_size = page_size.map_err(Error::InvalidRequest)?; - let page_token = page_token.map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/data/webhooks/subscriptions", client.baseurl,); + let user_id = user_id.map_err(Error::InvalidRequest)?; + let address = address.map_err(Error::InvalidRequest)?; + let project_id = project_id.map_err(Error::InvalidRequest)?; + let url = format!( + "{}/v2/embedded-wallet-api/end-users/{}/address/{}/delegation", + client.baseurl, + encode_path(&user_id.to_string()), + encode_path(&address.to_string()), + ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), @@ -85555,16 +99327,13 @@ pub mod builder { ::reqwest::header::HeaderValue::from_static("application/json"), ) .query(&progenitor_middleware_client::QueryParam::new( - "pageSize", &page_size, - )) - .query(&progenitor_middleware_client::QueryParam::new( - "pageToken", - &page_token, + "projectID", + &project_id, )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "list_webhook_subscriptions", + operation_id: "get_delegation_for_end_user_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -85572,46 +99341,111 @@ pub mod builder { let response = result?; match response.status().as_u16() { 200u16 => ResponseValue::from_response::(response).await, - 400u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 429u16 => Err(Error::ErrorResponse( + 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 502u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 503u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::create_webhook_subscription`] + /**Builder for [`Client::create_delegation_for_end_user_account`] - [`Client::create_webhook_subscription`]: super::Client::create_webhook_subscription*/ + [`Client::create_delegation_for_end_user_account`]: super::Client::create_delegation_for_end_user_account*/ #[derive(Debug, Clone)] - pub struct CreateWebhookSubscription<'a> { + pub struct CreateDelegationForEndUserAccount<'a> { client: &'a super::Client, - body: Result, + user_id: Result, + address: Result, + project_id: Result, String>, + x_idempotency_key: + Result, String>, + x_wallet_auth: Result<::std::string::String, String>, + body: Result, } - impl<'a> CreateWebhookSubscription<'a> { + impl<'a> CreateDelegationForEndUserAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, + user_id: Err("user_id was not initialized".to_string()), + address: Err("address was not initialized".to_string()), + project_id: Ok(None), + x_idempotency_key: Ok(None), + x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), body: Ok(::std::default::Default::default()), } } + pub fn user_id(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.user_id = value.try_into().map_err(|_| { + "conversion to `CreateDelegationForEndUserAccountUserId` for user_id failed" + .to_string() + }); + self + } + pub fn address(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.address = value + .try_into() + .map_err(|_| "conversion to `BlockchainAddress` for address failed".to_string()); + self + } + pub fn project_id(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.project_id = value.try_into().map(Some).map_err(|_| { + "conversion to `CreateDelegationForEndUserAccountProjectId` for project_id failed" + .to_string() + }); + self + } + pub fn x_idempotency_key(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.x_idempotency_key = value + .try_into() + .map(Some) + .map_err(|_| { + "conversion to `CreateDelegationForEndUserAccountXIdempotencyKey` for x_idempotency_key failed" + .to_string() + }); + self + } + pub fn x_wallet_auth(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.x_wallet_auth = value.try_into().map_err(|_| { + "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() + }); + self + } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: + V: std::convert::TryInto, + >::Error: std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `WebhookSubscriptionRequest` for body failed: {}", + "conversion to `CreateDelegationForEndUserAccountBody` for body failed: {}", s ) }); @@ -85620,29 +99454,55 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::WebhookSubscriptionRequest, - ) -> types::builder::WebhookSubscriptionRequest, + types::builder::CreateDelegationForEndUserAccountBody, + ) + -> types::builder::CreateDelegationForEndUserAccountBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/data/webhooks/subscriptions` + ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/address/{address}/delegation` pub async fn send( self, - ) -> Result, Error> - { - let Self { client, body } = self; + ) -> Result< + ResponseValue, + Error, + > { + let Self { + client, + user_id, + address, + project_id, + x_idempotency_key, + x_wallet_auth, + body, + } = self; + let user_id = user_id.map_err(Error::InvalidRequest)?; + let address = address.map_err(Error::InvalidRequest)?; + let project_id = project_id.map_err(Error::InvalidRequest)?; + let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; + let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body .and_then(|v| { - types::WebhookSubscriptionRequest::try_from(v).map_err(|e| e.to_string()) + types::CreateDelegationForEndUserAccountBody::try_from(v) + .map_err(|e| e.to_string()) }) .map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/data/webhooks/subscriptions", client.baseurl,); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + let url = format!( + "{}/v2/embedded-wallet-api/end-users/{}/address/{}/delegation", + client.baseurl, + encode_path(&user_id.to_string()), + encode_path(&address.to_string()), + ); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); + if let Some(value) = x_idempotency_key { + header_map.append("X-Idempotency-Key", value.to_string().try_into()?); + } + header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client @@ -85652,10 +99512,14 @@ pub mod builder { ::reqwest::header::HeaderValue::from_static("application/json"), ) .json(&body) + .query(&progenitor_middleware_client::QueryParam::new( + "projectID", + &project_id, + )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "create_webhook_subscription", + operation_id: "create_delegation_for_end_user_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -85669,83 +99533,16 @@ pub mod builder { 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 429u16 => Err(Error::ErrorResponse( + 402u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 500u16 => Err(Error::ErrorResponse( + 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - _ => Err(Error::UnexpectedResponse(response)), - } - } - } - /**Builder for [`Client::get_webhook_subscription`] - - [`Client::get_webhook_subscription`]: super::Client::get_webhook_subscription*/ - #[derive(Debug, Clone)] - pub struct GetWebhookSubscription<'a> { - client: &'a super::Client, - subscription_id: Result<::uuid::Uuid, String>, - } - impl<'a> GetWebhookSubscription<'a> { - pub fn new(client: &'a super::Client) -> Self { - Self { - client: client, - subscription_id: Err("subscription_id was not initialized".to_string()), - } - } - pub fn subscription_id(mut self, value: V) -> Self - where - V: std::convert::TryInto<::uuid::Uuid>, - { - self.subscription_id = value.try_into().map_err(|_| { - "conversion to `:: uuid :: Uuid` for subscription_id failed".to_string() - }); - self - } - ///Sends a `GET` request to `/v2/data/webhooks/subscriptions/{subscriptionId}` - pub async fn send( - self, - ) -> Result, Error> - { - let Self { - client, - subscription_id, - } = self; - let subscription_id = subscription_id.map_err(Error::InvalidRequest)?; - let url = format!( - "{}/v2/data/webhooks/subscriptions/{}", - client.baseurl, - encode_path(&subscription_id.to_string()), - ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); - header_map.append( - ::reqwest::header::HeaderName::from_static("api-version"), - ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), - ); - #[allow(unused_mut)] - let mut request = client - .client - .get(url) - .header( - ::reqwest::header::ACCEPT, - ::reqwest::header::HeaderValue::from_static("application/json"), - ) - .headers(header_map) - .build()?; - let info = OperationInfo { - operation_id: "get_webhook_subscription", - }; - client.pre(&mut request, &info).await?; - let result = client.exec(request, &info).await; - client.post(&result, &info).await?; - let response = result?; - match response.status().as_u16() { - 200u16 => ResponseValue::from_response::(response).await, - 401u16 => Err(Error::ErrorResponse( + 409u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 404u16 => Err(Error::ErrorResponse( + 422u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 429u16 => Err(Error::ErrorResponse( @@ -85754,45 +99551,113 @@ pub mod builder { 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 502u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 503u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::update_webhook_subscription`] + /**Builder for [`Client::revoke_delegation_for_end_user_account`] - [`Client::update_webhook_subscription`]: super::Client::update_webhook_subscription*/ + [`Client::revoke_delegation_for_end_user_account`]: super::Client::revoke_delegation_for_end_user_account*/ #[derive(Debug, Clone)] - pub struct UpdateWebhookSubscription<'a> { + pub struct RevokeDelegationForEndUserAccount<'a> { client: &'a super::Client, - subscription_id: Result<::uuid::Uuid, String>, - body: Result, + user_id: Result, + address: Result, + project_id: Result, String>, + x_developer_auth: Result, String>, + x_idempotency_key: + Result, String>, + x_wallet_auth: Result, String>, + body: Result, } - impl<'a> UpdateWebhookSubscription<'a> { + impl<'a> RevokeDelegationForEndUserAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - subscription_id: Err("subscription_id was not initialized".to_string()), + user_id: Err("user_id was not initialized".to_string()), + address: Err("address was not initialized".to_string()), + project_id: Ok(None), + x_developer_auth: Ok(None), + x_idempotency_key: Ok(None), + x_wallet_auth: Ok(None), body: Ok(::std::default::Default::default()), } } - pub fn subscription_id(mut self, value: V) -> Self + pub fn user_id(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.user_id = value.try_into().map_err(|_| { + "conversion to `RevokeDelegationForEndUserAccountUserId` for user_id failed" + .to_string() + }); + self + } + pub fn address(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.address = value + .try_into() + .map_err(|_| "conversion to `BlockchainAddress` for address failed".to_string()); + self + } + pub fn project_id(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.project_id = value.try_into().map(Some).map_err(|_| { + "conversion to `RevokeDelegationForEndUserAccountProjectId` for project_id failed" + .to_string() + }); + self + } + pub fn x_developer_auth(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.x_developer_auth = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for x_developer_auth failed".to_string() + }); + self + } + pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto<::uuid::Uuid>, + V: std::convert::TryInto, { - self.subscription_id = value.try_into().map_err(|_| { - "conversion to `:: uuid :: Uuid` for subscription_id failed".to_string() + self.x_idempotency_key = value + .try_into() + .map(Some) + .map_err(|_| { + "conversion to `RevokeDelegationForEndUserAccountXIdempotencyKey` for x_idempotency_key failed" + .to_string() + }); + self + } + pub fn x_wallet_auth(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.x_wallet_auth = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() }); self } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: + V: std::convert::TryInto, + >::Error: std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `WebhookSubscriptionUpdateRequest` for body failed: {}", + "conversion to `RevokeDelegationForEndUserAccountBody` for body failed: {}", s ) }); @@ -85801,112 +99666,151 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::WebhookSubscriptionUpdateRequest, - ) -> types::builder::WebhookSubscriptionUpdateRequest, + types::builder::RevokeDelegationForEndUserAccountBody, + ) + -> types::builder::RevokeDelegationForEndUserAccountBody, { self.body = self.body.map(f); self } - ///Sends a `PUT` request to `/v2/data/webhooks/subscriptions/{subscriptionId}` - pub async fn send( - self, - ) -> Result, Error> - { + ///Sends a `DELETE` request to `/v2/embedded-wallet-api/end-users/{userId}/address/{address}/delegation` + pub async fn send(self) -> Result, Error> { let Self { client, - subscription_id, + user_id, + address, + project_id, + x_developer_auth, + x_idempotency_key, + x_wallet_auth, body, } = self; - let subscription_id = subscription_id.map_err(Error::InvalidRequest)?; + let user_id = user_id.map_err(Error::InvalidRequest)?; + let address = address.map_err(Error::InvalidRequest)?; + let project_id = project_id.map_err(Error::InvalidRequest)?; + let x_developer_auth = x_developer_auth.map_err(Error::InvalidRequest)?; + let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; + let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body .and_then(|v| { - types::WebhookSubscriptionUpdateRequest::try_from(v).map_err(|e| e.to_string()) + types::RevokeDelegationForEndUserAccountBody::try_from(v) + .map_err(|e| e.to_string()) }) .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/data/webhooks/subscriptions/{}", + "{}/v2/embedded-wallet-api/end-users/{}/address/{}/delegation", client.baseurl, - encode_path(&subscription_id.to_string()), + encode_path(&user_id.to_string()), + encode_path(&address.to_string()), ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(4usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); + if let Some(value) = x_developer_auth { + header_map.append("X-Developer-Auth", value.to_string().try_into()?); + } + if let Some(value) = x_idempotency_key { + header_map.append("X-Idempotency-Key", value.to_string().try_into()?); + } + if let Some(value) = x_wallet_auth { + header_map.append("X-Wallet-Auth", value.to_string().try_into()?); + } #[allow(unused_mut)] let mut request = client .client - .put(url) + .delete(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) .json(&body) + .query(&progenitor_middleware_client::QueryParam::new( + "projectID", + &project_id, + )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "update_webhook_subscription", + operation_id: "revoke_delegation_for_end_user_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 200u16 => ResponseValue::from_response::(response).await, - 400u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), + 204u16 => Ok(ResponseValue::empty(response)), 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 429u16 => Err(Error::ErrorResponse( + 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 500u16 => Err(Error::ErrorResponse( + 502u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 503u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::delete_webhook_subscription`] + /**Builder for [`Client::get_delegation_for_end_user`] - [`Client::delete_webhook_subscription`]: super::Client::delete_webhook_subscription*/ + [`Client::get_delegation_for_end_user`]: super::Client::get_delegation_for_end_user*/ #[derive(Debug, Clone)] - pub struct DeleteWebhookSubscription<'a> { + pub struct GetDelegationForEndUser<'a> { client: &'a super::Client, - subscription_id: Result<::uuid::Uuid, String>, + user_id: Result, + project_id: Result, String>, } - impl<'a> DeleteWebhookSubscription<'a> { + impl<'a> GetDelegationForEndUser<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - subscription_id: Err("subscription_id was not initialized".to_string()), + user_id: Err("user_id was not initialized".to_string()), + project_id: Ok(None), } } - pub fn subscription_id(mut self, value: V) -> Self + pub fn user_id(mut self, value: V) -> Self where - V: std::convert::TryInto<::uuid::Uuid>, + V: std::convert::TryInto, { - self.subscription_id = value.try_into().map_err(|_| { - "conversion to `:: uuid :: Uuid` for subscription_id failed".to_string() + self.user_id = value.try_into().map_err(|_| { + "conversion to `GetDelegationForEndUserUserId` for user_id failed".to_string() }); self } - ///Sends a `DELETE` request to `/v2/data/webhooks/subscriptions/{subscriptionId}` - pub async fn send(self) -> Result, Error> { + pub fn project_id(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.project_id = value.try_into().map(Some).map_err(|_| { + "conversion to `GetDelegationForEndUserProjectId` for project_id failed".to_string() + }); + self + } + ///Sends a `GET` request to `/v2/embedded-wallet-api/end-users/{userId}/delegation` + pub async fn send( + self, + ) -> Result, Error> + { let Self { client, - subscription_id, + user_id, + project_id, } = self; - let subscription_id = subscription_id.map_err(Error::InvalidRequest)?; + let user_id = user_id.map_err(Error::InvalidRequest)?; + let project_id = project_id.map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/data/webhooks/subscriptions/{}", + "{}/v2/embedded-wallet-api/end-users/{}/delegation", client.baseurl, - encode_path(&subscription_id.to_string()), + encode_path(&user_id.to_string()), ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( @@ -85916,276 +99820,398 @@ pub mod builder { #[allow(unused_mut)] let mut request = client .client - .delete(url) + .get(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) + .query(&progenitor_middleware_client::QueryParam::new( + "projectID", + &project_id, + )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "delete_webhook_subscription", + operation_id: "get_delegation_for_end_user", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 204u16 => Ok(ResponseValue::empty(response)), + 200u16 => ResponseValue::from_response::(response).await, 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 429u16 => Err(Error::ErrorResponse( + 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 500u16 => Err(Error::ErrorResponse( + 502u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 503u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::list_webhook_subscription_events`] + /**Builder for [`Client::revoke_delegation_for_end_user`] - [`Client::list_webhook_subscription_events`]: super::Client::list_webhook_subscription_events*/ + [`Client::revoke_delegation_for_end_user`]: super::Client::revoke_delegation_for_end_user*/ #[derive(Debug, Clone)] - pub struct ListWebhookSubscriptionEvents<'a> { + pub struct RevokeDelegationForEndUser<'a> { client: &'a super::Client, - subscription_id: Result<::uuid::Uuid, String>, - event_id: Result, String>, - event_type_names: Result, String>, - max_created_at: Result>, String>, - min_created_at: Result>, String>, + user_id: Result, + project_id: Result, String>, + x_developer_auth: Result, String>, + x_idempotency_key: Result, String>, + x_wallet_auth: Result, String>, + body: Result, } - impl<'a> ListWebhookSubscriptionEvents<'a> { + impl<'a> RevokeDelegationForEndUser<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - subscription_id: Err("subscription_id was not initialized".to_string()), - event_id: Ok(None), - event_type_names: Ok(None), - max_created_at: Ok(None), - min_created_at: Ok(None), + user_id: Err("user_id was not initialized".to_string()), + project_id: Ok(None), + x_developer_auth: Ok(None), + x_idempotency_key: Ok(None), + x_wallet_auth: Ok(None), + body: Ok(::std::default::Default::default()), } } - pub fn subscription_id(mut self, value: V) -> Self + pub fn user_id(mut self, value: V) -> Self where - V: std::convert::TryInto<::uuid::Uuid>, + V: std::convert::TryInto, { - self.subscription_id = value.try_into().map_err(|_| { - "conversion to `:: uuid :: Uuid` for subscription_id failed".to_string() + self.user_id = value.try_into().map_err(|_| { + "conversion to `RevokeDelegationForEndUserUserId` for user_id failed".to_string() }); self } - pub fn event_id(mut self, value: V) -> Self + pub fn project_id(mut self, value: V) -> Self where - V: std::convert::TryInto<::uuid::Uuid>, + V: std::convert::TryInto, { - self.event_id = value - .try_into() - .map(Some) - .map_err(|_| "conversion to `:: uuid :: Uuid` for event_id failed".to_string()); + self.project_id = value.try_into().map(Some).map_err(|_| { + "conversion to `RevokeDelegationForEndUserProjectId` for project_id failed" + .to_string() + }); self } - pub fn event_type_names(mut self, value: V) -> Self + pub fn x_developer_auth(mut self, value: V) -> Self where V: std::convert::TryInto<::std::string::String>, { - self.event_type_names = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: string :: String` for event_type_names failed".to_string() + self.x_developer_auth = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for x_developer_auth failed".to_string() }); self } - pub fn max_created_at(mut self, value: V) -> Self + pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, + V: std::convert::TryInto, { - self.max_created_at = value + self.x_idempotency_key = value .try_into() .map(Some) .map_err(|_| { - "conversion to `:: chrono :: DateTime < :: chrono :: offset :: Utc >` for max_created_at failed" + "conversion to `RevokeDelegationForEndUserXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self } - pub fn min_created_at(mut self, value: V) -> Self + pub fn x_wallet_auth(mut self, value: V) -> Self where - V: std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, + V: std::convert::TryInto<::std::string::String>, { - self.min_created_at = value - .try_into() - .map(Some) - .map_err(|_| { - "conversion to `:: chrono :: DateTime < :: chrono :: offset :: Utc >` for min_created_at failed" - .to_string() - }); + self.x_wallet_auth = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() + }); self } - ///Sends a `GET` request to `/v2/data/webhooks/subscriptions/{subscriptionId}/events` - pub async fn send( - self, - ) -> Result, Error> { + pub fn body(mut self, value: V) -> Self + where + V: std::convert::TryInto, + >::Error: + std::fmt::Display, + { + self.body = value.try_into().map(From::from).map_err(|s| { + format!( + "conversion to `RevokeDelegationForEndUserBody` for body failed: {}", + s + ) + }); + self + } + pub fn body_map(mut self, f: F) -> Self + where + F: std::ops::FnOnce( + types::builder::RevokeDelegationForEndUserBody, + ) -> types::builder::RevokeDelegationForEndUserBody, + { + self.body = self.body.map(f); + self + } + ///Sends a `DELETE` request to `/v2/embedded-wallet-api/end-users/{userId}/delegation` + pub async fn send(self) -> Result, Error> { let Self { client, - subscription_id, - event_id, - event_type_names, - max_created_at, - min_created_at, + user_id, + project_id, + x_developer_auth, + x_idempotency_key, + x_wallet_auth, + body, } = self; - let subscription_id = subscription_id.map_err(Error::InvalidRequest)?; - let event_id = event_id.map_err(Error::InvalidRequest)?; - let event_type_names = event_type_names.map_err(Error::InvalidRequest)?; - let max_created_at = max_created_at.map_err(Error::InvalidRequest)?; - let min_created_at = min_created_at.map_err(Error::InvalidRequest)?; + let user_id = user_id.map_err(Error::InvalidRequest)?; + let project_id = project_id.map_err(Error::InvalidRequest)?; + let x_developer_auth = x_developer_auth.map_err(Error::InvalidRequest)?; + let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; + let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; + let body = body + .and_then(|v| { + types::RevokeDelegationForEndUserBody::try_from(v).map_err(|e| e.to_string()) + }) + .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/data/webhooks/subscriptions/{}/events", + "{}/v2/embedded-wallet-api/end-users/{}/delegation", client.baseurl, - encode_path(&subscription_id.to_string()), + encode_path(&user_id.to_string()), ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(4usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); + if let Some(value) = x_developer_auth { + header_map.append("X-Developer-Auth", value.to_string().try_into()?); + } + if let Some(value) = x_idempotency_key { + header_map.append("X-Idempotency-Key", value.to_string().try_into()?); + } + if let Some(value) = x_wallet_auth { + header_map.append("X-Wallet-Auth", value.to_string().try_into()?); + } #[allow(unused_mut)] let mut request = client .client - .get(url) + .delete(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) + .json(&body) .query(&progenitor_middleware_client::QueryParam::new( - "eventId", &event_id, - )) - .query(&progenitor_middleware_client::QueryParam::new( - "eventTypeNames", - &event_type_names, - )) - .query(&progenitor_middleware_client::QueryParam::new( - "maxCreatedAt", - &max_created_at, - )) - .query(&progenitor_middleware_client::QueryParam::new( - "minCreatedAt", - &min_created_at, + "projectID", + &project_id, )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "list_webhook_subscription_events", + operation_id: "revoke_delegation_for_end_user", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 200u16 => ResponseValue::from_response::(response).await, - 400u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), + 204u16 => Ok(ResponseValue::empty(response)), 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 429u16 => Err(Error::ErrorResponse( + 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 500u16 => Err(Error::ErrorResponse( + 502u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 503u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::get_delegation_for_end_user_account`] + /**Builder for [`Client::create_evm_eip7702_delegation_with_end_user_account`] - [`Client::get_delegation_for_end_user_account`]: super::Client::get_delegation_for_end_user_account*/ + [`Client::create_evm_eip7702_delegation_with_end_user_account`]: super::Client::create_evm_eip7702_delegation_with_end_user_account*/ #[derive(Debug, Clone)] - pub struct GetDelegationForEndUserAccount<'a> { + pub struct CreateEvmEip7702DelegationWithEndUserAccount<'a> { client: &'a super::Client, - user_id: Result, - address: Result, - project_id: Result, String>, + user_id: Result, + project_id: + Result, String>, + x_developer_auth: Result, String>, + x_idempotency_key: Result< + Option, + String, + >, + x_wallet_auth: Result, String>, + body: Result, } - impl<'a> GetDelegationForEndUserAccount<'a> { + impl<'a> CreateEvmEip7702DelegationWithEndUserAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, user_id: Err("user_id was not initialized".to_string()), - address: Err("address was not initialized".to_string()), project_id: Ok(None), + x_developer_auth: Ok(None), + x_idempotency_key: Ok(None), + x_wallet_auth: Ok(None), + body: Ok(::std::default::Default::default()), } } pub fn user_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.user_id = value.try_into().map_err(|_| { - "conversion to `GetDelegationForEndUserAccountUserId` for user_id failed" - .to_string() + self.user_id = value + .try_into() + .map_err(|_| { + "conversion to `CreateEvmEip7702DelegationWithEndUserAccountUserId` for user_id failed" + .to_string() + }); + self + } + pub fn project_id(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.project_id = value + .try_into() + .map(Some) + .map_err(|_| { + "conversion to `CreateEvmEip7702DelegationWithEndUserAccountProjectId` for project_id failed" + .to_string() + }); + self + } + pub fn x_developer_auth(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.x_developer_auth = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for x_developer_auth failed".to_string() }); self } - pub fn address(mut self, value: V) -> Self + pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto< + types::CreateEvmEip7702DelegationWithEndUserAccountXIdempotencyKey, + >, { - self.address = value + self.x_idempotency_key = value .try_into() - .map_err(|_| "conversion to `BlockchainAddress` for address failed".to_string()); + .map(Some) + .map_err(|_| { + "conversion to `CreateEvmEip7702DelegationWithEndUserAccountXIdempotencyKey` for x_idempotency_key failed" + .to_string() + }); self } - pub fn project_id(mut self, value: V) -> Self + pub fn x_wallet_auth(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto<::std::string::String>, { - self.project_id = value.try_into().map(Some).map_err(|_| { - "conversion to `GetDelegationForEndUserAccountProjectId` for project_id failed" - .to_string() + self.x_wallet_auth = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() }); self } - ///Sends a `GET` request to `/v2/embedded-wallet-api/end-users/{userId}/address/{address}/delegation` + pub fn body(mut self, value: V) -> Self + where + V: std::convert::TryInto< + types::CreateEvmEip7702DelegationWithEndUserAccountBody, + >, + >::Error: std::fmt::Display, + { + self.body = value + .try_into() + .map(From::from) + .map_err(|s| { + format!( + "conversion to `CreateEvmEip7702DelegationWithEndUserAccountBody` for body failed: {}", + s + ) + }); + self + } + pub fn body_map(mut self, f: F) -> Self + where + F: std::ops::FnOnce( + types::builder::CreateEvmEip7702DelegationWithEndUserAccountBody, + ) + -> types::builder::CreateEvmEip7702DelegationWithEndUserAccountBody, + { + self.body = self.body.map(f); + self + } + ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/evm/eip7702/delegation` pub async fn send( self, - ) -> Result, Error> - { + ) -> Result< + ResponseValue, + Error, + > { let Self { client, user_id, - address, project_id, + x_developer_auth, + x_idempotency_key, + x_wallet_auth, + body, } = self; let user_id = user_id.map_err(Error::InvalidRequest)?; - let address = address.map_err(Error::InvalidRequest)?; let project_id = project_id.map_err(Error::InvalidRequest)?; + let x_developer_auth = x_developer_auth.map_err(Error::InvalidRequest)?; + let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; + let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; + let body = body + .and_then(|v| { + types::CreateEvmEip7702DelegationWithEndUserAccountBody::try_from(v) + .map_err(|e| e.to_string()) + }) + .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/embedded-wallet-api/end-users/{}/address/{}/delegation", + "{}/v2/embedded-wallet-api/end-users/{}/evm/eip7702/delegation", client.baseurl, encode_path(&user_id.to_string()), - encode_path(&address.to_string()), ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(4usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); + if let Some(value) = x_developer_auth { + header_map.append("X-Developer-Auth", value.to_string().try_into()?); + } + if let Some(value) = x_idempotency_key { + header_map.append("X-Idempotency-Key", value.to_string().try_into()?); + } + if let Some(value) = x_wallet_auth { + header_map.append("X-Wallet-Auth", value.to_string().try_into()?); + } #[allow(unused_mut)] let mut request = client .client - .get(url) + .post(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) + .json(&body) .query(&progenitor_middleware_client::QueryParam::new( "projectID", &project_id, @@ -86193,18 +100219,36 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "get_delegation_for_end_user_account", + operation_id: "create_evm_eip7702_delegation_with_end_user_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 200u16 => ResponseValue::from_response::(response).await, + 201u16 => ResponseValue::from_response::(response).await, + 400u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 404u16 => Err(Error::ErrorResponse( + 402u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 403u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 404u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 409u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 422u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 429u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 500u16 => Err(Error::ErrorResponse( @@ -86220,70 +100264,73 @@ pub mod builder { } } } - /**Builder for [`Client::create_delegation_for_end_user_account`] + /**Builder for [`Client::send_evm_transaction_with_end_user_account`] - [`Client::create_delegation_for_end_user_account`]: super::Client::create_delegation_for_end_user_account*/ + [`Client::send_evm_transaction_with_end_user_account`]: super::Client::send_evm_transaction_with_end_user_account*/ #[derive(Debug, Clone)] - pub struct CreateDelegationForEndUserAccount<'a> { + pub struct SendEvmTransactionWithEndUserAccount<'a> { client: &'a super::Client, - user_id: Result, - address: Result, - project_id: Result, String>, + user_id: Result, + project_id: Result, String>, + x_developer_auth: Result, String>, x_idempotency_key: - Result, String>, - x_wallet_auth: Result<::std::string::String, String>, - body: Result, + Result, String>, + x_wallet_auth: Result, String>, + body: Result, } - impl<'a> CreateDelegationForEndUserAccount<'a> { + impl<'a> SendEvmTransactionWithEndUserAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, user_id: Err("user_id was not initialized".to_string()), - address: Err("address was not initialized".to_string()), project_id: Ok(None), + x_developer_auth: Ok(None), x_idempotency_key: Ok(None), - x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), + x_wallet_auth: Ok(None), body: Ok(::std::default::Default::default()), } } pub fn user_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.user_id = value.try_into().map_err(|_| { - "conversion to `CreateDelegationForEndUserAccountUserId` for user_id failed" + "conversion to `SendEvmTransactionWithEndUserAccountUserId` for user_id failed" .to_string() }); self } - pub fn address(mut self, value: V) -> Self + pub fn project_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.address = value + self.project_id = value .try_into() - .map_err(|_| "conversion to `BlockchainAddress` for address failed".to_string()); + .map(Some) + .map_err(|_| { + "conversion to `SendEvmTransactionWithEndUserAccountProjectId` for project_id failed" + .to_string() + }); self } - pub fn project_id(mut self, value: V) -> Self + pub fn x_developer_auth(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto<::std::string::String>, { - self.project_id = value.try_into().map(Some).map_err(|_| { - "conversion to `CreateDelegationForEndUserAccountProjectId` for project_id failed" - .to_string() + self.x_developer_auth = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for x_developer_auth failed".to_string() }); self } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value .try_into() .map(Some) .map_err(|_| { - "conversion to `CreateDelegationForEndUserAccountXIdempotencyKey` for x_idempotency_key failed" + "conversion to `SendEvmTransactionWithEndUserAccountXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self @@ -86292,20 +100339,20 @@ pub mod builder { where V: std::convert::TryInto<::std::string::String>, { - self.x_wallet_auth = value.try_into().map_err(|_| { + self.x_wallet_auth = value.try_into().map(Some).map_err(|_| { "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() }); self } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: + V: std::convert::TryInto, + >::Error: std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `CreateDelegationForEndUserAccountBody` for body failed: {}", + "conversion to `SendEvmTransactionWithEndUserAccountBody` for body failed: {}", s ) }); @@ -86314,55 +100361,59 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::CreateDelegationForEndUserAccountBody, + types::builder::SendEvmTransactionWithEndUserAccountBody, ) - -> types::builder::CreateDelegationForEndUserAccountBody, + -> types::builder::SendEvmTransactionWithEndUserAccountBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/address/{address}/delegation` + ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/evm/send/transaction` pub async fn send( self, ) -> Result< - ResponseValue, + ResponseValue, Error, > { let Self { client, user_id, - address, project_id, + x_developer_auth, x_idempotency_key, x_wallet_auth, body, } = self; let user_id = user_id.map_err(Error::InvalidRequest)?; - let address = address.map_err(Error::InvalidRequest)?; let project_id = project_id.map_err(Error::InvalidRequest)?; + let x_developer_auth = x_developer_auth.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body .and_then(|v| { - types::CreateDelegationForEndUserAccountBody::try_from(v) + types::SendEvmTransactionWithEndUserAccountBody::try_from(v) .map_err(|e| e.to_string()) }) .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/embedded-wallet-api/end-users/{}/address/{}/delegation", + "{}/v2/embedded-wallet-api/end-users/{}/evm/send/transaction", client.baseurl, encode_path(&user_id.to_string()), - encode_path(&address.to_string()), ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(4usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); + if let Some(value) = x_developer_auth { + header_map.append("X-Developer-Auth", value.to_string().try_into()?); + } if let Some(value) = x_idempotency_key { header_map.append("X-Idempotency-Key", value.to_string().try_into()?); } - header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); + if let Some(value) = x_wallet_auth { + header_map.append("X-Wallet-Auth", value.to_string().try_into()?); + } #[allow(unused_mut)] let mut request = client .client @@ -86379,14 +100430,14 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "create_delegation_for_end_user_account", + operation_id: "send_evm_transaction_with_end_user_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 201u16 => ResponseValue::from_response::(response).await, + 200u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -86396,6 +100447,9 @@ pub mod builder { 402u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 403u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -86405,9 +100459,6 @@ pub mod builder { 422u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 429u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -86421,27 +100472,25 @@ pub mod builder { } } } - /**Builder for [`Client::revoke_delegation_for_end_user_account`] + /**Builder for [`Client::sign_evm_message_with_end_user_account`] - [`Client::revoke_delegation_for_end_user_account`]: super::Client::revoke_delegation_for_end_user_account*/ + [`Client::sign_evm_message_with_end_user_account`]: super::Client::sign_evm_message_with_end_user_account*/ #[derive(Debug, Clone)] - pub struct RevokeDelegationForEndUserAccount<'a> { + pub struct SignEvmMessageWithEndUserAccount<'a> { client: &'a super::Client, - user_id: Result, - address: Result, - project_id: Result, String>, + user_id: Result, + project_id: Result, String>, x_developer_auth: Result, String>, x_idempotency_key: - Result, String>, + Result, String>, x_wallet_auth: Result, String>, - body: Result, + body: Result, } - impl<'a> RevokeDelegationForEndUserAccount<'a> { + impl<'a> SignEvmMessageWithEndUserAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, user_id: Err("user_id was not initialized".to_string()), - address: Err("address was not initialized".to_string()), project_id: Ok(None), x_developer_auth: Ok(None), x_idempotency_key: Ok(None), @@ -86451,29 +100500,20 @@ pub mod builder { } pub fn user_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.user_id = value.try_into().map_err(|_| { - "conversion to `RevokeDelegationForEndUserAccountUserId` for user_id failed" + "conversion to `SignEvmMessageWithEndUserAccountUserId` for user_id failed" .to_string() }); self } - pub fn address(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.address = value - .try_into() - .map_err(|_| "conversion to `BlockchainAddress` for address failed".to_string()); - self - } pub fn project_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.project_id = value.try_into().map(Some).map_err(|_| { - "conversion to `RevokeDelegationForEndUserAccountProjectId` for project_id failed" + "conversion to `SignEvmMessageWithEndUserAccountProjectId` for project_id failed" .to_string() }); self @@ -86489,13 +100529,13 @@ pub mod builder { } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value .try_into() .map(Some) .map_err(|_| { - "conversion to `RevokeDelegationForEndUserAccountXIdempotencyKey` for x_idempotency_key failed" + "conversion to `SignEvmMessageWithEndUserAccountXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self @@ -86511,13 +100551,13 @@ pub mod builder { } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: + V: std::convert::TryInto, + >::Error: std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `RevokeDelegationForEndUserAccountBody` for body failed: {}", + "conversion to `SignEvmMessageWithEndUserAccountBody` for body failed: {}", s ) }); @@ -86526,19 +100566,23 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::RevokeDelegationForEndUserAccountBody, + types::builder::SignEvmMessageWithEndUserAccountBody, ) - -> types::builder::RevokeDelegationForEndUserAccountBody, + -> types::builder::SignEvmMessageWithEndUserAccountBody, { self.body = self.body.map(f); self } - ///Sends a `DELETE` request to `/v2/embedded-wallet-api/end-users/{userId}/address/{address}/delegation` - pub async fn send(self) -> Result, Error> { + ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/evm/sign/message` + pub async fn send( + self, + ) -> Result< + ResponseValue, + Error, + > { let Self { client, user_id, - address, project_id, x_developer_auth, x_idempotency_key, @@ -86546,22 +100590,20 @@ pub mod builder { body, } = self; let user_id = user_id.map_err(Error::InvalidRequest)?; - let address = address.map_err(Error::InvalidRequest)?; let project_id = project_id.map_err(Error::InvalidRequest)?; let x_developer_auth = x_developer_auth.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body .and_then(|v| { - types::RevokeDelegationForEndUserAccountBody::try_from(v) + types::SignEvmMessageWithEndUserAccountBody::try_from(v) .map_err(|e| e.to_string()) }) .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/embedded-wallet-api/end-users/{}/address/{}/delegation", + "{}/v2/embedded-wallet-api/end-users/{}/evm/sign/message", client.baseurl, encode_path(&user_id.to_string()), - encode_path(&address.to_string()), ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(4usize); header_map.append( @@ -86580,7 +100622,7 @@ pub mod builder { #[allow(unused_mut)] let mut request = client .client - .delete(url) + .post(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), @@ -86593,20 +100635,32 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "revoke_delegation_for_end_user_account", + operation_id: "sign_evm_message_with_end_user_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 204u16 => Ok(ResponseValue::empty(response)), + 200u16 => ResponseValue::from_response::(response).await, 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 402u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 403u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 409u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 422u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -86620,71 +100674,165 @@ pub mod builder { } } } - /**Builder for [`Client::get_delegation_for_end_user`] + /**Builder for [`Client::sign_evm_transaction_with_end_user_account`] - [`Client::get_delegation_for_end_user`]: super::Client::get_delegation_for_end_user*/ + [`Client::sign_evm_transaction_with_end_user_account`]: super::Client::sign_evm_transaction_with_end_user_account*/ #[derive(Debug, Clone)] - pub struct GetDelegationForEndUser<'a> { + pub struct SignEvmTransactionWithEndUserAccount<'a> { client: &'a super::Client, - user_id: Result, - project_id: Result, String>, + user_id: Result, + project_id: Result, String>, + x_developer_auth: Result, String>, + x_idempotency_key: + Result, String>, + x_wallet_auth: Result, String>, + body: Result, } - impl<'a> GetDelegationForEndUser<'a> { + impl<'a> SignEvmTransactionWithEndUserAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, user_id: Err("user_id was not initialized".to_string()), project_id: Ok(None), + x_developer_auth: Ok(None), + x_idempotency_key: Ok(None), + x_wallet_auth: Ok(None), + body: Ok(::std::default::Default::default()), } } pub fn user_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.user_id = value.try_into().map_err(|_| { - "conversion to `GetDelegationForEndUserUserId` for user_id failed".to_string() + "conversion to `SignEvmTransactionWithEndUserAccountUserId` for user_id failed" + .to_string() }); self } pub fn project_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.project_id = value.try_into().map(Some).map_err(|_| { - "conversion to `GetDelegationForEndUserProjectId` for project_id failed".to_string() + self.project_id = value + .try_into() + .map(Some) + .map_err(|_| { + "conversion to `SignEvmTransactionWithEndUserAccountProjectId` for project_id failed" + .to_string() + }); + self + } + pub fn x_developer_auth(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.x_developer_auth = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for x_developer_auth failed".to_string() }); self } - ///Sends a `GET` request to `/v2/embedded-wallet-api/end-users/{userId}/delegation` + pub fn x_idempotency_key(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.x_idempotency_key = value + .try_into() + .map(Some) + .map_err(|_| { + "conversion to `SignEvmTransactionWithEndUserAccountXIdempotencyKey` for x_idempotency_key failed" + .to_string() + }); + self + } + pub fn x_wallet_auth(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.x_wallet_auth = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() + }); + self + } + pub fn body(mut self, value: V) -> Self + where + V: std::convert::TryInto, + >::Error: + std::fmt::Display, + { + self.body = value.try_into().map(From::from).map_err(|s| { + format!( + "conversion to `SignEvmTransactionWithEndUserAccountBody` for body failed: {}", + s + ) + }); + self + } + pub fn body_map(mut self, f: F) -> Self + where + F: std::ops::FnOnce( + types::builder::SignEvmTransactionWithEndUserAccountBody, + ) + -> types::builder::SignEvmTransactionWithEndUserAccountBody, + { + self.body = self.body.map(f); + self + } + ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/evm/sign/transaction` pub async fn send( self, - ) -> Result, Error> - { + ) -> Result< + ResponseValue, + Error, + > { let Self { client, user_id, project_id, + x_developer_auth, + x_idempotency_key, + x_wallet_auth, + body, } = self; let user_id = user_id.map_err(Error::InvalidRequest)?; let project_id = project_id.map_err(Error::InvalidRequest)?; + let x_developer_auth = x_developer_auth.map_err(Error::InvalidRequest)?; + let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; + let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; + let body = body + .and_then(|v| { + types::SignEvmTransactionWithEndUserAccountBody::try_from(v) + .map_err(|e| e.to_string()) + }) + .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/embedded-wallet-api/end-users/{}/delegation", + "{}/v2/embedded-wallet-api/end-users/{}/evm/sign/transaction", client.baseurl, encode_path(&user_id.to_string()), ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(4usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); + if let Some(value) = x_developer_auth { + header_map.append("X-Developer-Auth", value.to_string().try_into()?); + } + if let Some(value) = x_idempotency_key { + header_map.append("X-Idempotency-Key", value.to_string().try_into()?); + } + if let Some(value) = x_wallet_auth { + header_map.append("X-Wallet-Auth", value.to_string().try_into()?); + } #[allow(unused_mut)] let mut request = client .client - .get(url) + .post(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) + .json(&body) .query(&progenitor_middleware_client::QueryParam::new( "projectID", &project_id, @@ -86692,7 +100840,7 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "get_delegation_for_end_user", + operation_id: "sign_evm_transaction_with_end_user_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -86700,12 +100848,27 @@ pub mod builder { let response = result?; match response.status().as_u16() { 200u16 => ResponseValue::from_response::(response).await, + 400u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 402u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 403u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 409u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 422u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -86719,20 +100882,21 @@ pub mod builder { } } } - /**Builder for [`Client::revoke_delegation_for_end_user`] + /**Builder for [`Client::sign_evm_typed_data_with_end_user_account`] - [`Client::revoke_delegation_for_end_user`]: super::Client::revoke_delegation_for_end_user*/ + [`Client::sign_evm_typed_data_with_end_user_account`]: super::Client::sign_evm_typed_data_with_end_user_account*/ #[derive(Debug, Clone)] - pub struct RevokeDelegationForEndUser<'a> { + pub struct SignEvmTypedDataWithEndUserAccount<'a> { client: &'a super::Client, - user_id: Result, - project_id: Result, String>, + user_id: Result, + project_id: Result, String>, x_developer_auth: Result, String>, - x_idempotency_key: Result, String>, + x_idempotency_key: + Result, String>, x_wallet_auth: Result, String>, - body: Result, + body: Result, } - impl<'a> RevokeDelegationForEndUser<'a> { + impl<'a> SignEvmTypedDataWithEndUserAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, @@ -86746,19 +100910,20 @@ pub mod builder { } pub fn user_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.user_id = value.try_into().map_err(|_| { - "conversion to `RevokeDelegationForEndUserUserId` for user_id failed".to_string() + "conversion to `SignEvmTypedDataWithEndUserAccountUserId` for user_id failed" + .to_string() }); self } pub fn project_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.project_id = value.try_into().map(Some).map_err(|_| { - "conversion to `RevokeDelegationForEndUserProjectId` for project_id failed" + "conversion to `SignEvmTypedDataWithEndUserAccountProjectId` for project_id failed" .to_string() }); self @@ -86774,13 +100939,13 @@ pub mod builder { } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value .try_into() .map(Some) .map_err(|_| { - "conversion to `RevokeDelegationForEndUserXIdempotencyKey` for x_idempotency_key failed" + "conversion to `SignEvmTypedDataWithEndUserAccountXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self @@ -86796,13 +100961,13 @@ pub mod builder { } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: + V: std::convert::TryInto, + >::Error: std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `RevokeDelegationForEndUserBody` for body failed: {}", + "conversion to `SignEvmTypedDataWithEndUserAccountBody` for body failed: {}", s ) }); @@ -86811,14 +100976,20 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::RevokeDelegationForEndUserBody, - ) -> types::builder::RevokeDelegationForEndUserBody, + types::builder::SignEvmTypedDataWithEndUserAccountBody, + ) + -> types::builder::SignEvmTypedDataWithEndUserAccountBody, { self.body = self.body.map(f); self } - ///Sends a `DELETE` request to `/v2/embedded-wallet-api/end-users/{userId}/delegation` - pub async fn send(self) -> Result, Error> { + ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/evm/sign/typed-data` + pub async fn send( + self, + ) -> Result< + ResponseValue, + Error, + > { let Self { client, user_id, @@ -86835,11 +101006,12 @@ pub mod builder { let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body .and_then(|v| { - types::RevokeDelegationForEndUserBody::try_from(v).map_err(|e| e.to_string()) + types::SignEvmTypedDataWithEndUserAccountBody::try_from(v) + .map_err(|e| e.to_string()) }) .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/embedded-wallet-api/end-users/{}/delegation", + "{}/v2/embedded-wallet-api/end-users/{}/evm/sign/typed-data", client.baseurl, encode_path(&user_id.to_string()), ); @@ -86860,7 +101032,7 @@ pub mod builder { #[allow(unused_mut)] let mut request = client .client - .delete(url) + .post(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), @@ -86873,20 +101045,32 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "revoke_delegation_for_end_user", + operation_id: "sign_evm_typed_data_with_end_user_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 204u16 => Ok(ResponseValue::empty(response)), + 200u16 => ResponseValue::from_response::(response).await, + 400u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 402u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 403u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 422u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -86900,28 +101084,27 @@ pub mod builder { } } } - /**Builder for [`Client::create_evm_eip7702_delegation_with_end_user_account`] + /**Builder for [`Client::send_user_operation_with_end_user_account`] - [`Client::create_evm_eip7702_delegation_with_end_user_account`]: super::Client::create_evm_eip7702_delegation_with_end_user_account*/ + [`Client::send_user_operation_with_end_user_account`]: super::Client::send_user_operation_with_end_user_account*/ #[derive(Debug, Clone)] - pub struct CreateEvmEip7702DelegationWithEndUserAccount<'a> { + pub struct SendUserOperationWithEndUserAccount<'a> { client: &'a super::Client, - user_id: Result, - project_id: - Result, String>, + user_id: Result, + address: Result, + project_id: Result, String>, x_developer_auth: Result, String>, - x_idempotency_key: Result< - Option, - String, - >, + x_idempotency_key: + Result, String>, x_wallet_auth: Result, String>, - body: Result, + body: Result, } - impl<'a> CreateEvmEip7702DelegationWithEndUserAccount<'a> { + impl<'a> SendUserOperationWithEndUserAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, user_id: Err("user_id was not initialized".to_string()), + address: Err("address was not initialized".to_string()), project_id: Ok(None), x_developer_auth: Ok(None), x_idempotency_key: Ok(None), @@ -86931,27 +101114,32 @@ pub mod builder { } pub fn user_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.user_id = value - .try_into() - .map_err(|_| { - "conversion to `CreateEvmEip7702DelegationWithEndUserAccountUserId` for user_id failed" - .to_string() - }); + self.user_id = value.try_into().map_err(|_| { + "conversion to `SendUserOperationWithEndUserAccountUserId` for user_id failed" + .to_string() + }); + self + } + pub fn address(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.address = value.try_into().map_err(|_| { + "conversion to `SendUserOperationWithEndUserAccountAddress` for address failed" + .to_string() + }); self } pub fn project_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.project_id = value - .try_into() - .map(Some) - .map_err(|_| { - "conversion to `CreateEvmEip7702DelegationWithEndUserAccountProjectId` for project_id failed" - .to_string() - }); + self.project_id = value.try_into().map(Some).map_err(|_| { + "conversion to `SendUserOperationWithEndUserAccountProjectId` for project_id failed" + .to_string() + }); self } pub fn x_developer_auth(mut self, value: V) -> Self @@ -86965,15 +101153,13 @@ pub mod builder { } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto< - types::CreateEvmEip7702DelegationWithEndUserAccountXIdempotencyKey, - >, + V: std::convert::TryInto, { self.x_idempotency_key = value .try_into() .map(Some) .map_err(|_| { - "conversion to `CreateEvmEip7702DelegationWithEndUserAccountXIdempotencyKey` for x_idempotency_key failed" + "conversion to `SendUserOperationWithEndUserAccountXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self @@ -86989,44 +101175,36 @@ pub mod builder { } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto< - types::CreateEvmEip7702DelegationWithEndUserAccountBody, - >, - >::Error: std::fmt::Display, + V: std::convert::TryInto, + >::Error: + std::fmt::Display, { - self.body = value - .try_into() - .map(From::from) - .map_err(|s| { - format!( - "conversion to `CreateEvmEip7702DelegationWithEndUserAccountBody` for body failed: {}", - s - ) - }); + self.body = value.try_into().map(From::from).map_err(|s| { + format!( + "conversion to `SendUserOperationWithEndUserAccountBody` for body failed: {}", + s + ) + }); self } pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::CreateEvmEip7702DelegationWithEndUserAccountBody, + types::builder::SendUserOperationWithEndUserAccountBody, ) - -> types::builder::CreateEvmEip7702DelegationWithEndUserAccountBody, + -> types::builder::SendUserOperationWithEndUserAccountBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/evm/eip7702/delegation` + ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/evm/smart-accounts/{address}/send` pub async fn send( self, - ) -> Result< - ResponseValue, - Error, - > { + ) -> Result, Error> { let Self { client, user_id, + address, project_id, x_developer_auth, x_idempotency_key, @@ -87034,20 +101212,22 @@ pub mod builder { body, } = self; let user_id = user_id.map_err(Error::InvalidRequest)?; + let address = address.map_err(Error::InvalidRequest)?; let project_id = project_id.map_err(Error::InvalidRequest)?; let x_developer_auth = x_developer_auth.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body .and_then(|v| { - types::CreateEvmEip7702DelegationWithEndUserAccountBody::try_from(v) + types::SendUserOperationWithEndUserAccountBody::try_from(v) .map_err(|e| e.to_string()) }) .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/embedded-wallet-api/end-users/{}/evm/eip7702/delegation", + "{}/v2/embedded-wallet-api/end-users/{}/evm/smart-accounts/{}/send", client.baseurl, encode_path(&user_id.to_string()), + encode_path(&address.to_string()), ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(4usize); header_map.append( @@ -87079,14 +101259,14 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "create_evm_eip7702_delegation_with_end_user_account", + operation_id: "send_user_operation_with_end_user_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 201u16 => ResponseValue::from_response::(response).await, + 200u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -87096,13 +101276,10 @@ pub mod builder { 402u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 404u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 409u16 => Err(Error::ErrorResponse( + 403u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 422u16 => Err(Error::ErrorResponse( + 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 429u16 => Err(Error::ErrorResponse( @@ -87121,25 +101298,29 @@ pub mod builder { } } } - /**Builder for [`Client::send_evm_transaction_with_end_user_account`] + /**Builder for [`Client::send_evm_asset_with_end_user_account`] - [`Client::send_evm_transaction_with_end_user_account`]: super::Client::send_evm_transaction_with_end_user_account*/ + [`Client::send_evm_asset_with_end_user_account`]: super::Client::send_evm_asset_with_end_user_account*/ #[derive(Debug, Clone)] - pub struct SendEvmTransactionWithEndUserAccount<'a> { + pub struct SendEvmAssetWithEndUserAccount<'a> { client: &'a super::Client, - user_id: Result, - project_id: Result, String>, + user_id: Result, + address: Result, + asset: Result, + project_id: Result, String>, x_developer_auth: Result, String>, x_idempotency_key: - Result, String>, + Result, String>, x_wallet_auth: Result, String>, - body: Result, + body: Result, } - impl<'a> SendEvmTransactionWithEndUserAccount<'a> { + impl<'a> SendEvmAssetWithEndUserAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, user_id: Err("user_id was not initialized".to_string()), + address: Err("address was not initialized".to_string()), + asset: Err("asset was not initialized".to_string()), project_id: Ok(None), x_developer_auth: Ok(None), x_idempotency_key: Ok(None), @@ -87149,25 +101330,40 @@ pub mod builder { } pub fn user_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.user_id = value.try_into().map_err(|_| { - "conversion to `SendEvmTransactionWithEndUserAccountUserId` for user_id failed" + "conversion to `SendEvmAssetWithEndUserAccountUserId` for user_id failed" .to_string() }); self } - pub fn project_id(mut self, value: V) -> Self + pub fn address(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.project_id = value + self.address = value .try_into() - .map(Some) - .map_err(|_| { - "conversion to `SendEvmTransactionWithEndUserAccountProjectId` for project_id failed" - .to_string() - }); + .map_err(|_| "conversion to `BlockchainAddress` for address failed".to_string()); + self + } + pub fn asset(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.asset = value + .try_into() + .map_err(|_| "conversion to `Asset` for asset failed".to_string()); + self + } + pub fn project_id(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.project_id = value.try_into().map(Some).map_err(|_| { + "conversion to `SendEvmAssetWithEndUserAccountProjectId` for project_id failed" + .to_string() + }); self } pub fn x_developer_auth(mut self, value: V) -> Self @@ -87181,13 +101377,13 @@ pub mod builder { } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value .try_into() .map(Some) .map_err(|_| { - "conversion to `SendEvmTransactionWithEndUserAccountXIdempotencyKey` for x_idempotency_key failed" + "conversion to `SendEvmAssetWithEndUserAccountXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self @@ -87203,13 +101399,13 @@ pub mod builder { } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: + V: std::convert::TryInto, + >::Error: std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `SendEvmTransactionWithEndUserAccountBody` for body failed: {}", + "conversion to `SendEvmAssetWithEndUserAccountBody` for body failed: {}", s ) }); @@ -87218,23 +101414,22 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::SendEvmTransactionWithEndUserAccountBody, - ) - -> types::builder::SendEvmTransactionWithEndUserAccountBody, + types::builder::SendEvmAssetWithEndUserAccountBody, + ) -> types::builder::SendEvmAssetWithEndUserAccountBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/evm/send/transaction` + ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/evm/{address}/send/{asset}` pub async fn send( self, - ) -> Result< - ResponseValue, - Error, - > { + ) -> Result, Error> + { let Self { client, user_id, + address, + asset, project_id, x_developer_auth, x_idempotency_key, @@ -87242,20 +101437,24 @@ pub mod builder { body, } = self; let user_id = user_id.map_err(Error::InvalidRequest)?; + let address = address.map_err(Error::InvalidRequest)?; + let asset = asset.map_err(Error::InvalidRequest)?; let project_id = project_id.map_err(Error::InvalidRequest)?; let x_developer_auth = x_developer_auth.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body .and_then(|v| { - types::SendEvmTransactionWithEndUserAccountBody::try_from(v) + types::SendEvmAssetWithEndUserAccountBody::try_from(v) .map_err(|e| e.to_string()) }) .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/embedded-wallet-api/end-users/{}/evm/send/transaction", + "{}/v2/embedded-wallet-api/end-users/{}/evm/{}/send/{}", client.baseurl, encode_path(&user_id.to_string()), + encode_path(&address.to_string()), + encode_path(&asset.to_string()), ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(4usize); header_map.append( @@ -87287,7 +101486,7 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "send_evm_transaction_with_end_user_account", + operation_id: "send_evm_asset_with_end_user_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -87310,9 +101509,6 @@ pub mod builder { 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 409u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 422u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -87329,21 +101525,21 @@ pub mod builder { } } } - /**Builder for [`Client::sign_evm_message_with_end_user_account`] + /**Builder for [`Client::send_solana_transaction_with_end_user_account`] - [`Client::sign_evm_message_with_end_user_account`]: super::Client::sign_evm_message_with_end_user_account*/ + [`Client::send_solana_transaction_with_end_user_account`]: super::Client::send_solana_transaction_with_end_user_account*/ #[derive(Debug, Clone)] - pub struct SignEvmMessageWithEndUserAccount<'a> { + pub struct SendSolanaTransactionWithEndUserAccount<'a> { client: &'a super::Client, - user_id: Result, - project_id: Result, String>, + user_id: Result, + project_id: Result, String>, x_developer_auth: Result, String>, x_idempotency_key: - Result, String>, + Result, String>, x_wallet_auth: Result, String>, - body: Result, + body: Result, } - impl<'a> SignEvmMessageWithEndUserAccount<'a> { + impl<'a> SendSolanaTransactionWithEndUserAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, @@ -87357,22 +101553,25 @@ pub mod builder { } pub fn user_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.user_id = value.try_into().map_err(|_| { - "conversion to `SignEvmMessageWithEndUserAccountUserId` for user_id failed" + "conversion to `SendSolanaTransactionWithEndUserAccountUserId` for user_id failed" .to_string() }); self } pub fn project_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.project_id = value.try_into().map(Some).map_err(|_| { - "conversion to `SignEvmMessageWithEndUserAccountProjectId` for project_id failed" - .to_string() - }); + self.project_id = value + .try_into() + .map(Some) + .map_err(|_| { + "conversion to `SendSolanaTransactionWithEndUserAccountProjectId` for project_id failed" + .to_string() + }); self } pub fn x_developer_auth(mut self, value: V) -> Self @@ -87386,13 +101585,13 @@ pub mod builder { } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value .try_into() .map(Some) .map_err(|_| { - "conversion to `SignEvmMessageWithEndUserAccountXIdempotencyKey` for x_idempotency_key failed" + "conversion to `SendSolanaTransactionWithEndUserAccountXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self @@ -87408,33 +101607,36 @@ pub mod builder { } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: + V: std::convert::TryInto, + >::Error: std::fmt::Display, { - self.body = value.try_into().map(From::from).map_err(|s| { - format!( - "conversion to `SignEvmMessageWithEndUserAccountBody` for body failed: {}", - s - ) - }); + self.body = value + .try_into() + .map(From::from) + .map_err(|s| { + format!( + "conversion to `SendSolanaTransactionWithEndUserAccountBody` for body failed: {}", + s + ) + }); self } pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::SignEvmMessageWithEndUserAccountBody, + types::builder::SendSolanaTransactionWithEndUserAccountBody, ) - -> types::builder::SignEvmMessageWithEndUserAccountBody, + -> types::builder::SendSolanaTransactionWithEndUserAccountBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/evm/sign/message` + ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/solana/send/transaction` pub async fn send( self, ) -> Result< - ResponseValue, + ResponseValue, Error, > { let Self { @@ -87453,12 +101655,12 @@ pub mod builder { let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body .and_then(|v| { - types::SignEvmMessageWithEndUserAccountBody::try_from(v) + types::SendSolanaTransactionWithEndUserAccountBody::try_from(v) .map_err(|e| e.to_string()) }) .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/embedded-wallet-api/end-users/{}/evm/sign/message", + "{}/v2/embedded-wallet-api/end-users/{}/solana/send/transaction", client.baseurl, encode_path(&user_id.to_string()), ); @@ -87492,7 +101694,7 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "sign_evm_message_with_end_user_account", + operation_id: "send_solana_transaction_with_end_user_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -87500,16 +101702,19 @@ pub mod builder { let response = result?; match response.status().as_u16() { 200u16 => ResponseValue::from_response::(response).await, + 400u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 402u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 404u16 => Err(Error::ErrorResponse( + 403u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 409u16 => Err(Error::ErrorResponse( + 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 422u16 => Err(Error::ErrorResponse( @@ -87528,21 +101733,21 @@ pub mod builder { } } } - /**Builder for [`Client::sign_evm_transaction_with_end_user_account`] + /**Builder for [`Client::sign_solana_message_with_end_user_account`] - [`Client::sign_evm_transaction_with_end_user_account`]: super::Client::sign_evm_transaction_with_end_user_account*/ + [`Client::sign_solana_message_with_end_user_account`]: super::Client::sign_solana_message_with_end_user_account*/ #[derive(Debug, Clone)] - pub struct SignEvmTransactionWithEndUserAccount<'a> { + pub struct SignSolanaMessageWithEndUserAccount<'a> { client: &'a super::Client, - user_id: Result, - project_id: Result, String>, + user_id: Result, + project_id: Result, String>, x_developer_auth: Result, String>, x_idempotency_key: - Result, String>, + Result, String>, x_wallet_auth: Result, String>, - body: Result, + body: Result, } - impl<'a> SignEvmTransactionWithEndUserAccount<'a> { + impl<'a> SignSolanaMessageWithEndUserAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, @@ -87556,25 +101761,22 @@ pub mod builder { } pub fn user_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.user_id = value.try_into().map_err(|_| { - "conversion to `SignEvmTransactionWithEndUserAccountUserId` for user_id failed" + "conversion to `SignSolanaMessageWithEndUserAccountUserId` for user_id failed" .to_string() }); self } pub fn project_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.project_id = value - .try_into() - .map(Some) - .map_err(|_| { - "conversion to `SignEvmTransactionWithEndUserAccountProjectId` for project_id failed" - .to_string() - }); + self.project_id = value.try_into().map(Some).map_err(|_| { + "conversion to `SignSolanaMessageWithEndUserAccountProjectId` for project_id failed" + .to_string() + }); self } pub fn x_developer_auth(mut self, value: V) -> Self @@ -87588,13 +101790,13 @@ pub mod builder { } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value .try_into() .map(Some) .map_err(|_| { - "conversion to `SignEvmTransactionWithEndUserAccountXIdempotencyKey` for x_idempotency_key failed" + "conversion to `SignSolanaMessageWithEndUserAccountXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self @@ -87610,13 +101812,13 @@ pub mod builder { } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: + V: std::convert::TryInto, + >::Error: std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `SignEvmTransactionWithEndUserAccountBody` for body failed: {}", + "conversion to `SignSolanaMessageWithEndUserAccountBody` for body failed: {}", s ) }); @@ -87625,18 +101827,18 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::SignEvmTransactionWithEndUserAccountBody, + types::builder::SignSolanaMessageWithEndUserAccountBody, ) - -> types::builder::SignEvmTransactionWithEndUserAccountBody, + -> types::builder::SignSolanaMessageWithEndUserAccountBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/evm/sign/transaction` + ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/solana/sign/message` pub async fn send( self, ) -> Result< - ResponseValue, + ResponseValue, Error, > { let Self { @@ -87655,12 +101857,12 @@ pub mod builder { let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body .and_then(|v| { - types::SignEvmTransactionWithEndUserAccountBody::try_from(v) + types::SignSolanaMessageWithEndUserAccountBody::try_from(v) .map_err(|e| e.to_string()) }) .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/embedded-wallet-api/end-users/{}/evm/sign/transaction", + "{}/v2/embedded-wallet-api/end-users/{}/solana/sign/message", client.baseurl, encode_path(&user_id.to_string()), ); @@ -87694,7 +101896,7 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "sign_evm_transaction_with_end_user_account", + operation_id: "sign_solana_message_with_end_user_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -87736,21 +101938,21 @@ pub mod builder { } } } - /**Builder for [`Client::sign_evm_typed_data_with_end_user_account`] + /**Builder for [`Client::sign_solana_transaction_with_end_user_account`] - [`Client::sign_evm_typed_data_with_end_user_account`]: super::Client::sign_evm_typed_data_with_end_user_account*/ + [`Client::sign_solana_transaction_with_end_user_account`]: super::Client::sign_solana_transaction_with_end_user_account*/ #[derive(Debug, Clone)] - pub struct SignEvmTypedDataWithEndUserAccount<'a> { + pub struct SignSolanaTransactionWithEndUserAccount<'a> { client: &'a super::Client, - user_id: Result, - project_id: Result, String>, + user_id: Result, + project_id: Result, String>, x_developer_auth: Result, String>, x_idempotency_key: - Result, String>, + Result, String>, x_wallet_auth: Result, String>, - body: Result, + body: Result, } - impl<'a> SignEvmTypedDataWithEndUserAccount<'a> { + impl<'a> SignSolanaTransactionWithEndUserAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, @@ -87764,22 +101966,25 @@ pub mod builder { } pub fn user_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.user_id = value.try_into().map_err(|_| { - "conversion to `SignEvmTypedDataWithEndUserAccountUserId` for user_id failed" + "conversion to `SignSolanaTransactionWithEndUserAccountUserId` for user_id failed" .to_string() }); self } pub fn project_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.project_id = value.try_into().map(Some).map_err(|_| { - "conversion to `SignEvmTypedDataWithEndUserAccountProjectId` for project_id failed" - .to_string() - }); + self.project_id = value + .try_into() + .map(Some) + .map_err(|_| { + "conversion to `SignSolanaTransactionWithEndUserAccountProjectId` for project_id failed" + .to_string() + }); self } pub fn x_developer_auth(mut self, value: V) -> Self @@ -87793,13 +101998,13 @@ pub mod builder { } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value .try_into() .map(Some) .map_err(|_| { - "conversion to `SignEvmTypedDataWithEndUserAccountXIdempotencyKey` for x_idempotency_key failed" + "conversion to `SignSolanaTransactionWithEndUserAccountXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self @@ -87815,33 +102020,36 @@ pub mod builder { } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: + V: std::convert::TryInto, + >::Error: std::fmt::Display, { - self.body = value.try_into().map(From::from).map_err(|s| { - format!( - "conversion to `SignEvmTypedDataWithEndUserAccountBody` for body failed: {}", - s - ) - }); + self.body = value + .try_into() + .map(From::from) + .map_err(|s| { + format!( + "conversion to `SignSolanaTransactionWithEndUserAccountBody` for body failed: {}", + s + ) + }); self } pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::SignEvmTypedDataWithEndUserAccountBody, + types::builder::SignSolanaTransactionWithEndUserAccountBody, ) - -> types::builder::SignEvmTypedDataWithEndUserAccountBody, + -> types::builder::SignSolanaTransactionWithEndUserAccountBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/evm/sign/typed-data` + ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/solana/sign/transaction` pub async fn send( self, ) -> Result< - ResponseValue, + ResponseValue, Error, > { let Self { @@ -87860,12 +102068,12 @@ pub mod builder { let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body .and_then(|v| { - types::SignEvmTypedDataWithEndUserAccountBody::try_from(v) + types::SignSolanaTransactionWithEndUserAccountBody::try_from(v) .map_err(|e| e.to_string()) }) .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/embedded-wallet-api/end-users/{}/evm/sign/typed-data", + "{}/v2/embedded-wallet-api/end-users/{}/solana/sign/transaction", client.baseurl, encode_path(&user_id.to_string()), ); @@ -87899,7 +102107,7 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "sign_evm_typed_data_with_end_user_account", + operation_id: "sign_solana_transaction_with_end_user_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -87916,9 +102124,15 @@ pub mod builder { 402u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 403u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 409u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 422u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -87935,27 +102149,29 @@ pub mod builder { } } } - /**Builder for [`Client::send_user_operation_with_end_user_account`] + /**Builder for [`Client::send_solana_asset_with_end_user_account`] - [`Client::send_user_operation_with_end_user_account`]: super::Client::send_user_operation_with_end_user_account*/ + [`Client::send_solana_asset_with_end_user_account`]: super::Client::send_solana_asset_with_end_user_account*/ #[derive(Debug, Clone)] - pub struct SendUserOperationWithEndUserAccount<'a> { + pub struct SendSolanaAssetWithEndUserAccount<'a> { client: &'a super::Client, - user_id: Result, - address: Result, - project_id: Result, String>, + user_id: Result, + address: Result, + asset: Result, + project_id: Result, String>, x_developer_auth: Result, String>, x_idempotency_key: - Result, String>, + Result, String>, x_wallet_auth: Result, String>, - body: Result, + body: Result, } - impl<'a> SendUserOperationWithEndUserAccount<'a> { + impl<'a> SendSolanaAssetWithEndUserAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, user_id: Err("user_id was not initialized".to_string()), address: Err("address was not initialized".to_string()), + asset: Err("asset was not initialized".to_string()), project_id: Ok(None), x_developer_auth: Ok(None), x_idempotency_key: Ok(None), @@ -87965,30 +102181,38 @@ pub mod builder { } pub fn user_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.user_id = value.try_into().map_err(|_| { - "conversion to `SendUserOperationWithEndUserAccountUserId` for user_id failed" + "conversion to `SendSolanaAssetWithEndUserAccountUserId` for user_id failed" .to_string() }); self } pub fn address(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.address = value.try_into().map_err(|_| { - "conversion to `SendUserOperationWithEndUserAccountAddress` for address failed" - .to_string() - }); + self.address = value + .try_into() + .map_err(|_| "conversion to `BlockchainAddress` for address failed".to_string()); + self + } + pub fn asset(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.asset = value + .try_into() + .map_err(|_| "conversion to `Asset` for asset failed".to_string()); self } pub fn project_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.project_id = value.try_into().map(Some).map_err(|_| { - "conversion to `SendUserOperationWithEndUserAccountProjectId` for project_id failed" + "conversion to `SendSolanaAssetWithEndUserAccountProjectId` for project_id failed" .to_string() }); self @@ -88004,13 +102228,13 @@ pub mod builder { } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value .try_into() .map(Some) .map_err(|_| { - "conversion to `SendUserOperationWithEndUserAccountXIdempotencyKey` for x_idempotency_key failed" + "conversion to `SendSolanaAssetWithEndUserAccountXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self @@ -88026,13 +102250,13 @@ pub mod builder { } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: + V: std::convert::TryInto, + >::Error: std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `SendUserOperationWithEndUserAccountBody` for body failed: {}", + "conversion to `SendSolanaAssetWithEndUserAccountBody` for body failed: {}", s ) }); @@ -88041,21 +102265,25 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::SendUserOperationWithEndUserAccountBody, + types::builder::SendSolanaAssetWithEndUserAccountBody, ) - -> types::builder::SendUserOperationWithEndUserAccountBody, + -> types::builder::SendSolanaAssetWithEndUserAccountBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/evm/smart-accounts/{address}/send` + ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/solana/{address}/send/{asset}` pub async fn send( self, - ) -> Result, Error> { + ) -> Result< + ResponseValue, + Error, + > { let Self { client, user_id, address, + asset, project_id, x_developer_auth, x_idempotency_key, @@ -88064,21 +102292,23 @@ pub mod builder { } = self; let user_id = user_id.map_err(Error::InvalidRequest)?; let address = address.map_err(Error::InvalidRequest)?; + let asset = asset.map_err(Error::InvalidRequest)?; let project_id = project_id.map_err(Error::InvalidRequest)?; let x_developer_auth = x_developer_auth.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body .and_then(|v| { - types::SendUserOperationWithEndUserAccountBody::try_from(v) + types::SendSolanaAssetWithEndUserAccountBody::try_from(v) .map_err(|e| e.to_string()) }) .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/embedded-wallet-api/end-users/{}/evm/smart-accounts/{}/send", + "{}/v2/embedded-wallet-api/end-users/{}/solana/{}/send/{}", client.baseurl, encode_path(&user_id.to_string()), encode_path(&address.to_string()), + encode_path(&asset.to_string()), ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(4usize); header_map.append( @@ -88110,7 +102340,7 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "send_user_operation_with_end_user_account", + operation_id: "send_solana_asset_with_end_user_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -88133,7 +102363,7 @@ pub mod builder { 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 429u16 => Err(Error::ErrorResponse( + 422u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 500u16 => Err(Error::ErrorResponse( @@ -88149,114 +102379,264 @@ pub mod builder { } } } - /**Builder for [`Client::send_evm_asset_with_end_user_account`] + /**Builder for [`Client::list_end_users`] - [`Client::send_evm_asset_with_end_user_account`]: super::Client::send_evm_asset_with_end_user_account*/ + [`Client::list_end_users`]: super::Client::list_end_users*/ #[derive(Debug, Clone)] - pub struct SendEvmAssetWithEndUserAccount<'a> { + pub struct ListEndUsers<'a> { client: &'a super::Client, - user_id: Result, - address: Result, - asset: Result, - project_id: Result, String>, - x_developer_auth: Result, String>, - x_idempotency_key: - Result, String>, - x_wallet_auth: Result, String>, - body: Result, + page_size: Result, String>, + page_token: Result, String>, + sort: Result>, String>, } - impl<'a> SendEvmAssetWithEndUserAccount<'a> { + impl<'a> ListEndUsers<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - user_id: Err("user_id was not initialized".to_string()), - address: Err("address was not initialized".to_string()), - asset: Err("asset was not initialized".to_string()), - project_id: Ok(None), - x_developer_auth: Ok(None), - x_idempotency_key: Ok(None), - x_wallet_auth: Ok(None), - body: Ok(::std::default::Default::default()), + page_size: Ok(None), + page_token: Ok(None), + sort: Ok(None), } } - pub fn user_id(mut self, value: V) -> Self + pub fn page_size(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto<::std::num::NonZeroU64>, { - self.user_id = value.try_into().map_err(|_| { - "conversion to `SendEvmAssetWithEndUserAccountUserId` for user_id failed" - .to_string() + self.page_size = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: num :: NonZeroU64` for page_size failed".to_string() }); self } - pub fn address(mut self, value: V) -> Self + pub fn page_token(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto<::std::string::String>, { - self.address = value - .try_into() - .map_err(|_| "conversion to `BlockchainAddress` for address failed".to_string()); + self.page_token = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for page_token failed".to_string() + }); self } - pub fn asset(mut self, value: V) -> Self + pub fn sort(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto<::std::vec::Vec>, { - self.asset = value - .try_into() - .map_err(|_| "conversion to `Asset` for asset failed".to_string()); + self.sort = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: vec :: Vec < ListEndUsersSortItem >` for sort failed" + .to_string() + }); self } - pub fn project_id(mut self, value: V) -> Self + ///Sends a `GET` request to `/v2/end-users` + pub async fn send( + self, + ) -> Result, Error> { + let Self { + client, + page_size, + page_token, + sort, + } = self; + let page_size = page_size.map_err(Error::InvalidRequest)?; + let page_token = page_token.map_err(Error::InvalidRequest)?; + let sort = sort.map_err(Error::InvalidRequest)?; + let url = format!("{}/v2/end-users", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + #[allow(unused_mut)] + let mut request = client + .client + .get(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .query(&progenitor_middleware_client::QueryParam::new( + "pageSize", &page_size, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "pageToken", + &page_token, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "sort", &sort, + )) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "list_end_users", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 200u16 => ResponseValue::from_response::(response).await, + 400u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 401u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 500u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 502u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 503u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + _ => Err(Error::UnexpectedResponse(response)), + } + } + } + /**Builder for [`Client::create_end_user`] + + [`Client::create_end_user`]: super::Client::create_end_user*/ + #[derive(Debug, Clone)] + pub struct CreateEndUser<'a> { + client: &'a super::Client, + x_idempotency_key: Result, String>, + x_wallet_auth: Result<::std::string::String, String>, + body: Result, + } + impl<'a> CreateEndUser<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + x_idempotency_key: Ok(None), + x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), + body: Ok(::std::default::Default::default()), + } + } + pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.project_id = value.try_into().map(Some).map_err(|_| { - "conversion to `SendEvmAssetWithEndUserAccountProjectId` for project_id failed" + self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { + "conversion to `CreateEndUserXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self } - pub fn x_developer_auth(mut self, value: V) -> Self + pub fn x_wallet_auth(mut self, value: V) -> Self where V: std::convert::TryInto<::std::string::String>, { - self.x_developer_auth = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: string :: String` for x_developer_auth failed".to_string() + self.x_wallet_auth = value.try_into().map_err(|_| { + "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() }); self } - pub fn x_idempotency_key(mut self, value: V) -> Self + pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, + >::Error: std::fmt::Display, { - self.x_idempotency_key = value + self.body = value .try_into() - .map(Some) - .map_err(|_| { - "conversion to `SendEvmAssetWithEndUserAccountXIdempotencyKey` for x_idempotency_key failed" - .to_string() - }); + .map(From::from) + .map_err(|s| format!("conversion to `CreateEndUserBody` for body failed: {}", s)); self } - pub fn x_wallet_auth(mut self, value: V) -> Self + pub fn body_map(mut self, f: F) -> Self where - V: std::convert::TryInto<::std::string::String>, + F: std::ops::FnOnce( + types::builder::CreateEndUserBody, + ) -> types::builder::CreateEndUserBody, { - self.x_wallet_auth = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() - }); + self.body = self.body.map(f); self } + ///Sends a `POST` request to `/v2/end-users` + pub async fn send(self) -> Result, Error> { + let Self { + client, + x_idempotency_key, + x_wallet_auth, + body, + } = self; + let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; + let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; + let body = body + .and_then(|v| types::CreateEndUserBody::try_from(v).map_err(|e| e.to_string())) + .map_err(Error::InvalidRequest)?; + let url = format!("{}/v2/end-users", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + if let Some(value) = x_idempotency_key { + header_map.append("X-Idempotency-Key", value.to_string().try_into()?); + } + header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); + #[allow(unused_mut)] + let mut request = client + .client + .post(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .json(&body) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "create_end_user", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 201u16 => ResponseValue::from_response::(response).await, + 400u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 401u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 402u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 422u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 500u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + _ => Err(Error::UnexpectedResponse(response)), + } + } + } + /**Builder for [`Client::validate_end_user_access_token`] + + [`Client::validate_end_user_access_token`]: super::Client::validate_end_user_access_token*/ + #[derive(Debug, Clone)] + pub struct ValidateEndUserAccessToken<'a> { + client: &'a super::Client, + body: Result, + } + impl<'a> ValidateEndUserAccessToken<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + body: Ok(::std::default::Default::default()), + } + } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: + V: std::convert::TryInto, + >::Error: std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `SendEvmAssetWithEndUserAccountBody` for body failed: {}", + "conversion to `ValidateEndUserAccessTokenBody` for body failed: {}", s ) }); @@ -88265,62 +102645,143 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::SendEvmAssetWithEndUserAccountBody, - ) -> types::builder::SendEvmAssetWithEndUserAccountBody, + types::builder::ValidateEndUserAccessTokenBody, + ) -> types::builder::ValidateEndUserAccessTokenBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/evm/{address}/send/{asset}` - pub async fn send( - self, - ) -> Result, Error> + ///Sends a `POST` request to `/v2/end-users/auth/validate-token` + pub async fn send(self) -> Result, Error> { + let Self { client, body } = self; + let body = body + .and_then(|v| { + types::ValidateEndUserAccessTokenBody::try_from(v).map_err(|e| e.to_string()) + }) + .map_err(Error::InvalidRequest)?; + let url = format!("{}/v2/end-users/auth/validate-token", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + #[allow(unused_mut)] + let mut request = client + .client + .post(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .json(&body) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "validate_end_user_access_token", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 200u16 => ResponseValue::from_response::(response).await, + 400u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 401u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 404u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 500u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + _ => Err(Error::UnexpectedResponse(response)), + } + } + } + /**Builder for [`Client::import_end_user`] + + [`Client::import_end_user`]: super::Client::import_end_user*/ + #[derive(Debug, Clone)] + pub struct ImportEndUser<'a> { + client: &'a super::Client, + x_idempotency_key: Result, String>, + x_wallet_auth: Result<::std::string::String, String>, + body: Result, + } + impl<'a> ImportEndUser<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + x_idempotency_key: Ok(None), + x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), + body: Ok(::std::default::Default::default()), + } + } + pub fn x_idempotency_key(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { + "conversion to `ImportEndUserXIdempotencyKey` for x_idempotency_key failed" + .to_string() + }); + self + } + pub fn x_wallet_auth(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.x_wallet_auth = value.try_into().map_err(|_| { + "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() + }); + self + } + pub fn body(mut self, value: V) -> Self + where + V: std::convert::TryInto, + >::Error: std::fmt::Display, + { + self.body = value + .try_into() + .map(From::from) + .map_err(|s| format!("conversion to `ImportEndUserBody` for body failed: {}", s)); + self + } + pub fn body_map(mut self, f: F) -> Self + where + F: std::ops::FnOnce( + types::builder::ImportEndUserBody, + ) -> types::builder::ImportEndUserBody, { + self.body = self.body.map(f); + self + } + ///Sends a `POST` request to `/v2/end-users/import` + pub async fn send(self) -> Result, Error> { let Self { client, - user_id, - address, - asset, - project_id, - x_developer_auth, x_idempotency_key, x_wallet_auth, body, } = self; - let user_id = user_id.map_err(Error::InvalidRequest)?; - let address = address.map_err(Error::InvalidRequest)?; - let asset = asset.map_err(Error::InvalidRequest)?; - let project_id = project_id.map_err(Error::InvalidRequest)?; - let x_developer_auth = x_developer_auth.map_err(Error::InvalidRequest)?; - let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; - let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; - let body = body - .and_then(|v| { - types::SendEvmAssetWithEndUserAccountBody::try_from(v) - .map_err(|e| e.to_string()) - }) - .map_err(Error::InvalidRequest)?; - let url = format!( - "{}/v2/embedded-wallet-api/end-users/{}/evm/{}/send/{}", - client.baseurl, - encode_path(&user_id.to_string()), - encode_path(&address.to_string()), - encode_path(&asset.to_string()), - ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(4usize); + let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; + let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; + let body = body + .and_then(|v| types::ImportEndUserBody::try_from(v).map_err(|e| e.to_string())) + .map_err(Error::InvalidRequest)?; + let url = format!("{}/v2/end-users/import", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); - if let Some(value) = x_developer_auth { - header_map.append("X-Developer-Auth", value.to_string().try_into()?); - } if let Some(value) = x_idempotency_key { header_map.append("X-Idempotency-Key", value.to_string().try_into()?); } - if let Some(value) = x_wallet_auth { - header_map.append("X-Wallet-Auth", value.to_string().try_into()?); - } + header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client @@ -88330,21 +102791,17 @@ pub mod builder { ::reqwest::header::HeaderValue::from_static("application/json"), ) .json(&body) - .query(&progenitor_middleware_client::QueryParam::new( - "projectID", - &project_id, - )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "send_evm_asset_with_end_user_account", + operation_id: "import_end_user", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 200u16 => ResponseValue::from_response::(response).await, + 201u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -88354,7 +102811,7 @@ pub mod builder { 402u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 404u16 => Err(Error::ErrorResponse( + 409u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 422u16 => Err(Error::ErrorResponse( @@ -88373,176 +102830,111 @@ pub mod builder { } } } - /**Builder for [`Client::send_solana_transaction_with_end_user_account`] + /**Builder for [`Client::lookup_end_user`] - [`Client::send_solana_transaction_with_end_user_account`]: super::Client::send_solana_transaction_with_end_user_account*/ + [`Client::lookup_end_user`]: super::Client::lookup_end_user*/ #[derive(Debug, Clone)] - pub struct SendSolanaTransactionWithEndUserAccount<'a> { + pub struct LookupEndUser<'a> { client: &'a super::Client, - user_id: Result, - project_id: Result, String>, - x_developer_auth: Result, String>, - x_idempotency_key: - Result, String>, - x_wallet_auth: Result, String>, - body: Result, + email: Result, String>, + oauth_provider: Result, String>, + oauth_subject: Result, String>, + phone_number: Result, String>, } - impl<'a> SendSolanaTransactionWithEndUserAccount<'a> { + impl<'a> LookupEndUser<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - user_id: Err("user_id was not initialized".to_string()), - project_id: Ok(None), - x_developer_auth: Ok(None), - x_idempotency_key: Ok(None), - x_wallet_auth: Ok(None), - body: Ok(::std::default::Default::default()), + email: Ok(None), + oauth_provider: Ok(None), + oauth_subject: Ok(None), + phone_number: Ok(None), } } - pub fn user_id(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.user_id = value.try_into().map_err(|_| { - "conversion to `SendSolanaTransactionWithEndUserAccountUserId` for user_id failed" - .to_string() - }); - self - } - pub fn project_id(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.project_id = value - .try_into() - .map(Some) - .map_err(|_| { - "conversion to `SendSolanaTransactionWithEndUserAccountProjectId` for project_id failed" - .to_string() - }); - self - } - pub fn x_developer_auth(mut self, value: V) -> Self + pub fn email(mut self, value: V) -> Self where V: std::convert::TryInto<::std::string::String>, { - self.x_developer_auth = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: string :: String` for x_developer_auth failed".to_string() + self.email = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for email failed".to_string() }); self } - pub fn x_idempotency_key(mut self, value: V) -> Self + pub fn oauth_provider(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.x_idempotency_key = value - .try_into() - .map(Some) - .map_err(|_| { - "conversion to `SendSolanaTransactionWithEndUserAccountXIdempotencyKey` for x_idempotency_key failed" - .to_string() - }); + self.oauth_provider = value.try_into().map(Some).map_err(|_| { + "conversion to `OAuth2ProviderType` for oauth_provider failed".to_string() + }); self } - pub fn x_wallet_auth(mut self, value: V) -> Self + pub fn oauth_subject(mut self, value: V) -> Self where V: std::convert::TryInto<::std::string::String>, { - self.x_wallet_auth = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() + self.oauth_subject = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for oauth_subject failed".to_string() }); self } - pub fn body(mut self, value: V) -> Self - where - V: std::convert::TryInto, - >::Error: - std::fmt::Display, - { - self.body = value - .try_into() - .map(From::from) - .map_err(|s| { - format!( - "conversion to `SendSolanaTransactionWithEndUserAccountBody` for body failed: {}", - s - ) - }); - self - } - pub fn body_map(mut self, f: F) -> Self + pub fn phone_number(mut self, value: V) -> Self where - F: std::ops::FnOnce( - types::builder::SendSolanaTransactionWithEndUserAccountBody, - ) - -> types::builder::SendSolanaTransactionWithEndUserAccountBody, + V: std::convert::TryInto, { - self.body = self.body.map(f); + self.phone_number = value.try_into().map(Some).map_err(|_| { + "conversion to `LookupEndUserPhoneNumber` for phone_number failed".to_string() + }); self } - ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/solana/send/transaction` + ///Sends a `GET` request to `/v2/end-users/lookup` pub async fn send( self, - ) -> Result< - ResponseValue, - Error, - > { + ) -> Result, Error> { let Self { client, - user_id, - project_id, - x_developer_auth, - x_idempotency_key, - x_wallet_auth, - body, + email, + oauth_provider, + oauth_subject, + phone_number, } = self; - let user_id = user_id.map_err(Error::InvalidRequest)?; - let project_id = project_id.map_err(Error::InvalidRequest)?; - let x_developer_auth = x_developer_auth.map_err(Error::InvalidRequest)?; - let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; - let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; - let body = body - .and_then(|v| { - types::SendSolanaTransactionWithEndUserAccountBody::try_from(v) - .map_err(|e| e.to_string()) - }) - .map_err(Error::InvalidRequest)?; - let url = format!( - "{}/v2/embedded-wallet-api/end-users/{}/solana/send/transaction", - client.baseurl, - encode_path(&user_id.to_string()), - ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(4usize); + let email = email.map_err(Error::InvalidRequest)?; + let oauth_provider = oauth_provider.map_err(Error::InvalidRequest)?; + let oauth_subject = oauth_subject.map_err(Error::InvalidRequest)?; + let phone_number = phone_number.map_err(Error::InvalidRequest)?; + let url = format!("{}/v2/end-users/lookup", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); - if let Some(value) = x_developer_auth { - header_map.append("X-Developer-Auth", value.to_string().try_into()?); - } - if let Some(value) = x_idempotency_key { - header_map.append("X-Idempotency-Key", value.to_string().try_into()?); - } - if let Some(value) = x_wallet_auth { - header_map.append("X-Wallet-Auth", value.to_string().try_into()?); - } #[allow(unused_mut)] let mut request = client .client - .post(url) + .get(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) - .json(&body) .query(&progenitor_middleware_client::QueryParam::new( - "projectID", - &project_id, + "email", &email, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "oauthProvider", + &oauth_provider, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "oauthSubject", + &oauth_subject, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "phoneNumber", + &phone_number, )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "send_solana_transaction_with_end_user_account", + operation_id: "lookup_end_user", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -88556,178 +102948,171 @@ pub mod builder { 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 402u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 403u16 => Err(Error::ErrorResponse( + 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + _ => Err(Error::UnexpectedResponse(response)), + } + } + } + /**Builder for [`Client::get_end_user`] + + [`Client::get_end_user`]: super::Client::get_end_user*/ + #[derive(Debug, Clone)] + pub struct GetEndUser<'a> { + client: &'a super::Client, + user_id: Result, + } + impl<'a> GetEndUser<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + user_id: Err("user_id was not initialized".to_string()), + } + } + pub fn user_id(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.user_id = value + .try_into() + .map_err(|_| "conversion to `GetEndUserUserId` for user_id failed".to_string()); + self + } + ///Sends a `GET` request to `/v2/end-users/{userId}` + pub async fn send(self) -> Result, Error> { + let Self { client, user_id } = self; + let user_id = user_id.map_err(Error::InvalidRequest)?; + let url = format!( + "{}/v2/end-users/{}", + client.baseurl, + encode_path(&user_id.to_string()), + ); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + #[allow(unused_mut)] + let mut request = client + .client + .get(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "get_end_user", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 200u16 => ResponseValue::from_response::(response).await, 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 422u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 502u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 503u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::sign_solana_message_with_end_user_account`] + /**Builder for [`Client::add_end_user_evm_account`] - [`Client::sign_solana_message_with_end_user_account`]: super::Client::sign_solana_message_with_end_user_account*/ + [`Client::add_end_user_evm_account`]: super::Client::add_end_user_evm_account*/ #[derive(Debug, Clone)] - pub struct SignSolanaMessageWithEndUserAccount<'a> { + pub struct AddEndUserEvmAccount<'a> { client: &'a super::Client, - user_id: Result, - project_id: Result, String>, - x_developer_auth: Result, String>, - x_idempotency_key: - Result, String>, - x_wallet_auth: Result, String>, - body: Result, + user_id: Result, + x_idempotency_key: Result, String>, + x_wallet_auth: Result<::std::string::String, String>, + body: Result<::serde_json::Map<::std::string::String, ::serde_json::Value>, String>, } - impl<'a> SignSolanaMessageWithEndUserAccount<'a> { + impl<'a> AddEndUserEvmAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, user_id: Err("user_id was not initialized".to_string()), - project_id: Ok(None), - x_developer_auth: Ok(None), x_idempotency_key: Ok(None), - x_wallet_auth: Ok(None), - body: Ok(::std::default::Default::default()), + x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), + body: Err("body was not initialized".to_string()), } } pub fn user_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.user_id = value.try_into().map_err(|_| { - "conversion to `SignSolanaMessageWithEndUserAccountUserId` for user_id failed" - .to_string() + "conversion to `AddEndUserEvmAccountUserId` for user_id failed".to_string() }); self } - pub fn project_id(mut self, value: V) -> Self + pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.project_id = value.try_into().map(Some).map_err(|_| { - "conversion to `SignSolanaMessageWithEndUserAccountProjectId` for project_id failed" + self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { + "conversion to `AddEndUserEvmAccountXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self } - pub fn x_developer_auth(mut self, value: V) -> Self + pub fn x_wallet_auth(mut self, value: V) -> Self where V: std::convert::TryInto<::std::string::String>, { - self.x_developer_auth = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: string :: String` for x_developer_auth failed".to_string() + self.x_wallet_auth = value.try_into().map_err(|_| { + "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() }); self } - pub fn x_idempotency_key(mut self, value: V) -> Self + pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto<::serde_json::Map<::std::string::String, ::serde_json::Value>>, { - self.x_idempotency_key = value + self.body = value .try_into() - .map(Some) .map_err(|_| { - "conversion to `SignSolanaMessageWithEndUserAccountXIdempotencyKey` for x_idempotency_key failed" + "conversion to `:: serde_json :: Map < :: std :: string :: String , :: serde_json :: Value >` for body failed" .to_string() }); self } - pub fn x_wallet_auth(mut self, value: V) -> Self - where - V: std::convert::TryInto<::std::string::String>, - { - self.x_wallet_auth = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() - }); - self - } - pub fn body(mut self, value: V) -> Self - where - V: std::convert::TryInto, - >::Error: - std::fmt::Display, - { - self.body = value.try_into().map(From::from).map_err(|s| { - format!( - "conversion to `SignSolanaMessageWithEndUserAccountBody` for body failed: {}", - s - ) - }); - self - } - pub fn body_map(mut self, f: F) -> Self - where - F: std::ops::FnOnce( - types::builder::SignSolanaMessageWithEndUserAccountBody, - ) - -> types::builder::SignSolanaMessageWithEndUserAccountBody, - { - self.body = self.body.map(f); - self - } - ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/solana/sign/message` + ///Sends a `POST` request to `/v2/end-users/{userId}/evm` pub async fn send( self, - ) -> Result< - ResponseValue, - Error, - > { + ) -> Result, Error> + { let Self { client, user_id, - project_id, - x_developer_auth, x_idempotency_key, x_wallet_auth, body, } = self; let user_id = user_id.map_err(Error::InvalidRequest)?; - let project_id = project_id.map_err(Error::InvalidRequest)?; - let x_developer_auth = x_developer_auth.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; - let body = body - .and_then(|v| { - types::SignSolanaMessageWithEndUserAccountBody::try_from(v) - .map_err(|e| e.to_string()) - }) - .map_err(Error::InvalidRequest)?; + let body = body.map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/embedded-wallet-api/end-users/{}/solana/sign/message", + "{}/v2/end-users/{}/evm", client.baseurl, encode_path(&user_id.to_string()), ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(4usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); - if let Some(value) = x_developer_auth { - header_map.append("X-Developer-Auth", value.to_string().try_into()?); - } if let Some(value) = x_idempotency_key { header_map.append("X-Idempotency-Key", value.to_string().try_into()?); } - if let Some(value) = x_wallet_auth { - header_map.append("X-Wallet-Auth", value.to_string().try_into()?); - } + header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client @@ -88737,21 +103122,17 @@ pub mod builder { ::reqwest::header::HeaderValue::from_static("application/json"), ) .json(&body) - .query(&progenitor_middleware_client::QueryParam::new( - "projectID", - &project_id, - )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "sign_solana_message_with_end_user_account", + operation_id: "add_end_user_evm_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 200u16 => ResponseValue::from_response::(response).await, + 201u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -88764,9 +103145,6 @@ pub mod builder { 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 409u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 422u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -88783,73 +103161,45 @@ pub mod builder { } } } - /**Builder for [`Client::sign_solana_transaction_with_end_user_account`] + /**Builder for [`Client::add_end_user_evm_smart_account`] - [`Client::sign_solana_transaction_with_end_user_account`]: super::Client::sign_solana_transaction_with_end_user_account*/ + [`Client::add_end_user_evm_smart_account`]: super::Client::add_end_user_evm_smart_account*/ #[derive(Debug, Clone)] - pub struct SignSolanaTransactionWithEndUserAccount<'a> { + pub struct AddEndUserEvmSmartAccount<'a> { client: &'a super::Client, - user_id: Result, - project_id: Result, String>, - x_developer_auth: Result, String>, - x_idempotency_key: - Result, String>, - x_wallet_auth: Result, String>, - body: Result, + user_id: Result, + x_idempotency_key: Result, String>, + x_wallet_auth: Result<::std::string::String, String>, + body: Result, } - impl<'a> SignSolanaTransactionWithEndUserAccount<'a> { + impl<'a> AddEndUserEvmSmartAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, user_id: Err("user_id was not initialized".to_string()), - project_id: Ok(None), - x_developer_auth: Ok(None), x_idempotency_key: Ok(None), - x_wallet_auth: Ok(None), + x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), body: Ok(::std::default::Default::default()), } } pub fn user_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.user_id = value.try_into().map_err(|_| { - "conversion to `SignSolanaTransactionWithEndUserAccountUserId` for user_id failed" - .to_string() - }); - self - } - pub fn project_id(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.project_id = value - .try_into() - .map(Some) - .map_err(|_| { - "conversion to `SignSolanaTransactionWithEndUserAccountProjectId` for project_id failed" - .to_string() - }); - self - } - pub fn x_developer_auth(mut self, value: V) -> Self - where - V: std::convert::TryInto<::std::string::String>, - { - self.x_developer_auth = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: string :: String` for x_developer_auth failed".to_string() + "conversion to `AddEndUserEvmSmartAccountUserId` for user_id failed".to_string() }); self } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value .try_into() .map(Some) .map_err(|_| { - "conversion to `SignSolanaTransactionWithEndUserAccountXIdempotencyKey` for x_idempotency_key failed" + "conversion to `AddEndUserEvmSmartAccountXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self @@ -88858,84 +103208,68 @@ pub mod builder { where V: std::convert::TryInto<::std::string::String>, { - self.x_wallet_auth = value.try_into().map(Some).map_err(|_| { + self.x_wallet_auth = value.try_into().map_err(|_| { "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() }); self } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: + V: std::convert::TryInto, + >::Error: std::fmt::Display, { - self.body = value - .try_into() - .map(From::from) - .map_err(|s| { - format!( - "conversion to `SignSolanaTransactionWithEndUserAccountBody` for body failed: {}", - s - ) - }); + self.body = value.try_into().map(From::from).map_err(|s| { + format!( + "conversion to `AddEndUserEvmSmartAccountBody` for body failed: {}", + s + ) + }); self } pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::SignSolanaTransactionWithEndUserAccountBody, - ) - -> types::builder::SignSolanaTransactionWithEndUserAccountBody, + types::builder::AddEndUserEvmSmartAccountBody, + ) -> types::builder::AddEndUserEvmSmartAccountBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/solana/sign/transaction` + ///Sends a `POST` request to `/v2/end-users/{userId}/evm-smart-account` pub async fn send( self, - ) -> Result< - ResponseValue, - Error, - > { + ) -> Result, Error> + { let Self { client, user_id, - project_id, - x_developer_auth, x_idempotency_key, x_wallet_auth, body, } = self; let user_id = user_id.map_err(Error::InvalidRequest)?; - let project_id = project_id.map_err(Error::InvalidRequest)?; - let x_developer_auth = x_developer_auth.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body .and_then(|v| { - types::SignSolanaTransactionWithEndUserAccountBody::try_from(v) - .map_err(|e| e.to_string()) + types::AddEndUserEvmSmartAccountBody::try_from(v).map_err(|e| e.to_string()) }) .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/embedded-wallet-api/end-users/{}/solana/sign/transaction", + "{}/v2/end-users/{}/evm-smart-account", client.baseurl, encode_path(&user_id.to_string()), ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(4usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); - if let Some(value) = x_developer_auth { - header_map.append("X-Developer-Auth", value.to_string().try_into()?); - } if let Some(value) = x_idempotency_key { header_map.append("X-Idempotency-Key", value.to_string().try_into()?); } - if let Some(value) = x_wallet_auth { - header_map.append("X-Wallet-Auth", value.to_string().try_into()?); - } + header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client @@ -88944,22 +103278,18 @@ pub mod builder { ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) - .json(&body) - .query(&progenitor_middleware_client::QueryParam::new( - "projectID", - &project_id, - )) + .json(&body) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "sign_solana_transaction_with_end_user_account", + operation_id: "add_end_user_evm_smart_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 200u16 => ResponseValue::from_response::(response).await, + 201u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -88969,15 +103299,9 @@ pub mod builder { 402u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 403u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 409u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 422u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -88994,92 +103318,45 @@ pub mod builder { } } } - /**Builder for [`Client::send_solana_asset_with_end_user_account`] + /**Builder for [`Client::add_end_user_solana_account`] - [`Client::send_solana_asset_with_end_user_account`]: super::Client::send_solana_asset_with_end_user_account*/ + [`Client::add_end_user_solana_account`]: super::Client::add_end_user_solana_account*/ #[derive(Debug, Clone)] - pub struct SendSolanaAssetWithEndUserAccount<'a> { + pub struct AddEndUserSolanaAccount<'a> { client: &'a super::Client, - user_id: Result, - address: Result, - asset: Result, - project_id: Result, String>, - x_developer_auth: Result, String>, - x_idempotency_key: - Result, String>, - x_wallet_auth: Result, String>, - body: Result, + user_id: Result, + x_idempotency_key: Result, String>, + x_wallet_auth: Result<::std::string::String, String>, + body: Result<::serde_json::Map<::std::string::String, ::serde_json::Value>, String>, } - impl<'a> SendSolanaAssetWithEndUserAccount<'a> { + impl<'a> AddEndUserSolanaAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, user_id: Err("user_id was not initialized".to_string()), - address: Err("address was not initialized".to_string()), - asset: Err("asset was not initialized".to_string()), - project_id: Ok(None), - x_developer_auth: Ok(None), x_idempotency_key: Ok(None), - x_wallet_auth: Ok(None), - body: Ok(::std::default::Default::default()), + x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), + body: Err("body was not initialized".to_string()), } } pub fn user_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.user_id = value.try_into().map_err(|_| { - "conversion to `SendSolanaAssetWithEndUserAccountUserId` for user_id failed" - .to_string() - }); - self - } - pub fn address(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.address = value - .try_into() - .map_err(|_| "conversion to `BlockchainAddress` for address failed".to_string()); - self - } - pub fn asset(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.asset = value - .try_into() - .map_err(|_| "conversion to `Asset` for asset failed".to_string()); - self - } - pub fn project_id(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.project_id = value.try_into().map(Some).map_err(|_| { - "conversion to `SendSolanaAssetWithEndUserAccountProjectId` for project_id failed" - .to_string() - }); - self - } - pub fn x_developer_auth(mut self, value: V) -> Self - where - V: std::convert::TryInto<::std::string::String>, - { - self.x_developer_auth = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: string :: String` for x_developer_auth failed".to_string() + "conversion to `AddEndUserSolanaAccountUserId` for user_id failed".to_string() }); self } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value .try_into() .map(Some) .map_err(|_| { - "conversion to `SendSolanaAssetWithEndUserAccountXIdempotencyKey` for x_idempotency_key failed" + "conversion to `AddEndUserSolanaAccountXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self @@ -89088,87 +103365,53 @@ pub mod builder { where V: std::convert::TryInto<::std::string::String>, { - self.x_wallet_auth = value.try_into().map(Some).map_err(|_| { + self.x_wallet_auth = value.try_into().map_err(|_| { "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() }); self } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: - std::fmt::Display, - { - self.body = value.try_into().map(From::from).map_err(|s| { - format!( - "conversion to `SendSolanaAssetWithEndUserAccountBody` for body failed: {}", - s - ) - }); - self - } - pub fn body_map(mut self, f: F) -> Self - where - F: std::ops::FnOnce( - types::builder::SendSolanaAssetWithEndUserAccountBody, - ) - -> types::builder::SendSolanaAssetWithEndUserAccountBody, + V: std::convert::TryInto<::serde_json::Map<::std::string::String, ::serde_json::Value>>, { - self.body = self.body.map(f); + self.body = value + .try_into() + .map_err(|_| { + "conversion to `:: serde_json :: Map < :: std :: string :: String , :: serde_json :: Value >` for body failed" + .to_string() + }); self } - ///Sends a `POST` request to `/v2/embedded-wallet-api/end-users/{userId}/solana/{address}/send/{asset}` + ///Sends a `POST` request to `/v2/end-users/{userId}/solana` pub async fn send( self, - ) -> Result< - ResponseValue, - Error, - > { + ) -> Result, Error> + { let Self { client, user_id, - address, - asset, - project_id, - x_developer_auth, x_idempotency_key, x_wallet_auth, body, } = self; let user_id = user_id.map_err(Error::InvalidRequest)?; - let address = address.map_err(Error::InvalidRequest)?; - let asset = asset.map_err(Error::InvalidRequest)?; - let project_id = project_id.map_err(Error::InvalidRequest)?; - let x_developer_auth = x_developer_auth.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; - let body = body - .and_then(|v| { - types::SendSolanaAssetWithEndUserAccountBody::try_from(v) - .map_err(|e| e.to_string()) - }) - .map_err(Error::InvalidRequest)?; + let body = body.map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/embedded-wallet-api/end-users/{}/solana/{}/send/{}", + "{}/v2/end-users/{}/solana", client.baseurl, encode_path(&user_id.to_string()), - encode_path(&address.to_string()), - encode_path(&asset.to_string()), ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(4usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); - if let Some(value) = x_developer_auth { - header_map.append("X-Developer-Auth", value.to_string().try_into()?); - } if let Some(value) = x_idempotency_key { header_map.append("X-Idempotency-Key", value.to_string().try_into()?); } - if let Some(value) = x_wallet_auth { - header_map.append("X-Wallet-Auth", value.to_string().try_into()?); - } + header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client @@ -89178,21 +103421,17 @@ pub mod builder { ::reqwest::header::HeaderValue::from_static("application/json"), ) .json(&body) - .query(&progenitor_middleware_client::QueryParam::new( - "projectID", - &project_id, - )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "send_solana_asset_with_end_user_account", + operation_id: "add_end_user_solana_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 200u16 => ResponseValue::from_response::(response).await, + 201u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -89221,32 +103460,31 @@ pub mod builder { } } } - /**Builder for [`Client::list_end_users`] + /**Builder for [`Client::list_evm_accounts`] - [`Client::list_end_users`]: super::Client::list_end_users*/ + [`Client::list_evm_accounts`]: super::Client::list_evm_accounts*/ #[derive(Debug, Clone)] - pub struct ListEndUsers<'a> { + pub struct ListEvmAccounts<'a> { client: &'a super::Client, - page_size: Result, String>, + page_size: Result, String>, page_token: Result, String>, - sort: Result>, String>, } - impl<'a> ListEndUsers<'a> { + impl<'a> ListEvmAccounts<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, page_size: Ok(None), page_token: Ok(None), - sort: Ok(None), } } pub fn page_size(mut self, value: V) -> Self where - V: std::convert::TryInto<::std::num::NonZeroU64>, + V: std::convert::TryInto, { - self.page_size = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: num :: NonZeroU64` for page_size failed".to_string() - }); + self.page_size = value + .try_into() + .map(Some) + .map_err(|_| "conversion to `i64` for page_size failed".to_string()); self } pub fn page_token(mut self, value: V) -> Self @@ -89258,30 +103496,18 @@ pub mod builder { }); self } - pub fn sort(mut self, value: V) -> Self - where - V: std::convert::TryInto<::std::vec::Vec>, - { - self.sort = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: vec :: Vec < ListEndUsersSortItem >` for sort failed" - .to_string() - }); - self - } - ///Sends a `GET` request to `/v2/end-users` + ///Sends a `GET` request to `/v2/evm/accounts` pub async fn send( self, - ) -> Result, Error> { + ) -> Result, Error> { let Self { client, page_size, page_token, - sort, } = self; let page_size = page_size.map_err(Error::InvalidRequest)?; let page_token = page_token.map_err(Error::InvalidRequest)?; - let sort = sort.map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/end-users", client.baseurl,); + let url = format!("{}/v2/evm/accounts", client.baseurl,); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), @@ -89302,13 +103528,10 @@ pub mod builder { "pageToken", &page_token, )) - .query(&progenitor_middleware_client::QueryParam::new( - "sort", &sort, - )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "list_end_users", + operation_id: "list_evm_accounts", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -89316,12 +103539,6 @@ pub mod builder { let response = result?; match response.status().as_u16() { 200u16 => ResponseValue::from_response::(response).await, - 400u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 401u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -89335,17 +103552,17 @@ pub mod builder { } } } - /**Builder for [`Client::create_end_user`] + /**Builder for [`Client::create_evm_account`] - [`Client::create_end_user`]: super::Client::create_end_user*/ + [`Client::create_evm_account`]: super::Client::create_evm_account*/ #[derive(Debug, Clone)] - pub struct CreateEndUser<'a> { + pub struct CreateEvmAccount<'a> { client: &'a super::Client, - x_idempotency_key: Result, String>, + x_idempotency_key: Result, String>, x_wallet_auth: Result<::std::string::String, String>, - body: Result, + body: Result, } - impl<'a> CreateEndUser<'a> { + impl<'a> CreateEvmAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, @@ -89356,10 +103573,10 @@ pub mod builder { } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `CreateEndUserXIdempotencyKey` for x_idempotency_key failed" + "conversion to `CreateEvmAccountXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self @@ -89375,26 +103592,28 @@ pub mod builder { } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto, + >::Error: std::fmt::Display, { - self.body = value - .try_into() - .map(From::from) - .map_err(|s| format!("conversion to `CreateEndUserBody` for body failed: {}", s)); + self.body = value.try_into().map(From::from).map_err(|s| { + format!( + "conversion to `CreateEvmAccountBody` for body failed: {}", + s + ) + }); self } pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::CreateEndUserBody, - ) -> types::builder::CreateEndUserBody, + types::builder::CreateEvmAccountBody, + ) -> types::builder::CreateEvmAccountBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/end-users` - pub async fn send(self) -> Result, Error> { + ///Sends a `POST` request to `/v2/evm/accounts` + pub async fn send(self) -> Result, Error> { let Self { client, x_idempotency_key, @@ -89404,9 +103623,9 @@ pub mod builder { let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body - .and_then(|v| types::CreateEndUserBody::try_from(v).map_err(|e| e.to_string())) + .and_then(|v| types::CreateEvmAccountBody::try_from(v).map_err(|e| e.to_string())) .map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/end-users", client.baseurl,); + let url = format!("{}/v2/evm/accounts", client.baseurl,); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), @@ -89428,7 +103647,7 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "create_end_user", + operation_id: "create_evm_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -89445,63 +103664,58 @@ pub mod builder { 402u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 409u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 422u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 502u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 503u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::validate_end_user_access_token`] + /**Builder for [`Client::get_evm_account_by_name`] - [`Client::validate_end_user_access_token`]: super::Client::validate_end_user_access_token*/ + [`Client::get_evm_account_by_name`]: super::Client::get_evm_account_by_name*/ #[derive(Debug, Clone)] - pub struct ValidateEndUserAccessToken<'a> { + pub struct GetEvmAccountByName<'a> { client: &'a super::Client, - body: Result, + name: Result<::std::string::String, String>, } - impl<'a> ValidateEndUserAccessToken<'a> { + impl<'a> GetEvmAccountByName<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - body: Ok(::std::default::Default::default()), + name: Err("name was not initialized".to_string()), } } - pub fn body(mut self, value: V) -> Self + pub fn name(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: - std::fmt::Display, + V: std::convert::TryInto<::std::string::String>, { - self.body = value.try_into().map(From::from).map_err(|s| { - format!( - "conversion to `ValidateEndUserAccessTokenBody` for body failed: {}", - s - ) + self.name = value.try_into().map_err(|_| { + "conversion to `:: std :: string :: String` for name failed".to_string() }); self } - pub fn body_map(mut self, f: F) -> Self - where - F: std::ops::FnOnce( - types::builder::ValidateEndUserAccessTokenBody, - ) -> types::builder::ValidateEndUserAccessTokenBody, - { - self.body = self.body.map(f); - self - } - ///Sends a `POST` request to `/v2/end-users/auth/validate-token` - pub async fn send(self) -> Result, Error> { - let Self { client, body } = self; - let body = body - .and_then(|v| { - types::ValidateEndUserAccessTokenBody::try_from(v).map_err(|e| e.to_string()) - }) - .map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/end-users/auth/validate-token", client.baseurl,); + ///Sends a `GET` request to `/v2/evm/accounts/by-name/{name}` + pub async fn send(self) -> Result, Error> { + let Self { client, name } = self; + let name = name.map_err(Error::InvalidRequest)?; + let url = format!( + "{}/v2/evm/accounts/by-name/{}", + client.baseurl, + encode_path(&name.to_string()), + ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), @@ -89510,16 +103724,15 @@ pub mod builder { #[allow(unused_mut)] let mut request = client .client - .post(url) + .get(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) - .json(&body) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "validate_end_user_access_token", + operation_id: "get_evm_account_by_name", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -89530,44 +103743,58 @@ pub mod builder { 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 401u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 502u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 503u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::import_end_user`] + /**Builder for [`Client::export_evm_account_by_name`] - [`Client::import_end_user`]: super::Client::import_end_user*/ + [`Client::export_evm_account_by_name`]: super::Client::export_evm_account_by_name*/ #[derive(Debug, Clone)] - pub struct ImportEndUser<'a> { + pub struct ExportEvmAccountByName<'a> { client: &'a super::Client, - x_idempotency_key: Result, String>, + name: Result<::std::string::String, String>, + x_idempotency_key: Result, String>, x_wallet_auth: Result<::std::string::String, String>, - body: Result, + body: Result, } - impl<'a> ImportEndUser<'a> { + impl<'a> ExportEvmAccountByName<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, + name: Err("name was not initialized".to_string()), x_idempotency_key: Ok(None), x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), body: Ok(::std::default::Default::default()), } } + pub fn name(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.name = value.try_into().map_err(|_| { + "conversion to `:: std :: string :: String` for name failed".to_string() + }); + self + } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `ImportEndUserXIdempotencyKey` for x_idempotency_key failed" + "conversion to `ExportEvmAccountByNameXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self @@ -89583,38 +103810,52 @@ pub mod builder { } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto, + >::Error: + std::fmt::Display, { - self.body = value - .try_into() - .map(From::from) - .map_err(|s| format!("conversion to `ImportEndUserBody` for body failed: {}", s)); + self.body = value.try_into().map(From::from).map_err(|s| { + format!( + "conversion to `ExportEvmAccountByNameBody` for body failed: {}", + s + ) + }); self } pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::ImportEndUserBody, - ) -> types::builder::ImportEndUserBody, + types::builder::ExportEvmAccountByNameBody, + ) -> types::builder::ExportEvmAccountByNameBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/end-users/import` - pub async fn send(self) -> Result, Error> { + ///Sends a `POST` request to `/v2/evm/accounts/export/by-name/{name}` + pub async fn send( + self, + ) -> Result, Error> + { let Self { client, + name, x_idempotency_key, x_wallet_auth, body, } = self; + let name = name.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body - .and_then(|v| types::ImportEndUserBody::try_from(v).map_err(|e| e.to_string())) + .and_then(|v| { + types::ExportEvmAccountByNameBody::try_from(v).map_err(|e| e.to_string()) + }) .map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/end-users/import", client.baseurl,); + let url = format!( + "{}/v2/evm/accounts/export/by-name/{}", + client.baseurl, + encode_path(&name.to_string()), + ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), @@ -89636,14 +103877,14 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "import_end_user", + operation_id: "export_evm_account_by_name", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 201u16 => ResponseValue::from_response::(response).await, + 200u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -89653,7 +103894,7 @@ pub mod builder { 402u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 409u16 => Err(Error::ErrorResponse( + 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 422u16 => Err(Error::ErrorResponse( @@ -89672,163 +103913,169 @@ pub mod builder { } } } - /**Builder for [`Client::lookup_end_user`] + /**Builder for [`Client::import_evm_account`] - [`Client::lookup_end_user`]: super::Client::lookup_end_user*/ + [`Client::import_evm_account`]: super::Client::import_evm_account*/ #[derive(Debug, Clone)] - pub struct LookupEndUser<'a> { + pub struct ImportEvmAccount<'a> { client: &'a super::Client, - email: Result, String>, - oauth_provider: Result, String>, - oauth_subject: Result, String>, - phone_number: Result, String>, + x_idempotency_key: Result, String>, + x_wallet_auth: Result<::std::string::String, String>, + body: Result, } - impl<'a> LookupEndUser<'a> { + impl<'a> ImportEvmAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - email: Ok(None), - oauth_provider: Ok(None), - oauth_subject: Ok(None), - phone_number: Ok(None), + x_idempotency_key: Ok(None), + x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), + body: Ok(::std::default::Default::default()), } } - pub fn email(mut self, value: V) -> Self + pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto<::std::string::String>, + V: std::convert::TryInto, { - self.email = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: string :: String` for email failed".to_string() + self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { + "conversion to `ImportEvmAccountXIdempotencyKey` for x_idempotency_key failed" + .to_string() }); self } - pub fn oauth_provider(mut self, value: V) -> Self + pub fn x_wallet_auth(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto<::std::string::String>, { - self.oauth_provider = value.try_into().map(Some).map_err(|_| { - "conversion to `OAuth2ProviderType` for oauth_provider failed".to_string() + self.x_wallet_auth = value.try_into().map_err(|_| { + "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() }); self } - pub fn oauth_subject(mut self, value: V) -> Self + pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto<::std::string::String>, + V: std::convert::TryInto, + >::Error: std::fmt::Display, { - self.oauth_subject = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: string :: String` for oauth_subject failed".to_string() + self.body = value.try_into().map(From::from).map_err(|s| { + format!( + "conversion to `ImportEvmAccountBody` for body failed: {}", + s + ) }); self } - pub fn phone_number(mut self, value: V) -> Self + pub fn body_map(mut self, f: F) -> Self where - V: std::convert::TryInto, + F: std::ops::FnOnce( + types::builder::ImportEvmAccountBody, + ) -> types::builder::ImportEvmAccountBody, { - self.phone_number = value.try_into().map(Some).map_err(|_| { - "conversion to `LookupEndUserPhoneNumber` for phone_number failed".to_string() - }); + self.body = self.body.map(f); self } - ///Sends a `GET` request to `/v2/end-users/lookup` - pub async fn send( - self, - ) -> Result, Error> { + ///Sends a `POST` request to `/v2/evm/accounts/import` + pub async fn send(self) -> Result, Error> { let Self { client, - email, - oauth_provider, - oauth_subject, - phone_number, + x_idempotency_key, + x_wallet_auth, + body, } = self; - let email = email.map_err(Error::InvalidRequest)?; - let oauth_provider = oauth_provider.map_err(Error::InvalidRequest)?; - let oauth_subject = oauth_subject.map_err(Error::InvalidRequest)?; - let phone_number = phone_number.map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/end-users/lookup", client.baseurl,); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; + let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; + let body = body + .and_then(|v| types::ImportEvmAccountBody::try_from(v).map_err(|e| e.to_string())) + .map_err(Error::InvalidRequest)?; + let url = format!("{}/v2/evm/accounts/import", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); - #[allow(unused_mut)] - let mut request = client - .client - .get(url) - .header( - ::reqwest::header::ACCEPT, - ::reqwest::header::HeaderValue::from_static("application/json"), - ) - .query(&progenitor_middleware_client::QueryParam::new( - "email", &email, - )) - .query(&progenitor_middleware_client::QueryParam::new( - "oauthProvider", - &oauth_provider, - )) - .query(&progenitor_middleware_client::QueryParam::new( - "oauthSubject", - &oauth_subject, - )) - .query(&progenitor_middleware_client::QueryParam::new( - "phoneNumber", - &phone_number, - )) + if let Some(value) = x_idempotency_key { + header_map.append("X-Idempotency-Key", value.to_string().try_into()?); + } + header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); + #[allow(unused_mut)] + let mut request = client + .client + .post(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .json(&body) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "lookup_end_user", + operation_id: "import_evm_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 200u16 => ResponseValue::from_response::(response).await, + 201u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 402u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 409u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 422u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 502u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 503u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::get_end_user`] + /**Builder for [`Client::get_evm_account`] - [`Client::get_end_user`]: super::Client::get_end_user*/ + [`Client::get_evm_account`]: super::Client::get_evm_account*/ #[derive(Debug, Clone)] - pub struct GetEndUser<'a> { + pub struct GetEvmAccount<'a> { client: &'a super::Client, - user_id: Result, + address: Result, } - impl<'a> GetEndUser<'a> { + impl<'a> GetEvmAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - user_id: Err("user_id was not initialized".to_string()), + address: Err("address was not initialized".to_string()), } } - pub fn user_id(mut self, value: V) -> Self + pub fn address(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.user_id = value + self.address = value .try_into() - .map_err(|_| "conversion to `GetEndUserUserId` for user_id failed".to_string()); + .map_err(|_| "conversion to `GetEvmAccountAddress` for address failed".to_string()); self } - ///Sends a `GET` request to `/v2/end-users/{userId}` - pub async fn send(self) -> Result, Error> { - let Self { client, user_id } = self; - let user_id = user_id.map_err(Error::InvalidRequest)?; + ///Sends a `GET` request to `/v2/evm/accounts/{address}` + pub async fn send(self) -> Result, Error> { + let Self { client, address } = self; + let address = address.map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/end-users/{}", + "{}/v2/evm/accounts/{}", client.baseurl, - encode_path(&user_id.to_string()), + encode_path(&address.to_string()), ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( @@ -89846,7 +104093,7 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "get_end_user", + operation_id: "get_evm_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -89854,99 +104101,104 @@ pub mod builder { let response = result?; match response.status().as_u16() { 200u16 => ResponseValue::from_response::(response).await, + 400u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 502u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 503u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::add_end_user_evm_account`] + /**Builder for [`Client::update_evm_account`] - [`Client::add_end_user_evm_account`]: super::Client::add_end_user_evm_account*/ + [`Client::update_evm_account`]: super::Client::update_evm_account*/ #[derive(Debug, Clone)] - pub struct AddEndUserEvmAccount<'a> { + pub struct UpdateEvmAccount<'a> { client: &'a super::Client, - user_id: Result, - x_idempotency_key: Result, String>, - x_wallet_auth: Result<::std::string::String, String>, - body: Result<::serde_json::Map<::std::string::String, ::serde_json::Value>, String>, + address: Result, + x_idempotency_key: Result, String>, + body: Result, } - impl<'a> AddEndUserEvmAccount<'a> { + impl<'a> UpdateEvmAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - user_id: Err("user_id was not initialized".to_string()), + address: Err("address was not initialized".to_string()), x_idempotency_key: Ok(None), - x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), - body: Err("body was not initialized".to_string()), + body: Ok(::std::default::Default::default()), } } - pub fn user_id(mut self, value: V) -> Self + pub fn address(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.user_id = value.try_into().map_err(|_| { - "conversion to `AddEndUserEvmAccountUserId` for user_id failed".to_string() + self.address = value.try_into().map_err(|_| { + "conversion to `UpdateEvmAccountAddress` for address failed".to_string() }); self } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `AddEndUserEvmAccountXIdempotencyKey` for x_idempotency_key failed" + "conversion to `UpdateEvmAccountXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self } - pub fn x_wallet_auth(mut self, value: V) -> Self + pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto<::std::string::String>, + V: std::convert::TryInto, + >::Error: std::fmt::Display, { - self.x_wallet_auth = value.try_into().map_err(|_| { - "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() + self.body = value.try_into().map(From::from).map_err(|s| { + format!( + "conversion to `UpdateEvmAccountBody` for body failed: {}", + s + ) }); self } - pub fn body(mut self, value: V) -> Self + pub fn body_map(mut self, f: F) -> Self where - V: std::convert::TryInto<::serde_json::Map<::std::string::String, ::serde_json::Value>>, + F: std::ops::FnOnce( + types::builder::UpdateEvmAccountBody, + ) -> types::builder::UpdateEvmAccountBody, { - self.body = value - .try_into() - .map_err(|_| { - "conversion to `:: serde_json :: Map < :: std :: string :: String , :: serde_json :: Value >` for body failed" - .to_string() - }); + self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/end-users/{userId}/evm` - pub async fn send( - self, - ) -> Result, Error> - { + ///Sends a `PUT` request to `/v2/evm/accounts/{address}` + pub async fn send(self) -> Result, Error> { let Self { client, - user_id, + address, x_idempotency_key, - x_wallet_auth, body, } = self; - let user_id = user_id.map_err(Error::InvalidRequest)?; + let address = address.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; - let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; - let body = body.map_err(Error::InvalidRequest)?; + let body = body + .and_then(|v| types::UpdateEvmAccountBody::try_from(v).map_err(|e| e.to_string())) + .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/end-users/{}/evm", + "{}/v2/evm/accounts/{}", client.baseurl, - encode_path(&user_id.to_string()), + encode_path(&address.to_string()), ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(2usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), @@ -89954,11 +104206,10 @@ pub mod builder { if let Some(value) = x_idempotency_key { header_map.append("X-Idempotency-Key", value.to_string().try_into()?); } - header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client - .post(url) + .put(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), @@ -89967,24 +104218,21 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "add_end_user_evm_account", + operation_id: "update_evm_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 201u16 => ResponseValue::from_response::(response).await, + 200u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 401u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 402u16 => Err(Error::ErrorResponse( + 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 404u16 => Err(Error::ErrorResponse( + 409u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 422u16 => Err(Error::ErrorResponse( @@ -90003,45 +104251,45 @@ pub mod builder { } } } - /**Builder for [`Client::add_end_user_evm_smart_account`] + /**Builder for [`Client::create_evm_eip7702_delegation`] - [`Client::add_end_user_evm_smart_account`]: super::Client::add_end_user_evm_smart_account*/ + [`Client::create_evm_eip7702_delegation`]: super::Client::create_evm_eip7702_delegation*/ #[derive(Debug, Clone)] - pub struct AddEndUserEvmSmartAccount<'a> { + pub struct CreateEvmEip7702Delegation<'a> { client: &'a super::Client, - user_id: Result, - x_idempotency_key: Result, String>, + address: Result, + x_idempotency_key: Result, String>, x_wallet_auth: Result<::std::string::String, String>, - body: Result, + body: Result, } - impl<'a> AddEndUserEvmSmartAccount<'a> { + impl<'a> CreateEvmEip7702Delegation<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - user_id: Err("user_id was not initialized".to_string()), + address: Err("address was not initialized".to_string()), x_idempotency_key: Ok(None), x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), body: Ok(::std::default::Default::default()), } } - pub fn user_id(mut self, value: V) -> Self + pub fn address(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.user_id = value.try_into().map_err(|_| { - "conversion to `AddEndUserEvmSmartAccountUserId` for user_id failed".to_string() + self.address = value.try_into().map_err(|_| { + "conversion to `CreateEvmEip7702DelegationAddress` for address failed".to_string() }); self } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value .try_into() .map(Some) .map_err(|_| { - "conversion to `AddEndUserEvmSmartAccountXIdempotencyKey` for x_idempotency_key failed" + "conversion to `CreateEvmEip7702DelegationXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self @@ -90057,13 +104305,13 @@ pub mod builder { } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: + V: std::convert::TryInto, + >::Error: std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `AddEndUserEvmSmartAccountBody` for body failed: {}", + "conversion to `CreateEvmEip7702DelegationBody` for body failed: {}", s ) }); @@ -90072,36 +104320,36 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::AddEndUserEvmSmartAccountBody, - ) -> types::builder::AddEndUserEvmSmartAccountBody, + types::builder::CreateEvmEip7702DelegationBody, + ) -> types::builder::CreateEvmEip7702DelegationBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/end-users/{userId}/evm-smart-account` + ///Sends a `POST` request to `/v2/evm/accounts/{address}/eip7702/delegation` pub async fn send( self, - ) -> Result, Error> + ) -> Result, Error> { let Self { client, - user_id, + address, x_idempotency_key, x_wallet_auth, body, } = self; - let user_id = user_id.map_err(Error::InvalidRequest)?; + let address = address.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body .and_then(|v| { - types::AddEndUserEvmSmartAccountBody::try_from(v).map_err(|e| e.to_string()) + types::CreateEvmEip7702DelegationBody::try_from(v).map_err(|e| e.to_string()) }) .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/end-users/{}/evm-smart-account", + "{}/v2/evm/accounts/{}/eip7702/delegation", client.baseurl, - encode_path(&user_id.to_string()), + encode_path(&address.to_string()), ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( @@ -90124,7 +104372,7 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "add_end_user_evm_smart_account", + operation_id: "create_evm_eip7702_delegation", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -90144,6 +104392,9 @@ pub mod builder { 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 409u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 422u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -90160,47 +104411,44 @@ pub mod builder { } } } - /**Builder for [`Client::add_end_user_solana_account`] + /**Builder for [`Client::export_evm_account`] - [`Client::add_end_user_solana_account`]: super::Client::add_end_user_solana_account*/ + [`Client::export_evm_account`]: super::Client::export_evm_account*/ #[derive(Debug, Clone)] - pub struct AddEndUserSolanaAccount<'a> { + pub struct ExportEvmAccount<'a> { client: &'a super::Client, - user_id: Result, - x_idempotency_key: Result, String>, + address: Result, + x_idempotency_key: Result, String>, x_wallet_auth: Result<::std::string::String, String>, - body: Result<::serde_json::Map<::std::string::String, ::serde_json::Value>, String>, + body: Result, } - impl<'a> AddEndUserSolanaAccount<'a> { + impl<'a> ExportEvmAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - user_id: Err("user_id was not initialized".to_string()), + address: Err("address was not initialized".to_string()), x_idempotency_key: Ok(None), x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), - body: Err("body was not initialized".to_string()), + body: Ok(::std::default::Default::default()), } } - pub fn user_id(mut self, value: V) -> Self + pub fn address(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.user_id = value.try_into().map_err(|_| { - "conversion to `AddEndUserSolanaAccountUserId` for user_id failed".to_string() + self.address = value.try_into().map_err(|_| { + "conversion to `ExportEvmAccountAddress` for address failed".to_string() }); self } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.x_idempotency_key = value - .try_into() - .map(Some) - .map_err(|_| { - "conversion to `AddEndUserSolanaAccountXIdempotencyKey` for x_idempotency_key failed" - .to_string() - }); + self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { + "conversion to `ExportEvmAccountXIdempotencyKey` for x_idempotency_key failed" + .to_string() + }); self } pub fn x_wallet_auth(mut self, value: V) -> Self @@ -90214,36 +104462,47 @@ pub mod builder { } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto<::serde_json::Map<::std::string::String, ::serde_json::Value>>, + V: std::convert::TryInto, + >::Error: std::fmt::Display, { - self.body = value - .try_into() - .map_err(|_| { - "conversion to `:: serde_json :: Map < :: std :: string :: String , :: serde_json :: Value >` for body failed" - .to_string() - }); + self.body = value.try_into().map(From::from).map_err(|s| { + format!( + "conversion to `ExportEvmAccountBody` for body failed: {}", + s + ) + }); self } - ///Sends a `POST` request to `/v2/end-users/{userId}/solana` + pub fn body_map(mut self, f: F) -> Self + where + F: std::ops::FnOnce( + types::builder::ExportEvmAccountBody, + ) -> types::builder::ExportEvmAccountBody, + { + self.body = self.body.map(f); + self + } + ///Sends a `POST` request to `/v2/evm/accounts/{address}/export` pub async fn send( self, - ) -> Result, Error> - { + ) -> Result, Error> { let Self { client, - user_id, + address, x_idempotency_key, x_wallet_auth, body, } = self; - let user_id = user_id.map_err(Error::InvalidRequest)?; + let address = address.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; - let body = body.map_err(Error::InvalidRequest)?; + let body = body + .and_then(|v| types::ExportEvmAccountBody::try_from(v).map_err(|e| e.to_string())) + .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/end-users/{}/solana", + "{}/v2/evm/accounts/{}/export", client.baseurl, - encode_path(&user_id.to_string()), + encode_path(&address.to_string()), ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( @@ -90266,14 +104525,14 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "add_end_user_solana_account", + operation_id: "export_evm_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 201u16 => ResponseValue::from_response::(response).await, + 200u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -90302,123 +104561,42 @@ pub mod builder { } } } - /**Builder for [`Client::list_evm_accounts`] + /**Builder for [`Client::send_evm_transaction`] - [`Client::list_evm_accounts`]: super::Client::list_evm_accounts*/ + [`Client::send_evm_transaction`]: super::Client::send_evm_transaction*/ #[derive(Debug, Clone)] - pub struct ListEvmAccounts<'a> { + pub struct SendEvmTransaction<'a> { client: &'a super::Client, - page_size: Result, String>, - page_token: Result, String>, + address: Result, + x_idempotency_key: Result, String>, + x_wallet_auth: Result<::std::string::String, String>, + body: Result, } - impl<'a> ListEvmAccounts<'a> { + impl<'a> SendEvmTransaction<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - page_size: Ok(None), - page_token: Ok(None), + address: Err("address was not initialized".to_string()), + x_idempotency_key: Ok(None), + x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), + body: Ok(::std::default::Default::default()), } } - pub fn page_size(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.page_size = value - .try_into() - .map(Some) - .map_err(|_| "conversion to `i64` for page_size failed".to_string()); - self - } - pub fn page_token(mut self, value: V) -> Self + pub fn address(mut self, value: V) -> Self where - V: std::convert::TryInto<::std::string::String>, + V: std::convert::TryInto, { - self.page_token = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: string :: String` for page_token failed".to_string() + self.address = value.try_into().map_err(|_| { + "conversion to `SendEvmTransactionAddress` for address failed".to_string() }); self } - ///Sends a `GET` request to `/v2/evm/accounts` - pub async fn send( - self, - ) -> Result, Error> { - let Self { - client, - page_size, - page_token, - } = self; - let page_size = page_size.map_err(Error::InvalidRequest)?; - let page_token = page_token.map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/evm/accounts", client.baseurl,); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); - header_map.append( - ::reqwest::header::HeaderName::from_static("api-version"), - ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), - ); - #[allow(unused_mut)] - let mut request = client - .client - .get(url) - .header( - ::reqwest::header::ACCEPT, - ::reqwest::header::HeaderValue::from_static("application/json"), - ) - .query(&progenitor_middleware_client::QueryParam::new( - "pageSize", &page_size, - )) - .query(&progenitor_middleware_client::QueryParam::new( - "pageToken", - &page_token, - )) - .headers(header_map) - .build()?; - let info = OperationInfo { - operation_id: "list_evm_accounts", - }; - client.pre(&mut request, &info).await?; - let result = client.exec(request, &info).await; - client.post(&result, &info).await?; - let response = result?; - match response.status().as_u16() { - 200u16 => ResponseValue::from_response::(response).await, - 500u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 502u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 503u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - _ => Err(Error::UnexpectedResponse(response)), - } - } - } - /**Builder for [`Client::create_evm_account`] - - [`Client::create_evm_account`]: super::Client::create_evm_account*/ - #[derive(Debug, Clone)] - pub struct CreateEvmAccount<'a> { - client: &'a super::Client, - x_idempotency_key: Result, String>, - x_wallet_auth: Result<::std::string::String, String>, - body: Result, - } - impl<'a> CreateEvmAccount<'a> { - pub fn new(client: &'a super::Client) -> Self { - Self { - client: client, - x_idempotency_key: Ok(None), - x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), - body: Ok(::std::default::Default::default()), - } - } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `CreateEvmAccountXIdempotencyKey` for x_idempotency_key failed" + "conversion to `SendEvmTransactionXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self @@ -90434,12 +104612,12 @@ pub mod builder { } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto, + >::Error: std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `CreateEvmAccountBody` for body failed: {}", + "conversion to `SendEvmTransactionBody` for body failed: {}", s ) }); @@ -90448,26 +104626,34 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::CreateEvmAccountBody, - ) -> types::builder::CreateEvmAccountBody, + types::builder::SendEvmTransactionBody, + ) -> types::builder::SendEvmTransactionBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/evm/accounts` - pub async fn send(self) -> Result, Error> { + ///Sends a `POST` request to `/v2/evm/accounts/{address}/send/transaction` + pub async fn send( + self, + ) -> Result, Error> { let Self { client, + address, x_idempotency_key, x_wallet_auth, body, } = self; + let address = address.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body - .and_then(|v| types::CreateEvmAccountBody::try_from(v).map_err(|e| e.to_string())) + .and_then(|v| types::SendEvmTransactionBody::try_from(v).map_err(|e| e.to_string())) .map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/evm/accounts", client.baseurl,); + let url = format!( + "{}/v2/evm/accounts/{}/send/transaction", + client.baseurl, + encode_path(&address.to_string()), + ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), @@ -90489,14 +104675,14 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "create_evm_account", + operation_id: "send_evm_transaction", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 201u16 => ResponseValue::from_response::(response).await, + 200u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -90506,6 +104692,12 @@ pub mod builder { 402u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 403u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 404u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 409u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -90525,56 +104717,117 @@ pub mod builder { } } } - /**Builder for [`Client::get_evm_account_by_name`] + /**Builder for [`Client::sign_evm_hash`] - [`Client::get_evm_account_by_name`]: super::Client::get_evm_account_by_name*/ + [`Client::sign_evm_hash`]: super::Client::sign_evm_hash*/ #[derive(Debug, Clone)] - pub struct GetEvmAccountByName<'a> { + pub struct SignEvmHash<'a> { client: &'a super::Client, - name: Result<::std::string::String, String>, + address: Result, + x_idempotency_key: Result, String>, + x_wallet_auth: Result<::std::string::String, String>, + body: Result, } - impl<'a> GetEvmAccountByName<'a> { + impl<'a> SignEvmHash<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - name: Err("name was not initialized".to_string()), + address: Err("address was not initialized".to_string()), + x_idempotency_key: Ok(None), + x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), + body: Ok(::std::default::Default::default()), } } - pub fn name(mut self, value: V) -> Self + pub fn address(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.address = value + .try_into() + .map_err(|_| "conversion to `SignEvmHashAddress` for address failed".to_string()); + self + } + pub fn x_idempotency_key(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { + "conversion to `SignEvmHashXIdempotencyKey` for x_idempotency_key failed" + .to_string() + }); + self + } + pub fn x_wallet_auth(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.x_wallet_auth = value.try_into().map_err(|_| { + "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() + }); + self + } + pub fn body(mut self, value: V) -> Self + where + V: std::convert::TryInto, + >::Error: std::fmt::Display, + { + self.body = value + .try_into() + .map(From::from) + .map_err(|s| format!("conversion to `SignEvmHashBody` for body failed: {}", s)); + self + } + pub fn body_map(mut self, f: F) -> Self where - V: std::convert::TryInto<::std::string::String>, + F: std::ops::FnOnce(types::builder::SignEvmHashBody) -> types::builder::SignEvmHashBody, { - self.name = value.try_into().map_err(|_| { - "conversion to `:: std :: string :: String` for name failed".to_string() - }); + self.body = self.body.map(f); self } - ///Sends a `GET` request to `/v2/evm/accounts/by-name/{name}` - pub async fn send(self) -> Result, Error> { - let Self { client, name } = self; - let name = name.map_err(Error::InvalidRequest)?; + ///Sends a `POST` request to `/v2/evm/accounts/{address}/sign` + pub async fn send( + self, + ) -> Result, Error> { + let Self { + client, + address, + x_idempotency_key, + x_wallet_auth, + body, + } = self; + let address = address.map_err(Error::InvalidRequest)?; + let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; + let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; + let body = body + .and_then(|v| types::SignEvmHashBody::try_from(v).map_err(|e| e.to_string())) + .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/evm/accounts/by-name/{}", + "{}/v2/evm/accounts/{}/sign", client.baseurl, - encode_path(&name.to_string()), + encode_path(&address.to_string()), ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); + if let Some(value) = x_idempotency_key { + header_map.append("X-Idempotency-Key", value.to_string().try_into()?); + } + header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client - .get(url) + .post(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) + .json(&body) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "get_evm_account_by_name", + operation_id: "sign_evm_hash", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -90585,9 +104838,18 @@ pub mod builder { 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 402u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 409u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 422u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -90601,42 +104863,42 @@ pub mod builder { } } } - /**Builder for [`Client::export_evm_account_by_name`] + /**Builder for [`Client::sign_evm_message`] - [`Client::export_evm_account_by_name`]: super::Client::export_evm_account_by_name*/ + [`Client::sign_evm_message`]: super::Client::sign_evm_message*/ #[derive(Debug, Clone)] - pub struct ExportEvmAccountByName<'a> { + pub struct SignEvmMessage<'a> { client: &'a super::Client, - name: Result<::std::string::String, String>, - x_idempotency_key: Result, String>, + address: Result, + x_idempotency_key: Result, String>, x_wallet_auth: Result<::std::string::String, String>, - body: Result, + body: Result, } - impl<'a> ExportEvmAccountByName<'a> { + impl<'a> SignEvmMessage<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - name: Err("name was not initialized".to_string()), + address: Err("address was not initialized".to_string()), x_idempotency_key: Ok(None), x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), body: Ok(::std::default::Default::default()), } } - pub fn name(mut self, value: V) -> Self + pub fn address(mut self, value: V) -> Self where - V: std::convert::TryInto<::std::string::String>, + V: std::convert::TryInto, { - self.name = value.try_into().map_err(|_| { - "conversion to `:: std :: string :: String` for name failed".to_string() + self.address = value.try_into().map_err(|_| { + "conversion to `SignEvmMessageAddress` for address failed".to_string() }); self } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `ExportEvmAccountByNameXIdempotencyKey` for x_idempotency_key failed" + "conversion to `SignEvmMessageXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self @@ -90652,51 +104914,45 @@ pub mod builder { } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: - std::fmt::Display, + V: std::convert::TryInto, + >::Error: std::fmt::Display, { - self.body = value.try_into().map(From::from).map_err(|s| { - format!( - "conversion to `ExportEvmAccountByNameBody` for body failed: {}", - s - ) - }); + self.body = value + .try_into() + .map(From::from) + .map_err(|s| format!("conversion to `SignEvmMessageBody` for body failed: {}", s)); self } pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::ExportEvmAccountByNameBody, - ) -> types::builder::ExportEvmAccountByNameBody, + types::builder::SignEvmMessageBody, + ) -> types::builder::SignEvmMessageBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/evm/accounts/export/by-name/{name}` + ///Sends a `POST` request to `/v2/evm/accounts/{address}/sign/message` pub async fn send( self, - ) -> Result, Error> - { + ) -> Result, Error> { let Self { client, - name, + address, x_idempotency_key, x_wallet_auth, body, } = self; - let name = name.map_err(Error::InvalidRequest)?; + let address = address.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body - .and_then(|v| { - types::ExportEvmAccountByNameBody::try_from(v).map_err(|e| e.to_string()) - }) + .and_then(|v| types::SignEvmMessageBody::try_from(v).map_err(|e| e.to_string())) .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/evm/accounts/export/by-name/{}", + "{}/v2/evm/accounts/{}/sign/message", client.baseurl, - encode_path(&name.to_string()), + encode_path(&address.to_string()), ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( @@ -90719,7 +104975,7 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "export_evm_account_by_name", + operation_id: "sign_evm_message", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -90727,9 +104983,6 @@ pub mod builder { let response = result?; match response.status().as_u16() { 200u16 => ResponseValue::from_response::(response).await, - 400u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -90739,6 +104992,9 @@ pub mod builder { 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 409u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 422u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -90755,31 +105011,42 @@ pub mod builder { } } } - /**Builder for [`Client::import_evm_account`] + /**Builder for [`Client::sign_evm_transaction`] - [`Client::import_evm_account`]: super::Client::import_evm_account*/ + [`Client::sign_evm_transaction`]: super::Client::sign_evm_transaction*/ #[derive(Debug, Clone)] - pub struct ImportEvmAccount<'a> { + pub struct SignEvmTransaction<'a> { client: &'a super::Client, - x_idempotency_key: Result, String>, + address: Result, + x_idempotency_key: Result, String>, x_wallet_auth: Result<::std::string::String, String>, - body: Result, + body: Result, } - impl<'a> ImportEvmAccount<'a> { + impl<'a> SignEvmTransaction<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, + address: Err("address was not initialized".to_string()), x_idempotency_key: Ok(None), x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), body: Ok(::std::default::Default::default()), } } + pub fn address(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.address = value.try_into().map_err(|_| { + "conversion to `SignEvmTransactionAddress` for address failed".to_string() + }); + self + } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `ImportEvmAccountXIdempotencyKey` for x_idempotency_key failed" + "conversion to `SignEvmTransactionXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self @@ -90795,12 +105062,12 @@ pub mod builder { } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto, + >::Error: std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `ImportEvmAccountBody` for body failed: {}", + "conversion to `SignEvmTransactionBody` for body failed: {}", s ) }); @@ -90809,26 +105076,34 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::ImportEvmAccountBody, - ) -> types::builder::ImportEvmAccountBody, + types::builder::SignEvmTransactionBody, + ) -> types::builder::SignEvmTransactionBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/evm/accounts/import` - pub async fn send(self) -> Result, Error> { + ///Sends a `POST` request to `/v2/evm/accounts/{address}/sign/transaction` + pub async fn send( + self, + ) -> Result, Error> { let Self { client, + address, x_idempotency_key, x_wallet_auth, body, } = self; + let address = address.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body - .and_then(|v| types::ImportEvmAccountBody::try_from(v).map_err(|e| e.to_string())) + .and_then(|v| types::SignEvmTransactionBody::try_from(v).map_err(|e| e.to_string())) .map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/evm/accounts/import", client.baseurl,); + let url = format!( + "{}/v2/evm/accounts/{}/sign/transaction", + client.baseurl, + encode_path(&address.to_string()), + ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), @@ -90850,14 +105125,14 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "import_evm_account", + operation_id: "sign_evm_transaction", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 201u16 => ResponseValue::from_response::(response).await, + 200u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -90867,6 +105142,12 @@ pub mod builder { 402u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 403u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 404u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 409u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -90886,56 +105167,117 @@ pub mod builder { } } } - /**Builder for [`Client::get_evm_account`] + /**Builder for [`Client::sign_evm_typed_data`] - [`Client::get_evm_account`]: super::Client::get_evm_account*/ + [`Client::sign_evm_typed_data`]: super::Client::sign_evm_typed_data*/ #[derive(Debug, Clone)] - pub struct GetEvmAccount<'a> { + pub struct SignEvmTypedData<'a> { client: &'a super::Client, - address: Result, + address: Result, + x_idempotency_key: Result, String>, + x_wallet_auth: Result<::std::string::String, String>, + body: Result, } - impl<'a> GetEvmAccount<'a> { + impl<'a> SignEvmTypedData<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, address: Err("address was not initialized".to_string()), + x_idempotency_key: Ok(None), + x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), + body: Ok(::std::default::Default::default()), } } pub fn address(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.address = value + self.address = value.try_into().map_err(|_| { + "conversion to `SignEvmTypedDataAddress` for address failed".to_string() + }); + self + } + pub fn x_idempotency_key(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { + "conversion to `SignEvmTypedDataXIdempotencyKey` for x_idempotency_key failed" + .to_string() + }); + self + } + pub fn x_wallet_auth(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.x_wallet_auth = value.try_into().map_err(|_| { + "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() + }); + self + } + pub fn body(mut self, value: V) -> Self + where + V: std::convert::TryInto, + >::Error: std::fmt::Display, + { + self.body = value .try_into() - .map_err(|_| "conversion to `GetEvmAccountAddress` for address failed".to_string()); + .map(From::from) + .map_err(|s| format!("conversion to `Eip712Message` for body failed: {}", s)); self } - ///Sends a `GET` request to `/v2/evm/accounts/{address}` - pub async fn send(self) -> Result, Error> { - let Self { client, address } = self; + pub fn body_map(mut self, f: F) -> Self + where + F: std::ops::FnOnce(types::builder::Eip712Message) -> types::builder::Eip712Message, + { + self.body = self.body.map(f); + self + } + ///Sends a `POST` request to `/v2/evm/accounts/{address}/sign/typed-data` + pub async fn send( + self, + ) -> Result, Error> { + let Self { + client, + address, + x_idempotency_key, + x_wallet_auth, + body, + } = self; let address = address.map_err(Error::InvalidRequest)?; + let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; + let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; + let body = body + .and_then(|v| types::Eip712Message::try_from(v).map_err(|e| e.to_string())) + .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/evm/accounts/{}", + "{}/v2/evm/accounts/{}/sign/typed-data", client.baseurl, encode_path(&address.to_string()), ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); + if let Some(value) = x_idempotency_key { + header_map.append("X-Idempotency-Key", value.to_string().try_into()?); + } + header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client - .get(url) + .post(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) + .json(&body) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "get_evm_account", + operation_id: "sign_evm_typed_data", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -90946,9 +105288,18 @@ pub mod builder { 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 401u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 402u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 422u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -90962,105 +105313,64 @@ pub mod builder { } } } - /**Builder for [`Client::update_evm_account`] + /**Builder for [`Client::get_evm_eip7702_delegation_operation_by_id`] - [`Client::update_evm_account`]: super::Client::update_evm_account*/ + [`Client::get_evm_eip7702_delegation_operation_by_id`]: super::Client::get_evm_eip7702_delegation_operation_by_id*/ #[derive(Debug, Clone)] - pub struct UpdateEvmAccount<'a> { + pub struct GetEvmEip7702DelegationOperationById<'a> { client: &'a super::Client, - address: Result, - x_idempotency_key: Result, String>, - body: Result, + delegation_operation_id: Result<::uuid::Uuid, String>, } - impl<'a> UpdateEvmAccount<'a> { + impl<'a> GetEvmEip7702DelegationOperationById<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - address: Err("address was not initialized".to_string()), - x_idempotency_key: Ok(None), - body: Ok(::std::default::Default::default()), + delegation_operation_id: Err( + "delegation_operation_id was not initialized".to_string() + ), } } - pub fn address(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.address = value.try_into().map_err(|_| { - "conversion to `UpdateEvmAccountAddress` for address failed".to_string() - }); - self - } - pub fn x_idempotency_key(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `UpdateEvmAccountXIdempotencyKey` for x_idempotency_key failed" - .to_string() - }); - self - } - pub fn body(mut self, value: V) -> Self + pub fn delegation_operation_id(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto<::uuid::Uuid>, { - self.body = value.try_into().map(From::from).map_err(|s| { - format!( - "conversion to `UpdateEvmAccountBody` for body failed: {}", - s - ) + self.delegation_operation_id = value.try_into().map_err(|_| { + "conversion to `:: uuid :: Uuid` for delegation_operation_id failed".to_string() }); self } - pub fn body_map(mut self, f: F) -> Self - where - F: std::ops::FnOnce( - types::builder::UpdateEvmAccountBody, - ) -> types::builder::UpdateEvmAccountBody, + ///Sends a `GET` request to `/v2/evm/eip7702/delegation-operations/{delegationOperationId}` + pub async fn send( + self, + ) -> Result, Error> { - self.body = self.body.map(f); - self - } - ///Sends a `PUT` request to `/v2/evm/accounts/{address}` - pub async fn send(self) -> Result, Error> { let Self { client, - address, - x_idempotency_key, - body, + delegation_operation_id, } = self; - let address = address.map_err(Error::InvalidRequest)?; - let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; - let body = body - .and_then(|v| types::UpdateEvmAccountBody::try_from(v).map_err(|e| e.to_string())) - .map_err(Error::InvalidRequest)?; + let delegation_operation_id = delegation_operation_id.map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/evm/accounts/{}", + "{}/v2/evm/eip7702/delegation-operations/{}", client.baseurl, - encode_path(&address.to_string()), + encode_path(&delegation_operation_id.to_string()), ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(2usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); - if let Some(value) = x_idempotency_key { - header_map.append("X-Idempotency-Key", value.to_string().try_into()?); - } #[allow(unused_mut)] let mut request = client .client - .put(url) + .get(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) - .json(&body) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "update_evm_account", + operation_id: "get_evm_eip7702_delegation_operation_by_id", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -91074,12 +105384,6 @@ pub mod builder { 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 409u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 422u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -91093,67 +105397,29 @@ pub mod builder { } } } - /**Builder for [`Client::create_evm_eip7702_delegation`] + /**Builder for [`Client::request_evm_faucet`] - [`Client::create_evm_eip7702_delegation`]: super::Client::create_evm_eip7702_delegation*/ + [`Client::request_evm_faucet`]: super::Client::request_evm_faucet*/ #[derive(Debug, Clone)] - pub struct CreateEvmEip7702Delegation<'a> { + pub struct RequestEvmFaucet<'a> { client: &'a super::Client, - address: Result, - x_idempotency_key: Result, String>, - x_wallet_auth: Result<::std::string::String, String>, - body: Result, + body: Result, } - impl<'a> CreateEvmEip7702Delegation<'a> { + impl<'a> RequestEvmFaucet<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - address: Err("address was not initialized".to_string()), - x_idempotency_key: Ok(None), - x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), body: Ok(::std::default::Default::default()), } } - pub fn address(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.address = value.try_into().map_err(|_| { - "conversion to `CreateEvmEip7702DelegationAddress` for address failed".to_string() - }); - self - } - pub fn x_idempotency_key(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.x_idempotency_key = value - .try_into() - .map(Some) - .map_err(|_| { - "conversion to `CreateEvmEip7702DelegationXIdempotencyKey` for x_idempotency_key failed" - .to_string() - }); - self - } - pub fn x_wallet_auth(mut self, value: V) -> Self - where - V: std::convert::TryInto<::std::string::String>, - { - self.x_wallet_auth = value.try_into().map_err(|_| { - "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() - }); - self - } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: - std::fmt::Display, + V: std::convert::TryInto, + >::Error: std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `CreateEvmEip7702DelegationBody` for body failed: {}", + "conversion to `RequestEvmFaucetBody` for body failed: {}", s ) }); @@ -91162,46 +105428,26 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::CreateEvmEip7702DelegationBody, - ) -> types::builder::CreateEvmEip7702DelegationBody, + types::builder::RequestEvmFaucetBody, + ) -> types::builder::RequestEvmFaucetBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/evm/accounts/{address}/eip7702/delegation` + ///Sends a `POST` request to `/v2/evm/faucet` pub async fn send( self, - ) -> Result, Error> - { - let Self { - client, - address, - x_idempotency_key, - x_wallet_auth, - body, - } = self; - let address = address.map_err(Error::InvalidRequest)?; - let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; - let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; + ) -> Result, Error> { + let Self { client, body } = self; let body = body - .and_then(|v| { - types::CreateEvmEip7702DelegationBody::try_from(v).map_err(|e| e.to_string()) - }) + .and_then(|v| types::RequestEvmFaucetBody::try_from(v).map_err(|e| e.to_string())) .map_err(Error::InvalidRequest)?; - let url = format!( - "{}/v2/evm/accounts/{}/eip7702/delegation", - client.baseurl, - encode_path(&address.to_string()), - ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); + let url = format!("{}/v2/evm/faucet", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); - if let Some(value) = x_idempotency_key { - header_map.append("X-Idempotency-Key", value.to_string().try_into()?); - } - header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client @@ -91214,30 +105460,21 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "create_evm_eip7702_delegation", + operation_id: "request_evm_faucet", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 201u16 => ResponseValue::from_response::(response).await, + 200u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 401u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 402u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 404u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 409u16 => Err(Error::ErrorResponse( + 403u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 422u16 => Err(Error::ErrorResponse( + 429u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 500u16 => Err(Error::ErrorResponse( @@ -91253,121 +105490,79 @@ pub mod builder { } } } - /**Builder for [`Client::export_evm_account`] + /**Builder for [`Client::list_evm_smart_accounts`] - [`Client::export_evm_account`]: super::Client::export_evm_account*/ + [`Client::list_evm_smart_accounts`]: super::Client::list_evm_smart_accounts*/ #[derive(Debug, Clone)] - pub struct ExportEvmAccount<'a> { + pub struct ListEvmSmartAccounts<'a> { client: &'a super::Client, - address: Result, - x_idempotency_key: Result, String>, - x_wallet_auth: Result<::std::string::String, String>, - body: Result, + page_size: Result, String>, + page_token: Result, String>, } - impl<'a> ExportEvmAccount<'a> { + impl<'a> ListEvmSmartAccounts<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - address: Err("address was not initialized".to_string()), - x_idempotency_key: Ok(None), - x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), - body: Ok(::std::default::Default::default()), + page_size: Ok(None), + page_token: Ok(None), } } - pub fn address(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.address = value.try_into().map_err(|_| { - "conversion to `ExportEvmAccountAddress` for address failed".to_string() - }); - self - } - pub fn x_idempotency_key(mut self, value: V) -> Self + pub fn page_size(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `ExportEvmAccountXIdempotencyKey` for x_idempotency_key failed" - .to_string() - }); + self.page_size = value + .try_into() + .map(Some) + .map_err(|_| "conversion to `i64` for page_size failed".to_string()); self } - pub fn x_wallet_auth(mut self, value: V) -> Self + pub fn page_token(mut self, value: V) -> Self where V: std::convert::TryInto<::std::string::String>, { - self.x_wallet_auth = value.try_into().map_err(|_| { - "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() - }); - self - } - pub fn body(mut self, value: V) -> Self - where - V: std::convert::TryInto, - >::Error: std::fmt::Display, - { - self.body = value.try_into().map(From::from).map_err(|s| { - format!( - "conversion to `ExportEvmAccountBody` for body failed: {}", - s - ) + self.page_token = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for page_token failed".to_string() }); self } - pub fn body_map(mut self, f: F) -> Self - where - F: std::ops::FnOnce( - types::builder::ExportEvmAccountBody, - ) -> types::builder::ExportEvmAccountBody, - { - self.body = self.body.map(f); - self - } - ///Sends a `POST` request to `/v2/evm/accounts/{address}/export` + ///Sends a `GET` request to `/v2/evm/smart-accounts` pub async fn send( self, - ) -> Result, Error> { + ) -> Result, Error> + { let Self { client, - address, - x_idempotency_key, - x_wallet_auth, - body, + page_size, + page_token, } = self; - let address = address.map_err(Error::InvalidRequest)?; - let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; - let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; - let body = body - .and_then(|v| types::ExportEvmAccountBody::try_from(v).map_err(|e| e.to_string())) - .map_err(Error::InvalidRequest)?; - let url = format!( - "{}/v2/evm/accounts/{}/export", - client.baseurl, - encode_path(&address.to_string()), - ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); + let page_size = page_size.map_err(Error::InvalidRequest)?; + let page_token = page_token.map_err(Error::InvalidRequest)?; + let url = format!("{}/v2/evm/smart-accounts", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); - if let Some(value) = x_idempotency_key { - header_map.append("X-Idempotency-Key", value.to_string().try_into()?); - } - header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client - .post(url) + .get(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) - .json(&body) + .query(&progenitor_middleware_client::QueryParam::new( + "pageSize", &page_size, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "pageToken", + &page_token, + )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "export_evm_account", + operation_id: "list_evm_smart_accounts", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -91378,18 +105573,6 @@ pub mod builder { 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 401u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 402u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 404u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 422u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -91403,63 +105586,42 @@ pub mod builder { } } } - /**Builder for [`Client::send_evm_transaction`] + /**Builder for [`Client::create_evm_smart_account`] - [`Client::send_evm_transaction`]: super::Client::send_evm_transaction*/ + [`Client::create_evm_smart_account`]: super::Client::create_evm_smart_account*/ #[derive(Debug, Clone)] - pub struct SendEvmTransaction<'a> { + pub struct CreateEvmSmartAccount<'a> { client: &'a super::Client, - address: Result, - x_idempotency_key: Result, String>, - x_wallet_auth: Result<::std::string::String, String>, - body: Result, + x_idempotency_key: Result, String>, + body: Result, } - impl<'a> SendEvmTransaction<'a> { + impl<'a> CreateEvmSmartAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - address: Err("address was not initialized".to_string()), x_idempotency_key: Ok(None), - x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), body: Ok(::std::default::Default::default()), } } - pub fn address(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.address = value.try_into().map_err(|_| { - "conversion to `SendEvmTransactionAddress` for address failed".to_string() - }); - self - } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `SendEvmTransactionXIdempotencyKey` for x_idempotency_key failed" + "conversion to `CreateEvmSmartAccountXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self } - pub fn x_wallet_auth(mut self, value: V) -> Self - where - V: std::convert::TryInto<::std::string::String>, - { - self.x_wallet_auth = value.try_into().map_err(|_| { - "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() - }); - self - } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto, + >::Error: + std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `SendEvmTransactionBody` for body failed: {}", + "conversion to `CreateEvmSmartAccountBody` for body failed: {}", s ) }); @@ -91468,35 +105630,29 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::SendEvmTransactionBody, - ) -> types::builder::SendEvmTransactionBody, + types::builder::CreateEvmSmartAccountBody, + ) -> types::builder::CreateEvmSmartAccountBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/evm/accounts/{address}/send/transaction` + ///Sends a `POST` request to `/v2/evm/smart-accounts` pub async fn send( self, - ) -> Result, Error> { + ) -> Result, Error> { let Self { client, - address, x_idempotency_key, - x_wallet_auth, body, } = self; - let address = address.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; - let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body - .and_then(|v| types::SendEvmTransactionBody::try_from(v).map_err(|e| e.to_string())) + .and_then(|v| { + types::CreateEvmSmartAccountBody::try_from(v).map_err(|e| e.to_string()) + }) .map_err(Error::InvalidRequest)?; - let url = format!( - "{}/v2/evm/accounts/{}/send/transaction", - client.baseurl, - encode_path(&address.to_string()), - ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); + let url = format!("{}/v2/evm/smart-accounts", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(2usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), @@ -91504,7 +105660,6 @@ pub mod builder { if let Some(value) = x_idempotency_key { header_map.append("X-Idempotency-Key", value.to_string().try_into()?); } - header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client @@ -91517,35 +105672,20 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "send_evm_transaction", + operation_id: "create_evm_smart_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 200u16 => ResponseValue::from_response::(response).await, + 201u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 401u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 402u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 403u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 404u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 409u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 422u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -91559,117 +105699,58 @@ pub mod builder { } } } - /**Builder for [`Client::sign_evm_hash`] + /**Builder for [`Client::get_evm_smart_account_by_name`] - [`Client::sign_evm_hash`]: super::Client::sign_evm_hash*/ + [`Client::get_evm_smart_account_by_name`]: super::Client::get_evm_smart_account_by_name*/ #[derive(Debug, Clone)] - pub struct SignEvmHash<'a> { + pub struct GetEvmSmartAccountByName<'a> { client: &'a super::Client, - address: Result, - x_idempotency_key: Result, String>, - x_wallet_auth: Result<::std::string::String, String>, - body: Result, + name: Result<::std::string::String, String>, } - impl<'a> SignEvmHash<'a> { + impl<'a> GetEvmSmartAccountByName<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - address: Err("address was not initialized".to_string()), - x_idempotency_key: Ok(None), - x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), - body: Ok(::std::default::Default::default()), + name: Err("name was not initialized".to_string()), } } - pub fn address(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.address = value - .try_into() - .map_err(|_| "conversion to `SignEvmHashAddress` for address failed".to_string()); - self - } - pub fn x_idempotency_key(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `SignEvmHashXIdempotencyKey` for x_idempotency_key failed" - .to_string() - }); - self - } - pub fn x_wallet_auth(mut self, value: V) -> Self + pub fn name(mut self, value: V) -> Self where V: std::convert::TryInto<::std::string::String>, { - self.x_wallet_auth = value.try_into().map_err(|_| { - "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() + self.name = value.try_into().map_err(|_| { + "conversion to `:: std :: string :: String` for name failed".to_string() }); self } - pub fn body(mut self, value: V) -> Self - where - V: std::convert::TryInto, - >::Error: std::fmt::Display, - { - self.body = value - .try_into() - .map(From::from) - .map_err(|s| format!("conversion to `SignEvmHashBody` for body failed: {}", s)); - self - } - pub fn body_map(mut self, f: F) -> Self - where - F: std::ops::FnOnce(types::builder::SignEvmHashBody) -> types::builder::SignEvmHashBody, - { - self.body = self.body.map(f); - self - } - ///Sends a `POST` request to `/v2/evm/accounts/{address}/sign` + ///Sends a `GET` request to `/v2/evm/smart-accounts/by-name/{name}` pub async fn send( self, - ) -> Result, Error> { - let Self { - client, - address, - x_idempotency_key, - x_wallet_auth, - body, - } = self; - let address = address.map_err(Error::InvalidRequest)?; - let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; - let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; - let body = body - .and_then(|v| types::SignEvmHashBody::try_from(v).map_err(|e| e.to_string())) - .map_err(Error::InvalidRequest)?; + ) -> Result, Error> { + let Self { client, name } = self; + let name = name.map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/evm/accounts/{}/sign", + "{}/v2/evm/smart-accounts/by-name/{}", client.baseurl, - encode_path(&address.to_string()), + encode_path(&name.to_string()), ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); - if let Some(value) = x_idempotency_key { - header_map.append("X-Idempotency-Key", value.to_string().try_into()?); - } - header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client - .post(url) + .get(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) - .json(&body) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "sign_evm_hash", + operation_id: "get_evm_smart_account_by_name", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -91680,18 +105761,9 @@ pub mod builder { 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 402u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 409u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 422u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -91705,119 +105777,58 @@ pub mod builder { } } } - /**Builder for [`Client::sign_evm_message`] + /**Builder for [`Client::get_evm_smart_account`] - [`Client::sign_evm_message`]: super::Client::sign_evm_message*/ + [`Client::get_evm_smart_account`]: super::Client::get_evm_smart_account*/ #[derive(Debug, Clone)] - pub struct SignEvmMessage<'a> { + pub struct GetEvmSmartAccount<'a> { client: &'a super::Client, - address: Result, - x_idempotency_key: Result, String>, - x_wallet_auth: Result<::std::string::String, String>, - body: Result, + address: Result, } - impl<'a> SignEvmMessage<'a> { + impl<'a> GetEvmSmartAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, address: Err("address was not initialized".to_string()), - x_idempotency_key: Ok(None), - x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), - body: Ok(::std::default::Default::default()), } } pub fn address(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.address = value.try_into().map_err(|_| { - "conversion to `SignEvmMessageAddress` for address failed".to_string() - }); - self - } - pub fn x_idempotency_key(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `SignEvmMessageXIdempotencyKey` for x_idempotency_key failed" - .to_string() - }); - self - } - pub fn x_wallet_auth(mut self, value: V) -> Self - where - V: std::convert::TryInto<::std::string::String>, - { - self.x_wallet_auth = value.try_into().map_err(|_| { - "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() + "conversion to `GetEvmSmartAccountAddress` for address failed".to_string() }); self } - pub fn body(mut self, value: V) -> Self - where - V: std::convert::TryInto, - >::Error: std::fmt::Display, - { - self.body = value - .try_into() - .map(From::from) - .map_err(|s| format!("conversion to `SignEvmMessageBody` for body failed: {}", s)); - self - } - pub fn body_map(mut self, f: F) -> Self - where - F: std::ops::FnOnce( - types::builder::SignEvmMessageBody, - ) -> types::builder::SignEvmMessageBody, - { - self.body = self.body.map(f); - self - } - ///Sends a `POST` request to `/v2/evm/accounts/{address}/sign/message` + ///Sends a `GET` request to `/v2/evm/smart-accounts/{address}` pub async fn send( self, - ) -> Result, Error> { - let Self { - client, - address, - x_idempotency_key, - x_wallet_auth, - body, - } = self; + ) -> Result, Error> { + let Self { client, address } = self; let address = address.map_err(Error::InvalidRequest)?; - let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; - let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; - let body = body - .and_then(|v| types::SignEvmMessageBody::try_from(v).map_err(|e| e.to_string())) - .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/evm/accounts/{}/sign/message", + "{}/v2/evm/smart-accounts/{}", client.baseurl, encode_path(&address.to_string()), ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); - if let Some(value) = x_idempotency_key { - header_map.append("X-Idempotency-Key", value.to_string().try_into()?); - } - header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client - .post(url) + .get(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) - .json(&body) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "sign_evm_message", + operation_id: "get_evm_smart_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -91825,21 +105836,12 @@ pub mod builder { let response = result?; match response.status().as_u16() { 200u16 => ResponseValue::from_response::(response).await, - 401u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 402u16 => Err(Error::ErrorResponse( + 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 409u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 422u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -91853,63 +105855,41 @@ pub mod builder { } } } - /**Builder for [`Client::sign_evm_transaction`] + /**Builder for [`Client::update_evm_smart_account`] - [`Client::sign_evm_transaction`]: super::Client::sign_evm_transaction*/ + [`Client::update_evm_smart_account`]: super::Client::update_evm_smart_account*/ #[derive(Debug, Clone)] - pub struct SignEvmTransaction<'a> { + pub struct UpdateEvmSmartAccount<'a> { client: &'a super::Client, - address: Result, - x_idempotency_key: Result, String>, - x_wallet_auth: Result<::std::string::String, String>, - body: Result, + address: Result, + body: Result, } - impl<'a> SignEvmTransaction<'a> { + impl<'a> UpdateEvmSmartAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, address: Err("address was not initialized".to_string()), - x_idempotency_key: Ok(None), - x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), body: Ok(::std::default::Default::default()), } } pub fn address(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.address = value.try_into().map_err(|_| { - "conversion to `SignEvmTransactionAddress` for address failed".to_string() - }); - self - } - pub fn x_idempotency_key(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `SignEvmTransactionXIdempotencyKey` for x_idempotency_key failed" - .to_string() - }); - self - } - pub fn x_wallet_auth(mut self, value: V) -> Self - where - V: std::convert::TryInto<::std::string::String>, - { - self.x_wallet_auth = value.try_into().map_err(|_| { - "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() + "conversion to `UpdateEvmSmartAccountAddress` for address failed".to_string() }); self } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto, + >::Error: + std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `SignEvmTransactionBody` for body failed: {}", + "conversion to `UpdateEvmSmartAccountBody` for body failed: {}", s ) }); @@ -91918,47 +105898,41 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::SignEvmTransactionBody, - ) -> types::builder::SignEvmTransactionBody, + types::builder::UpdateEvmSmartAccountBody, + ) -> types::builder::UpdateEvmSmartAccountBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/evm/accounts/{address}/sign/transaction` + ///Sends a `PUT` request to `/v2/evm/smart-accounts/{address}` pub async fn send( self, - ) -> Result, Error> { + ) -> Result, Error> { let Self { client, address, - x_idempotency_key, - x_wallet_auth, body, } = self; let address = address.map_err(Error::InvalidRequest)?; - let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; - let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body - .and_then(|v| types::SignEvmTransactionBody::try_from(v).map_err(|e| e.to_string())) + .and_then(|v| { + types::UpdateEvmSmartAccountBody::try_from(v).map_err(|e| e.to_string()) + }) .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/evm/accounts/{}/sign/transaction", + "{}/v2/evm/smart-accounts/{}", client.baseurl, encode_path(&address.to_string()), ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); - if let Some(value) = x_idempotency_key { - header_map.append("X-Idempotency-Key", value.to_string().try_into()?); - } - header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client - .post(url) + .put(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), @@ -91967,7 +105941,7 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "sign_evm_transaction", + operation_id: "update_evm_smart_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -91978,15 +105952,6 @@ pub mod builder { 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 401u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 402u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 403u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -92009,18 +105974,18 @@ pub mod builder { } } } - /**Builder for [`Client::sign_evm_typed_data`] + /**Builder for [`Client::create_spend_permission`] - [`Client::sign_evm_typed_data`]: super::Client::sign_evm_typed_data*/ + [`Client::create_spend_permission`]: super::Client::create_spend_permission*/ #[derive(Debug, Clone)] - pub struct SignEvmTypedData<'a> { + pub struct CreateSpendPermission<'a> { client: &'a super::Client, - address: Result, - x_idempotency_key: Result, String>, + address: Result, + x_idempotency_key: Result, String>, x_wallet_auth: Result<::std::string::String, String>, - body: Result, + body: Result, } - impl<'a> SignEvmTypedData<'a> { + impl<'a> CreateSpendPermission<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, @@ -92032,19 +105997,19 @@ pub mod builder { } pub fn address(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.address = value.try_into().map_err(|_| { - "conversion to `SignEvmTypedDataAddress` for address failed".to_string() + "conversion to `CreateSpendPermissionAddress` for address failed".to_string() }); self } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `SignEvmTypedDataXIdempotencyKey` for x_idempotency_key failed" + "conversion to `CreateSpendPermissionXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self @@ -92060,26 +106025,31 @@ pub mod builder { } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, - { - self.body = value - .try_into() - .map(From::from) - .map_err(|s| format!("conversion to `Eip712Message` for body failed: {}", s)); + V: std::convert::TryInto, + >::Error: + std::fmt::Display, + { + self.body = value.try_into().map(From::from).map_err(|s| { + format!( + "conversion to `CreateSpendPermissionRequest` for body failed: {}", + s + ) + }); self } pub fn body_map(mut self, f: F) -> Self where - F: std::ops::FnOnce(types::builder::Eip712Message) -> types::builder::Eip712Message, + F: std::ops::FnOnce( + types::builder::CreateSpendPermissionRequest, + ) -> types::builder::CreateSpendPermissionRequest, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/evm/accounts/{address}/sign/typed-data` + ///Sends a `POST` request to `/v2/evm/smart-accounts/{address}/spend-permissions` pub async fn send( self, - ) -> Result, Error> { + ) -> Result, Error> { let Self { client, address, @@ -92091,10 +106061,12 @@ pub mod builder { let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body - .and_then(|v| types::Eip712Message::try_from(v).map_err(|e| e.to_string())) + .and_then(|v| { + types::CreateSpendPermissionRequest::try_from(v).map_err(|e| e.to_string()) + }) .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/evm/accounts/{}/sign/typed-data", + "{}/v2/evm/smart-accounts/{}/spend-permissions", client.baseurl, encode_path(&address.to_string()), ); @@ -92119,7 +106091,7 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "sign_evm_typed_data", + operation_id: "create_spend_permission", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -92130,18 +106102,9 @@ pub mod builder { 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 401u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 402u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 422u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -92155,46 +106118,71 @@ pub mod builder { } } } - /**Builder for [`Client::get_evm_eip7702_delegation_operation_by_id`] + /**Builder for [`Client::list_spend_permissions`] - [`Client::get_evm_eip7702_delegation_operation_by_id`]: super::Client::get_evm_eip7702_delegation_operation_by_id*/ + [`Client::list_spend_permissions`]: super::Client::list_spend_permissions*/ #[derive(Debug, Clone)] - pub struct GetEvmEip7702DelegationOperationById<'a> { + pub struct ListSpendPermissions<'a> { client: &'a super::Client, - delegation_operation_id: Result<::uuid::Uuid, String>, + address: Result, + page_size: Result, String>, + page_token: Result, String>, } - impl<'a> GetEvmEip7702DelegationOperationById<'a> { + impl<'a> ListSpendPermissions<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - delegation_operation_id: Err( - "delegation_operation_id was not initialized".to_string() - ), + address: Err("address was not initialized".to_string()), + page_size: Ok(None), + page_token: Ok(None), } } - pub fn delegation_operation_id(mut self, value: V) -> Self + pub fn address(mut self, value: V) -> Self where - V: std::convert::TryInto<::uuid::Uuid>, + V: std::convert::TryInto, { - self.delegation_operation_id = value.try_into().map_err(|_| { - "conversion to `:: uuid :: Uuid` for delegation_operation_id failed".to_string() + self.address = value.try_into().map_err(|_| { + "conversion to `ListSpendPermissionsAddress` for address failed".to_string() }); self } - ///Sends a `GET` request to `/v2/evm/eip7702/delegation-operations/{delegationOperationId}` + pub fn page_size(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.page_size = value + .try_into() + .map(Some) + .map_err(|_| "conversion to `i64` for page_size failed".to_string()); + self + } + pub fn page_token(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.page_token = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for page_token failed".to_string() + }); + self + } + ///Sends a `GET` request to `/v2/evm/smart-accounts/{address}/spend-permissions/list` pub async fn send( self, - ) -> Result, Error> + ) -> Result, Error> { let Self { client, - delegation_operation_id, + address, + page_size, + page_token, } = self; - let delegation_operation_id = delegation_operation_id.map_err(Error::InvalidRequest)?; + let address = address.map_err(Error::InvalidRequest)?; + let page_size = page_size.map_err(Error::InvalidRequest)?; + let page_token = page_token.map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/evm/eip7702/delegation-operations/{}", + "{}/v2/evm/smart-accounts/{}/spend-permissions/list", client.baseurl, - encode_path(&delegation_operation_id.to_string()), + encode_path(&address.to_string()), ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( @@ -92209,10 +106197,17 @@ pub mod builder { ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) + .query(&progenitor_middleware_client::QueryParam::new( + "pageSize", &page_size, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "pageToken", + &page_token, + )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "get_evm_eip7702_delegation_operation_by_id", + operation_id: "list_spend_permissions", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -92239,29 +106234,64 @@ pub mod builder { } } } - /**Builder for [`Client::request_evm_faucet`] + /**Builder for [`Client::revoke_spend_permission`] - [`Client::request_evm_faucet`]: super::Client::request_evm_faucet*/ + [`Client::revoke_spend_permission`]: super::Client::revoke_spend_permission*/ #[derive(Debug, Clone)] - pub struct RequestEvmFaucet<'a> { + pub struct RevokeSpendPermission<'a> { client: &'a super::Client, - body: Result, + address: Result, + x_idempotency_key: Result, String>, + x_wallet_auth: Result<::std::string::String, String>, + body: Result, } - impl<'a> RequestEvmFaucet<'a> { + impl<'a> RevokeSpendPermission<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, + address: Err("address was not initialized".to_string()), + x_idempotency_key: Ok(None), + x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), body: Ok(::std::default::Default::default()), } } + pub fn address(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.address = value.try_into().map_err(|_| { + "conversion to `RevokeSpendPermissionAddress` for address failed".to_string() + }); + self + } + pub fn x_idempotency_key(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { + "conversion to `RevokeSpendPermissionXIdempotencyKey` for x_idempotency_key failed" + .to_string() + }); + self + } + pub fn x_wallet_auth(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.x_wallet_auth = value.try_into().map_err(|_| { + "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() + }); + self + } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto, + >::Error: + std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `RequestEvmFaucetBody` for body failed: {}", + "conversion to `RevokeSpendPermissionRequest` for body failed: {}", s ) }); @@ -92270,26 +106300,45 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::RequestEvmFaucetBody, - ) -> types::builder::RequestEvmFaucetBody, + types::builder::RevokeSpendPermissionRequest, + ) -> types::builder::RevokeSpendPermissionRequest, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/evm/faucet` + ///Sends a `POST` request to `/v2/evm/smart-accounts/{address}/spend-permissions/revoke` pub async fn send( self, - ) -> Result, Error> { - let Self { client, body } = self; + ) -> Result, Error> { + let Self { + client, + address, + x_idempotency_key, + x_wallet_auth, + body, + } = self; + let address = address.map_err(Error::InvalidRequest)?; + let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; + let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body - .and_then(|v| types::RequestEvmFaucetBody::try_from(v).map_err(|e| e.to_string())) + .and_then(|v| { + types::RevokeSpendPermissionRequest::try_from(v).map_err(|e| e.to_string()) + }) .map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/evm/faucet", client.baseurl,); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + let url = format!( + "{}/v2/evm/smart-accounts/{}/spend-permissions/revoke", + client.baseurl, + encode_path(&address.to_string()), + ); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); + if let Some(value) = x_idempotency_key { + header_map.append("X-Idempotency-Key", value.to_string().try_into()?); + } + header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client @@ -92302,7 +106351,7 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "request_evm_faucet", + operation_id: "revoke_spend_permission", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -92313,10 +106362,7 @@ pub mod builder { 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 403u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 429u16 => Err(Error::ErrorResponse( + 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 500u16 => Err(Error::ErrorResponse( @@ -92332,55 +106378,74 @@ pub mod builder { } } } - /**Builder for [`Client::list_evm_smart_accounts`] + /**Builder for [`Client::prepare_user_operation`] - [`Client::list_evm_smart_accounts`]: super::Client::list_evm_smart_accounts*/ + [`Client::prepare_user_operation`]: super::Client::prepare_user_operation*/ #[derive(Debug, Clone)] - pub struct ListEvmSmartAccounts<'a> { + pub struct PrepareUserOperation<'a> { client: &'a super::Client, - page_size: Result, String>, - page_token: Result, String>, + address: Result, + body: Result, } - impl<'a> ListEvmSmartAccounts<'a> { + impl<'a> PrepareUserOperation<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - page_size: Ok(None), - page_token: Ok(None), + address: Err("address was not initialized".to_string()), + body: Ok(::std::default::Default::default()), } } - pub fn page_size(mut self, value: V) -> Self + pub fn address(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.page_size = value - .try_into() - .map(Some) - .map_err(|_| "conversion to `i64` for page_size failed".to_string()); + self.address = value.try_into().map_err(|_| { + "conversion to `PrepareUserOperationAddress` for address failed".to_string() + }); self } - pub fn page_token(mut self, value: V) -> Self + pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto<::std::string::String>, + V: std::convert::TryInto, + >::Error: std::fmt::Display, { - self.page_token = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: string :: String` for page_token failed".to_string() + self.body = value.try_into().map(From::from).map_err(|s| { + format!( + "conversion to `PrepareUserOperationBody` for body failed: {}", + s + ) }); self } - ///Sends a `GET` request to `/v2/evm/smart-accounts` + pub fn body_map(mut self, f: F) -> Self + where + F: std::ops::FnOnce( + types::builder::PrepareUserOperationBody, + ) -> types::builder::PrepareUserOperationBody, + { + self.body = self.body.map(f); + self + } + ///Sends a `POST` request to `/v2/evm/smart-accounts/{address}/user-operations` pub async fn send( self, - ) -> Result, Error> - { + ) -> Result, Error> { let Self { client, - page_size, - page_token, + address, + body, } = self; - let page_size = page_size.map_err(Error::InvalidRequest)?; - let page_token = page_token.map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/evm/smart-accounts", client.baseurl,); + let address = address.map_err(Error::InvalidRequest)?; + let body = body + .and_then(|v| { + types::PrepareUserOperationBody::try_from(v).map_err(|e| e.to_string()) + }) + .map_err(Error::InvalidRequest)?; + let url = format!( + "{}/v2/evm/smart-accounts/{}/user-operations", + client.baseurl, + encode_path(&address.to_string()), + ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), @@ -92389,32 +106454,32 @@ pub mod builder { #[allow(unused_mut)] let mut request = client .client - .get(url) + .post(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) - .query(&progenitor_middleware_client::QueryParam::new( - "pageSize", &page_size, - )) - .query(&progenitor_middleware_client::QueryParam::new( - "pageToken", - &page_token, - )) + .json(&body) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "list_evm_smart_accounts", + operation_id: "prepare_user_operation", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 200u16 => ResponseValue::from_response::(response).await, + 201u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 403u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 404u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -92428,42 +106493,68 @@ pub mod builder { } } } - /**Builder for [`Client::create_evm_smart_account`] + /**Builder for [`Client::prepare_and_send_user_operation`] - [`Client::create_evm_smart_account`]: super::Client::create_evm_smart_account*/ + [`Client::prepare_and_send_user_operation`]: super::Client::prepare_and_send_user_operation*/ #[derive(Debug, Clone)] - pub struct CreateEvmSmartAccount<'a> { + pub struct PrepareAndSendUserOperation<'a> { client: &'a super::Client, - x_idempotency_key: Result, String>, - body: Result, + address: Result, + x_idempotency_key: + Result, String>, + x_wallet_auth: Result<::std::string::String, String>, + body: Result, } - impl<'a> CreateEvmSmartAccount<'a> { + impl<'a> PrepareAndSendUserOperation<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, + address: Err("address was not initialized".to_string()), x_idempotency_key: Ok(None), + x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), body: Ok(::std::default::Default::default()), } } + pub fn address(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.address = value.try_into().map_err(|_| { + "conversion to `PrepareAndSendUserOperationAddress` for address failed".to_string() + }); + self + } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `CreateEvmSmartAccountXIdempotencyKey` for x_idempotency_key failed" - .to_string() + self.x_idempotency_key = value + .try_into() + .map(Some) + .map_err(|_| { + "conversion to `PrepareAndSendUserOperationXIdempotencyKey` for x_idempotency_key failed" + .to_string() + }); + self + } + pub fn x_wallet_auth(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.x_wallet_auth = value.try_into().map_err(|_| { + "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() }); self } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: + V: std::convert::TryInto, + >::Error: std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `CreateEvmSmartAccountBody` for body failed: {}", + "conversion to `PrepareAndSendUserOperationBody` for body failed: {}", s ) }); @@ -92472,29 +106563,37 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::CreateEvmSmartAccountBody, - ) -> types::builder::CreateEvmSmartAccountBody, + types::builder::PrepareAndSendUserOperationBody, + ) -> types::builder::PrepareAndSendUserOperationBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/evm/smart-accounts` + ///Sends a `POST` request to `/v2/evm/smart-accounts/{address}/user-operations/prepare-and-send` pub async fn send( self, - ) -> Result, Error> { + ) -> Result, Error> { let Self { client, + address, x_idempotency_key, + x_wallet_auth, body, } = self; + let address = address.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; + let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body .and_then(|v| { - types::CreateEvmSmartAccountBody::try_from(v).map_err(|e| e.to_string()) + types::PrepareAndSendUserOperationBody::try_from(v).map_err(|e| e.to_string()) }) .map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/evm/smart-accounts", client.baseurl,); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(2usize); + let url = format!( + "{}/v2/evm/smart-accounts/{}/user-operations/prepare-and-send", + client.baseurl, + encode_path(&address.to_string()), + ); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), @@ -92502,6 +106601,7 @@ pub mod builder { if let Some(value) = x_idempotency_key { header_map.append("X-Idempotency-Key", value.to_string().try_into()?); } + header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client @@ -92514,96 +106614,30 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "create_evm_smart_account", + operation_id: "prepare_and_send_user_operation", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 201u16 => ResponseValue::from_response::(response).await, + 200u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 402u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 500u16 => Err(Error::ErrorResponse( + 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 502u16 => Err(Error::ErrorResponse( + 402u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 503u16 => Err(Error::ErrorResponse( + 403u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - _ => Err(Error::UnexpectedResponse(response)), - } - } - } - /**Builder for [`Client::get_evm_smart_account_by_name`] - - [`Client::get_evm_smart_account_by_name`]: super::Client::get_evm_smart_account_by_name*/ - #[derive(Debug, Clone)] - pub struct GetEvmSmartAccountByName<'a> { - client: &'a super::Client, - name: Result<::std::string::String, String>, - } - impl<'a> GetEvmSmartAccountByName<'a> { - pub fn new(client: &'a super::Client) -> Self { - Self { - client: client, - name: Err("name was not initialized".to_string()), - } - } - pub fn name(mut self, value: V) -> Self - where - V: std::convert::TryInto<::std::string::String>, - { - self.name = value.try_into().map_err(|_| { - "conversion to `:: std :: string :: String` for name failed".to_string() - }); - self - } - ///Sends a `GET` request to `/v2/evm/smart-accounts/by-name/{name}` - pub async fn send( - self, - ) -> Result, Error> { - let Self { client, name } = self; - let name = name.map_err(Error::InvalidRequest)?; - let url = format!( - "{}/v2/evm/smart-accounts/by-name/{}", - client.baseurl, - encode_path(&name.to_string()), - ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); - header_map.append( - ::reqwest::header::HeaderName::from_static("api-version"), - ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), - ); - #[allow(unused_mut)] - let mut request = client - .client - .get(url) - .header( - ::reqwest::header::ACCEPT, - ::reqwest::header::HeaderValue::from_static("application/json"), - ) - .headers(header_map) - .build()?; - let info = OperationInfo { - operation_id: "get_evm_smart_account_by_name", - }; - client.pre(&mut request, &info).await?; - let result = client.exec(request, &info).await; - client.post(&result, &info).await?; - let response = result?; - match response.status().as_u16() { - 200u16 => ResponseValue::from_response::(response).await, - 400u16 => Err(Error::ErrorResponse( + 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 404u16 => Err(Error::ErrorResponse( + 429u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 500u16 => Err(Error::ErrorResponse( @@ -92619,40 +106653,57 @@ pub mod builder { } } } - /**Builder for [`Client::get_evm_smart_account`] + /**Builder for [`Client::get_user_operation`] - [`Client::get_evm_smart_account`]: super::Client::get_evm_smart_account*/ + [`Client::get_user_operation`]: super::Client::get_user_operation*/ #[derive(Debug, Clone)] - pub struct GetEvmSmartAccount<'a> { + pub struct GetUserOperation<'a> { client: &'a super::Client, - address: Result, + address: Result, + user_op_hash: Result, } - impl<'a> GetEvmSmartAccount<'a> { + impl<'a> GetUserOperation<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, address: Err("address was not initialized".to_string()), + user_op_hash: Err("user_op_hash was not initialized".to_string()), } } pub fn address(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.address = value.try_into().map_err(|_| { - "conversion to `GetEvmSmartAccountAddress` for address failed".to_string() + "conversion to `GetUserOperationAddress` for address failed".to_string() }); self } - ///Sends a `GET` request to `/v2/evm/smart-accounts/{address}` + pub fn user_op_hash(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.user_op_hash = value.try_into().map_err(|_| { + "conversion to `GetUserOperationUserOpHash` for user_op_hash failed".to_string() + }); + self + } + ///Sends a `GET` request to `/v2/evm/smart-accounts/{address}/user-operations/{userOpHash}` pub async fn send( self, - ) -> Result, Error> { - let Self { client, address } = self; + ) -> Result, Error> { + let Self { + client, + address, + user_op_hash, + } = self; let address = address.map_err(Error::InvalidRequest)?; + let user_op_hash = user_op_hash.map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/evm/smart-accounts/{}", + "{}/v2/evm/smart-accounts/{}/user-operations/{}", client.baseurl, encode_path(&address.to_string()), + encode_path(&user_op_hash.to_string()), ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( @@ -92670,7 +106721,7 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "get_evm_smart_account", + operation_id: "get_user_operation", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -92697,41 +106748,51 @@ pub mod builder { } } } - /**Builder for [`Client::update_evm_smart_account`] + /**Builder for [`Client::send_user_operation`] - [`Client::update_evm_smart_account`]: super::Client::update_evm_smart_account*/ + [`Client::send_user_operation`]: super::Client::send_user_operation*/ #[derive(Debug, Clone)] - pub struct UpdateEvmSmartAccount<'a> { + pub struct SendUserOperation<'a> { client: &'a super::Client, - address: Result, - body: Result, + address: Result, + user_op_hash: Result, + body: Result, } - impl<'a> UpdateEvmSmartAccount<'a> { + impl<'a> SendUserOperation<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, address: Err("address was not initialized".to_string()), + user_op_hash: Err("user_op_hash was not initialized".to_string()), body: Ok(::std::default::Default::default()), } } pub fn address(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.address = value.try_into().map_err(|_| { - "conversion to `UpdateEvmSmartAccountAddress` for address failed".to_string() + "conversion to `SendUserOperationAddress` for address failed".to_string() + }); + self + } + pub fn user_op_hash(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.user_op_hash = value.try_into().map_err(|_| { + "conversion to `SendUserOperationUserOpHash` for user_op_hash failed".to_string() }); self } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: - std::fmt::Display, + V: std::convert::TryInto, + >::Error: std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `UpdateEvmSmartAccountBody` for body failed: {}", + "conversion to `SendUserOperationBody` for body failed: {}", s ) }); @@ -92740,31 +106801,32 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::UpdateEvmSmartAccountBody, - ) -> types::builder::UpdateEvmSmartAccountBody, + types::builder::SendUserOperationBody, + ) -> types::builder::SendUserOperationBody, { self.body = self.body.map(f); self } - ///Sends a `PUT` request to `/v2/evm/smart-accounts/{address}` + ///Sends a `POST` request to `/v2/evm/smart-accounts/{address}/user-operations/{userOpHash}/send` pub async fn send( self, - ) -> Result, Error> { + ) -> Result, Error> { let Self { client, address, + user_op_hash, body, } = self; let address = address.map_err(Error::InvalidRequest)?; + let user_op_hash = user_op_hash.map_err(Error::InvalidRequest)?; let body = body - .and_then(|v| { - types::UpdateEvmSmartAccountBody::try_from(v).map_err(|e| e.to_string()) - }) + .and_then(|v| types::SendUserOperationBody::try_from(v).map_err(|e| e.to_string())) .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/evm/smart-accounts/{}", + "{}/v2/evm/smart-accounts/{}/user-operations/{}/send", client.baseurl, encode_path(&address.to_string()), + encode_path(&user_op_hash.to_string()), ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( @@ -92774,7 +106836,7 @@ pub mod builder { #[allow(unused_mut)] let mut request = client .client - .put(url) + .post(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), @@ -92783,7 +106845,7 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "update_evm_smart_account", + operation_id: "send_user_operation", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -92794,13 +106856,16 @@ pub mod builder { 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 404u16 => Err(Error::ErrorResponse( + 402u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 409u16 => Err(Error::ErrorResponse( + 403u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 422u16 => Err(Error::ErrorResponse( + 404u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 429u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 500u16 => Err(Error::ErrorResponse( @@ -92816,64 +106881,41 @@ pub mod builder { } } } - /**Builder for [`Client::create_spend_permission`] + /**Builder for [`Client::create_evm_swap_quote`] - [`Client::create_spend_permission`]: super::Client::create_spend_permission*/ + [`Client::create_evm_swap_quote`]: super::Client::create_evm_swap_quote*/ #[derive(Debug, Clone)] - pub struct CreateSpendPermission<'a> { + pub struct CreateEvmSwapQuote<'a> { client: &'a super::Client, - address: Result, - x_idempotency_key: Result, String>, - x_wallet_auth: Result<::std::string::String, String>, - body: Result, + x_idempotency_key: Result, String>, + body: Result, } - impl<'a> CreateSpendPermission<'a> { + impl<'a> CreateEvmSwapQuote<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - address: Err("address was not initialized".to_string()), x_idempotency_key: Ok(None), - x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), body: Ok(::std::default::Default::default()), } } - pub fn address(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.address = value.try_into().map_err(|_| { - "conversion to `CreateSpendPermissionAddress` for address failed".to_string() - }); - self - } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `CreateSpendPermissionXIdempotencyKey` for x_idempotency_key failed" + "conversion to `CreateEvmSwapQuoteXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self } - pub fn x_wallet_auth(mut self, value: V) -> Self - where - V: std::convert::TryInto<::std::string::String>, - { - self.x_wallet_auth = value.try_into().map_err(|_| { - "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() - }); - self - } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: - std::fmt::Display, + V: std::convert::TryInto, + >::Error: std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `CreateSpendPermissionRequest` for body failed: {}", + "conversion to `CreateEvmSwapQuoteBody` for body failed: {}", s ) }); @@ -92882,37 +106924,28 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::CreateSpendPermissionRequest, - ) -> types::builder::CreateSpendPermissionRequest, + types::builder::CreateEvmSwapQuoteBody, + ) -> types::builder::CreateEvmSwapQuoteBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/evm/smart-accounts/{address}/spend-permissions` + ///Sends a `POST` request to `/v2/evm/swaps` pub async fn send( self, - ) -> Result, Error> { + ) -> Result, Error> + { let Self { client, - address, x_idempotency_key, - x_wallet_auth, body, } = self; - let address = address.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; - let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body - .and_then(|v| { - types::CreateSpendPermissionRequest::try_from(v).map_err(|e| e.to_string()) - }) + .and_then(|v| types::CreateEvmSwapQuoteBody::try_from(v).map_err(|e| e.to_string())) .map_err(Error::InvalidRequest)?; - let url = format!( - "{}/v2/evm/smart-accounts/{}/spend-permissions", - client.baseurl, - encode_path(&address.to_string()), - ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); + let url = format!("{}/v2/evm/swaps", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(2usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), @@ -92920,7 +106953,6 @@ pub mod builder { if let Some(value) = x_idempotency_key { header_map.append("X-Idempotency-Key", value.to_string().try_into()?); } - header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client @@ -92933,18 +106965,18 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "create_spend_permission", + operation_id: "create_evm_swap_quote", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 200u16 => ResponseValue::from_response::(response).await, + 201u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 404u16 => Err(Error::ErrorResponse( + 403u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 500u16 => Err(Error::ErrorResponse( @@ -92960,72 +106992,135 @@ pub mod builder { } } } - /**Builder for [`Client::list_spend_permissions`] + /**Builder for [`Client::get_evm_swap_price`] - [`Client::list_spend_permissions`]: super::Client::list_spend_permissions*/ + [`Client::get_evm_swap_price`]: super::Client::get_evm_swap_price*/ #[derive(Debug, Clone)] - pub struct ListSpendPermissions<'a> { + pub struct GetEvmSwapPrice<'a> { client: &'a super::Client, - address: Result, - page_size: Result, String>, - page_token: Result, String>, + from_amount: Result, + from_token: Result, + gas_price: Result, String>, + network: Result, + signer_address: Result, String>, + slippage_bps: Result, String>, + taker: Result, + to_token: Result, } - impl<'a> ListSpendPermissions<'a> { + impl<'a> GetEvmSwapPrice<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - address: Err("address was not initialized".to_string()), - page_size: Ok(None), - page_token: Ok(None), + from_amount: Err("from_amount was not initialized".to_string()), + from_token: Err("from_token was not initialized".to_string()), + gas_price: Ok(None), + network: Err("network was not initialized".to_string()), + signer_address: Ok(None), + slippage_bps: Ok(None), + taker: Err("taker was not initialized".to_string()), + to_token: Err("to_token was not initialized".to_string()), } } - pub fn address(mut self, value: V) -> Self + pub fn from_amount(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.address = value.try_into().map_err(|_| { - "conversion to `ListSpendPermissionsAddress` for address failed".to_string() - }); + self.from_amount = value + .try_into() + .map_err(|_| "conversion to `FromAmount` for from_amount failed".to_string()); self } - pub fn page_size(mut self, value: V) -> Self + pub fn from_token(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.page_size = value + self.from_token = value + .try_into() + .map_err(|_| "conversion to `FromToken` for from_token failed".to_string()); + self + } + pub fn gas_price(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.gas_price = value .try_into() .map(Some) - .map_err(|_| "conversion to `i64` for page_size failed".to_string()); + .map_err(|_| "conversion to `GasPrice` for gas_price failed".to_string()); self } - pub fn page_token(mut self, value: V) -> Self + pub fn network(mut self, value: V) -> Self where - V: std::convert::TryInto<::std::string::String>, + V: std::convert::TryInto, { - self.page_token = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: string :: String` for page_token failed".to_string() - }); + self.network = value + .try_into() + .map_err(|_| "conversion to `EvmSwapsNetwork` for network failed".to_string()); self } - ///Sends a `GET` request to `/v2/evm/smart-accounts/{address}/spend-permissions/list` + pub fn signer_address(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.signer_address = value + .try_into() + .map(Some) + .map_err(|_| "conversion to `SignerAddress` for signer_address failed".to_string()); + self + } + pub fn slippage_bps(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.slippage_bps = value + .try_into() + .map(Some) + .map_err(|_| "conversion to `SlippageBps` for slippage_bps failed".to_string()); + self + } + pub fn taker(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.taker = value + .try_into() + .map_err(|_| "conversion to `Taker` for taker failed".to_string()); + self + } + pub fn to_token(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.to_token = value + .try_into() + .map_err(|_| "conversion to `ToToken` for to_token failed".to_string()); + self + } + ///Sends a `GET` request to `/v2/evm/swaps/quote` pub async fn send( self, - ) -> Result, Error> + ) -> Result, Error> { let Self { client, - address, - page_size, - page_token, + from_amount, + from_token, + gas_price, + network, + signer_address, + slippage_bps, + taker, + to_token, } = self; - let address = address.map_err(Error::InvalidRequest)?; - let page_size = page_size.map_err(Error::InvalidRequest)?; - let page_token = page_token.map_err(Error::InvalidRequest)?; - let url = format!( - "{}/v2/evm/smart-accounts/{}/spend-permissions/list", - client.baseurl, - encode_path(&address.to_string()), - ); + let from_amount = from_amount.map_err(Error::InvalidRequest)?; + let from_token = from_token.map_err(Error::InvalidRequest)?; + let gas_price = gas_price.map_err(Error::InvalidRequest)?; + let network = network.map_err(Error::InvalidRequest)?; + let signer_address = signer_address.map_err(Error::InvalidRequest)?; + let slippage_bps = slippage_bps.map_err(Error::InvalidRequest)?; + let taker = taker.map_err(Error::InvalidRequest)?; + let to_token = to_token.map_err(Error::InvalidRequest)?; + let url = format!("{}/v2/evm/swaps/quote", client.baseurl,); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), @@ -93040,16 +107135,37 @@ pub mod builder { ::reqwest::header::HeaderValue::from_static("application/json"), ) .query(&progenitor_middleware_client::QueryParam::new( - "pageSize", &page_size, + "fromAmount", + &from_amount, )) .query(&progenitor_middleware_client::QueryParam::new( - "pageToken", - &page_token, + "fromToken", + &from_token, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "gasPrice", &gas_price, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "network", &network, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "signerAddress", + &signer_address, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "slippageBps", + &slippage_bps, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "taker", &taker, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "toToken", &to_token, )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "list_spend_permissions", + operation_id: "get_evm_swap_price", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -93060,7 +107176,7 @@ pub mod builder { 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 404u16 => Err(Error::ErrorResponse( + 403u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 500u16 => Err(Error::ErrorResponse( @@ -93076,124 +107192,110 @@ pub mod builder { } } } - /**Builder for [`Client::revoke_spend_permission`] + /**Builder for [`Client::list_evm_token_balances`] - [`Client::revoke_spend_permission`]: super::Client::revoke_spend_permission*/ + [`Client::list_evm_token_balances`]: super::Client::list_evm_token_balances*/ #[derive(Debug, Clone)] - pub struct RevokeSpendPermission<'a> { + pub struct ListEvmTokenBalances<'a> { client: &'a super::Client, - address: Result, - x_idempotency_key: Result, String>, - x_wallet_auth: Result<::std::string::String, String>, - body: Result, + network: Result, + address: Result, + page_size: Result, String>, + page_token: Result, String>, } - impl<'a> RevokeSpendPermission<'a> { + impl<'a> ListEvmTokenBalances<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, + network: Err("network was not initialized".to_string()), address: Err("address was not initialized".to_string()), - x_idempotency_key: Ok(None), - x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), - body: Ok(::std::default::Default::default()), + page_size: Ok(None), + page_token: Ok(None), } } - pub fn address(mut self, value: V) -> Self + pub fn network(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.address = value.try_into().map_err(|_| { - "conversion to `RevokeSpendPermissionAddress` for address failed".to_string() + self.network = value.try_into().map_err(|_| { + "conversion to `ListEvmTokenBalancesNetwork` for network failed".to_string() }); self } - pub fn x_idempotency_key(mut self, value: V) -> Self + pub fn address(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `RevokeSpendPermissionXIdempotencyKey` for x_idempotency_key failed" - .to_string() + self.address = value.try_into().map_err(|_| { + "conversion to `ListEvmTokenBalancesAddress` for address failed".to_string() }); self } - pub fn x_wallet_auth(mut self, value: V) -> Self + pub fn page_size(mut self, value: V) -> Self where - V: std::convert::TryInto<::std::string::String>, + V: std::convert::TryInto, { - self.x_wallet_auth = value.try_into().map_err(|_| { - "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() - }); + self.page_size = value + .try_into() + .map(Some) + .map_err(|_| "conversion to `i64` for page_size failed".to_string()); self } - pub fn body(mut self, value: V) -> Self + pub fn page_token(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: - std::fmt::Display, + V: std::convert::TryInto<::std::string::String>, { - self.body = value.try_into().map(From::from).map_err(|s| { - format!( - "conversion to `RevokeSpendPermissionRequest` for body failed: {}", - s - ) + self.page_token = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for page_token failed".to_string() }); self } - pub fn body_map(mut self, f: F) -> Self - where - F: std::ops::FnOnce( - types::builder::RevokeSpendPermissionRequest, - ) -> types::builder::RevokeSpendPermissionRequest, - { - self.body = self.body.map(f); - self - } - ///Sends a `POST` request to `/v2/evm/smart-accounts/{address}/spend-permissions/revoke` + ///Sends a `GET` request to `/v2/evm/token-balances/{network}/{address}` pub async fn send( self, - ) -> Result, Error> { + ) -> Result, Error> + { let Self { client, + network, address, - x_idempotency_key, - x_wallet_auth, - body, + page_size, + page_token, } = self; + let network = network.map_err(Error::InvalidRequest)?; let address = address.map_err(Error::InvalidRequest)?; - let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; - let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; - let body = body - .and_then(|v| { - types::RevokeSpendPermissionRequest::try_from(v).map_err(|e| e.to_string()) - }) - .map_err(Error::InvalidRequest)?; + let page_size = page_size.map_err(Error::InvalidRequest)?; + let page_token = page_token.map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/evm/smart-accounts/{}/spend-permissions/revoke", + "{}/v2/evm/token-balances/{}/{}", client.baseurl, + encode_path(&network.to_string()), encode_path(&address.to_string()), ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); - if let Some(value) = x_idempotency_key { - header_map.append("X-Idempotency-Key", value.to_string().try_into()?); - } - header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client - .post(url) + .get(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) - .json(&body) + .query(&progenitor_middleware_client::QueryParam::new( + "pageSize", &page_size, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "pageToken", + &page_token, + )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "revoke_spend_permission", + operation_id: "list_evm_token_balances", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -93220,40 +107322,29 @@ pub mod builder { } } } - /**Builder for [`Client::prepare_user_operation`] + /**Builder for [`Client::get_onramp_user_limits`] - [`Client::prepare_user_operation`]: super::Client::prepare_user_operation*/ + [`Client::get_onramp_user_limits`]: super::Client::get_onramp_user_limits*/ #[derive(Debug, Clone)] - pub struct PrepareUserOperation<'a> { + pub struct GetOnrampUserLimits<'a> { client: &'a super::Client, - address: Result, - body: Result, + body: Result, } - impl<'a> PrepareUserOperation<'a> { + impl<'a> GetOnrampUserLimits<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - address: Err("address was not initialized".to_string()), body: Ok(::std::default::Default::default()), } } - pub fn address(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.address = value.try_into().map_err(|_| { - "conversion to `PrepareUserOperationAddress` for address failed".to_string() - }); - self - } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto, + >::Error: std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `PrepareUserOperationBody` for body failed: {}", + "conversion to `GetOnrampUserLimitsBody` for body failed: {}", s ) }); @@ -93262,32 +107353,24 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::PrepareUserOperationBody, - ) -> types::builder::PrepareUserOperationBody, + types::builder::GetOnrampUserLimitsBody, + ) -> types::builder::GetOnrampUserLimitsBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/evm/smart-accounts/{address}/user-operations` + ///Sends a `POST` request to `/v2/onramp/limits` pub async fn send( self, - ) -> Result, Error> { - let Self { - client, - address, - body, - } = self; - let address = address.map_err(Error::InvalidRequest)?; + ) -> Result, Error> + { + let Self { client, body } = self; let body = body .and_then(|v| { - types::PrepareUserOperationBody::try_from(v).map_err(|e| e.to_string()) + types::GetOnrampUserLimitsBody::try_from(v).map_err(|e| e.to_string()) }) .map_err(Error::InvalidRequest)?; - let url = format!( - "{}/v2/evm/smart-accounts/{}/user-operations", - client.baseurl, - encode_path(&address.to_string()), - ); + let url = format!("{}/v2/onramp/limits", client.baseurl,); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), @@ -93305,98 +107388,54 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "prepare_user_operation", + operation_id: "get_onramp_user_limits", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 201u16 => ResponseValue::from_response::(response).await, + 200u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 403u16 => Err(Error::ErrorResponse( + 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 404u16 => Err(Error::ErrorResponse( + 429u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 502u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 503u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), _ => Err(Error::UnexpectedResponse(response)), } } - } - /**Builder for [`Client::prepare_and_send_user_operation`] - - [`Client::prepare_and_send_user_operation`]: super::Client::prepare_and_send_user_operation*/ - #[derive(Debug, Clone)] - pub struct PrepareAndSendUserOperation<'a> { - client: &'a super::Client, - address: Result, - x_idempotency_key: - Result, String>, - x_wallet_auth: Result<::std::string::String, String>, - body: Result, - } - impl<'a> PrepareAndSendUserOperation<'a> { - pub fn new(client: &'a super::Client) -> Self { - Self { - client: client, - address: Err("address was not initialized".to_string()), - x_idempotency_key: Ok(None), - x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), - body: Ok(::std::default::Default::default()), - } - } - pub fn address(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.address = value.try_into().map_err(|_| { - "conversion to `PrepareAndSendUserOperationAddress` for address failed".to_string() - }); - self - } - pub fn x_idempotency_key(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.x_idempotency_key = value - .try_into() - .map(Some) - .map_err(|_| { - "conversion to `PrepareAndSendUserOperationXIdempotencyKey` for x_idempotency_key failed" - .to_string() - }); - self - } - pub fn x_wallet_auth(mut self, value: V) -> Self - where - V: std::convert::TryInto<::std::string::String>, - { - self.x_wallet_auth = value.try_into().map_err(|_| { - "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() - }); - self - } + } + /**Builder for [`Client::request_limits_upgrade`] + + [`Client::request_limits_upgrade`]: super::Client::request_limits_upgrade*/ + #[derive(Debug, Clone)] + pub struct RequestLimitsUpgrade<'a> { + client: &'a super::Client, + body: Result, + } + impl<'a> RequestLimitsUpgrade<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + body: Ok(::std::default::Default::default()), + } + } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: + V: std::convert::TryInto, + >::Error: std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `PrepareAndSendUserOperationBody` for body failed: {}", + "conversion to `OnrampLimitUpgradeRequest` for body failed: {}", s ) }); @@ -93405,45 +107444,26 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::PrepareAndSendUserOperationBody, - ) -> types::builder::PrepareAndSendUserOperationBody, + types::builder::OnrampLimitUpgradeRequest, + ) -> types::builder::OnrampLimitUpgradeRequest, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/evm/smart-accounts/{address}/user-operations/prepare-and-send` - pub async fn send( - self, - ) -> Result, Error> { - let Self { - client, - address, - x_idempotency_key, - x_wallet_auth, - body, - } = self; - let address = address.map_err(Error::InvalidRequest)?; - let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; - let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; + ///Sends a `POST` request to `/v2/onramp/limits/upgrade` + pub async fn send(self) -> Result, Error> { + let Self { client, body } = self; let body = body .and_then(|v| { - types::PrepareAndSendUserOperationBody::try_from(v).map_err(|e| e.to_string()) + types::OnrampLimitUpgradeRequest::try_from(v).map_err(|e| e.to_string()) }) .map_err(Error::InvalidRequest)?; - let url = format!( - "{}/v2/evm/smart-accounts/{}/user-operations/prepare-and-send", - client.baseurl, - encode_path(&address.to_string()), - ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); + let url = format!("{}/v2/onramp/limits/upgrade", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); - if let Some(value) = x_idempotency_key { - header_map.append("X-Idempotency-Key", value.to_string().try_into()?); - } - header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client @@ -93456,97 +107476,76 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "prepare_and_send_user_operation", + operation_id: "request_limits_upgrade", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 200u16 => ResponseValue::from_response::(response).await, + 202u16 => Ok(ResponseValue::empty(response)), 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 402u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 403u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 404u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 429u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 502u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 503u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::get_user_operation`] + /**Builder for [`Client::create_onramp_order`] - [`Client::get_user_operation`]: super::Client::get_user_operation*/ + [`Client::create_onramp_order`]: super::Client::create_onramp_order*/ #[derive(Debug, Clone)] - pub struct GetUserOperation<'a> { + pub struct CreateOnrampOrder<'a> { client: &'a super::Client, - address: Result, - user_op_hash: Result, + body: Result, } - impl<'a> GetUserOperation<'a> { + impl<'a> CreateOnrampOrder<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - address: Err("address was not initialized".to_string()), - user_op_hash: Err("user_op_hash was not initialized".to_string()), + body: Ok(::std::default::Default::default()), } } - pub fn address(mut self, value: V) -> Self + pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, + >::Error: std::fmt::Display, { - self.address = value.try_into().map_err(|_| { - "conversion to `GetUserOperationAddress` for address failed".to_string() + self.body = value.try_into().map(From::from).map_err(|s| { + format!( + "conversion to `CreateOnrampOrderBody` for body failed: {}", + s + ) }); self } - pub fn user_op_hash(mut self, value: V) -> Self + pub fn body_map(mut self, f: F) -> Self where - V: std::convert::TryInto, + F: std::ops::FnOnce( + types::builder::CreateOnrampOrderBody, + ) -> types::builder::CreateOnrampOrderBody, { - self.user_op_hash = value.try_into().map_err(|_| { - "conversion to `GetUserOperationUserOpHash` for user_op_hash failed".to_string() - }); + self.body = self.body.map(f); self } - ///Sends a `GET` request to `/v2/evm/smart-accounts/{address}/user-operations/{userOpHash}` + ///Sends a `POST` request to `/v2/onramp/orders` pub async fn send( self, - ) -> Result, Error> { - let Self { - client, - address, - user_op_hash, - } = self; - let address = address.map_err(Error::InvalidRequest)?; - let user_op_hash = user_op_hash.map_err(Error::InvalidRequest)?; - let url = format!( - "{}/v2/evm/smart-accounts/{}/user-operations/{}", - client.baseurl, - encode_path(&address.to_string()), - encode_path(&user_op_hash.to_string()), - ); + ) -> Result, Error> { + let Self { client, body } = self; + let body = body + .and_then(|v| types::CreateOnrampOrderBody::try_from(v).map_err(|e| e.to_string())) + .map_err(Error::InvalidRequest)?; + let url = format!("{}/v2/onramp/orders", client.baseurl,); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), @@ -93555,120 +107554,73 @@ pub mod builder { #[allow(unused_mut)] let mut request = client .client - .get(url) + .post(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) + .json(&body) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "get_user_operation", + operation_id: "create_onramp_order", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 200u16 => ResponseValue::from_response::(response).await, + 201u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 404u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 500u16 => Err(Error::ErrorResponse( + 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 502u16 => Err(Error::ErrorResponse( + 429u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 503u16 => Err(Error::ErrorResponse( + 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::send_user_operation`] + /**Builder for [`Client::get_onramp_order_by_id`] - [`Client::send_user_operation`]: super::Client::send_user_operation*/ + [`Client::get_onramp_order_by_id`]: super::Client::get_onramp_order_by_id*/ #[derive(Debug, Clone)] - pub struct SendUserOperation<'a> { + pub struct GetOnrampOrderById<'a> { client: &'a super::Client, - address: Result, - user_op_hash: Result, - body: Result, + order_id: Result<::std::string::String, String>, } - impl<'a> SendUserOperation<'a> { + impl<'a> GetOnrampOrderById<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - address: Err("address was not initialized".to_string()), - user_op_hash: Err("user_op_hash was not initialized".to_string()), - body: Ok(::std::default::Default::default()), + order_id: Err("order_id was not initialized".to_string()), } } - pub fn address(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.address = value.try_into().map_err(|_| { - "conversion to `SendUserOperationAddress` for address failed".to_string() - }); - self - } - pub fn user_op_hash(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.user_op_hash = value.try_into().map_err(|_| { - "conversion to `SendUserOperationUserOpHash` for user_op_hash failed".to_string() - }); - self - } - pub fn body(mut self, value: V) -> Self + pub fn order_id(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto<::std::string::String>, { - self.body = value.try_into().map(From::from).map_err(|s| { - format!( - "conversion to `SendUserOperationBody` for body failed: {}", - s - ) + self.order_id = value.try_into().map_err(|_| { + "conversion to `:: std :: string :: String` for order_id failed".to_string() }); self } - pub fn body_map(mut self, f: F) -> Self - where - F: std::ops::FnOnce( - types::builder::SendUserOperationBody, - ) -> types::builder::SendUserOperationBody, - { - self.body = self.body.map(f); - self - } - ///Sends a `POST` request to `/v2/evm/smart-accounts/{address}/user-operations/{userOpHash}/send` + ///Sends a `GET` request to `/v2/onramp/orders/{orderId}` pub async fn send( self, - ) -> Result, Error> { - let Self { - client, - address, - user_op_hash, - body, - } = self; - let address = address.map_err(Error::InvalidRequest)?; - let user_op_hash = user_op_hash.map_err(Error::InvalidRequest)?; - let body = body - .and_then(|v| types::SendUserOperationBody::try_from(v).map_err(|e| e.to_string())) - .map_err(Error::InvalidRequest)?; + ) -> Result, Error> { + let Self { client, order_id } = self; + let order_id = order_id.map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/evm/smart-accounts/{}/user-operations/{}/send", + "{}/v2/onramp/orders/{}", client.baseurl, - encode_path(&address.to_string()), - encode_path(&user_op_hash.to_string()), + encode_path(&order_id.to_string()), ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( @@ -93678,16 +107630,15 @@ pub mod builder { #[allow(unused_mut)] let mut request = client .client - .post(url) + .get(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) - .json(&body) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "send_user_operation", + operation_id: "get_onramp_order_by_id", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -93695,13 +107646,7 @@ pub mod builder { let response = result?; match response.status().as_u16() { 200u16 => ResponseValue::from_response::(response).await, - 400u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 402u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 403u16 => Err(Error::ErrorResponse( + 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 404u16 => Err(Error::ErrorResponse( @@ -93710,54 +107655,33 @@ pub mod builder { 429u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 500u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 502u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 503u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::create_evm_swap_quote`] + /**Builder for [`Client::create_onramp_session`] - [`Client::create_evm_swap_quote`]: super::Client::create_evm_swap_quote*/ + [`Client::create_onramp_session`]: super::Client::create_onramp_session*/ #[derive(Debug, Clone)] - pub struct CreateEvmSwapQuote<'a> { + pub struct CreateOnrampSession<'a> { client: &'a super::Client, - x_idempotency_key: Result, String>, - body: Result, + body: Result, } - impl<'a> CreateEvmSwapQuote<'a> { + impl<'a> CreateOnrampSession<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - x_idempotency_key: Ok(None), body: Ok(::std::default::Default::default()), } } - pub fn x_idempotency_key(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `CreateEvmSwapQuoteXIdempotencyKey` for x_idempotency_key failed" - .to_string() - }); - self - } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto, + >::Error: std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `CreateEvmSwapQuoteBody` for body failed: {}", + "conversion to `CreateOnrampSessionBody` for body failed: {}", s ) }); @@ -93766,35 +107690,29 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::CreateEvmSwapQuoteBody, - ) -> types::builder::CreateEvmSwapQuoteBody, + types::builder::CreateOnrampSessionBody, + ) -> types::builder::CreateOnrampSessionBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/evm/swaps` + ///Sends a `POST` request to `/v2/onramp/sessions` pub async fn send( self, - ) -> Result, Error> + ) -> Result, Error> { - let Self { - client, - x_idempotency_key, - body, - } = self; - let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; + let Self { client, body } = self; let body = body - .and_then(|v| types::CreateEvmSwapQuoteBody::try_from(v).map_err(|e| e.to_string())) + .and_then(|v| { + types::CreateOnrampSessionBody::try_from(v).map_err(|e| e.to_string()) + }) .map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/evm/swaps", client.baseurl,); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(2usize); + let url = format!("{}/v2/onramp/sessions", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); - if let Some(value) = x_idempotency_key { - header_map.append("X-Idempotency-Key", value.to_string().try_into()?); - } #[allow(unused_mut)] let mut request = client .client @@ -93807,7 +107725,7 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "create_evm_swap_quote", + operation_id: "create_onramp_session", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -93818,151 +107736,67 @@ pub mod builder { 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 403u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 500u16 => Err(Error::ErrorResponse( + 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 502u16 => Err(Error::ErrorResponse( + 429u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 503u16 => Err(Error::ErrorResponse( + 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::get_evm_swap_price`] + /**Builder for [`Client::list_payment_methods`] - [`Client::get_evm_swap_price`]: super::Client::get_evm_swap_price*/ + [`Client::list_payment_methods`]: super::Client::list_payment_methods*/ #[derive(Debug, Clone)] - pub struct GetEvmSwapPrice<'a> { + pub struct ListPaymentMethods<'a> { client: &'a super::Client, - from_amount: Result, - from_token: Result, - gas_price: Result, String>, - network: Result, - signer_address: Result, String>, - slippage_bps: Result, String>, - taker: Result, - to_token: Result, + page_size: Result, String>, + page_token: Result, String>, } - impl<'a> GetEvmSwapPrice<'a> { + impl<'a> ListPaymentMethods<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - from_amount: Err("from_amount was not initialized".to_string()), - from_token: Err("from_token was not initialized".to_string()), - gas_price: Ok(None), - network: Err("network was not initialized".to_string()), - signer_address: Ok(None), - slippage_bps: Ok(None), - taker: Err("taker was not initialized".to_string()), - to_token: Err("to_token was not initialized".to_string()), + page_size: Ok(None), + page_token: Ok(None), } } - pub fn from_amount(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.from_amount = value - .try_into() - .map_err(|_| "conversion to `FromAmount` for from_amount failed".to_string()); - self - } - pub fn from_token(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.from_token = value - .try_into() - .map_err(|_| "conversion to `FromToken` for from_token failed".to_string()); - self - } - pub fn gas_price(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.gas_price = value - .try_into() - .map(Some) - .map_err(|_| "conversion to `GasPrice` for gas_price failed".to_string()); - self - } - pub fn network(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.network = value - .try_into() - .map_err(|_| "conversion to `EvmSwapsNetwork` for network failed".to_string()); - self - } - pub fn signer_address(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.signer_address = value - .try_into() - .map(Some) - .map_err(|_| "conversion to `SignerAddress` for signer_address failed".to_string()); - self - } - pub fn slippage_bps(mut self, value: V) -> Self + pub fn page_size(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.slippage_bps = value + self.page_size = value .try_into() .map(Some) - .map_err(|_| "conversion to `SlippageBps` for slippage_bps failed".to_string()); - self - } - pub fn taker(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.taker = value - .try_into() - .map_err(|_| "conversion to `Taker` for taker failed".to_string()); + .map_err(|_| "conversion to `i64` for page_size failed".to_string()); self } - pub fn to_token(mut self, value: V) -> Self + pub fn page_token(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto<::std::string::String>, { - self.to_token = value - .try_into() - .map_err(|_| "conversion to `ToToken` for to_token failed".to_string()); + self.page_token = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for page_token failed".to_string() + }); self } - ///Sends a `GET` request to `/v2/evm/swaps/quote` + ///Sends a `GET` request to `/v2/payment-methods` pub async fn send( self, - ) -> Result, Error> - { + ) -> Result, Error> { let Self { client, - from_amount, - from_token, - gas_price, - network, - signer_address, - slippage_bps, - taker, - to_token, + page_size, + page_token, } = self; - let from_amount = from_amount.map_err(Error::InvalidRequest)?; - let from_token = from_token.map_err(Error::InvalidRequest)?; - let gas_price = gas_price.map_err(Error::InvalidRequest)?; - let network = network.map_err(Error::InvalidRequest)?; - let signer_address = signer_address.map_err(Error::InvalidRequest)?; - let slippage_bps = slippage_bps.map_err(Error::InvalidRequest)?; - let taker = taker.map_err(Error::InvalidRequest)?; - let to_token = to_token.map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/evm/swaps/quote", client.baseurl,); + let page_size = page_size.map_err(Error::InvalidRequest)?; + let page_token = page_token.map_err(Error::InvalidRequest)?; + let url = format!("{}/v2/payment-methods", client.baseurl,); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), @@ -93977,37 +107811,16 @@ pub mod builder { ::reqwest::header::HeaderValue::from_static("application/json"), ) .query(&progenitor_middleware_client::QueryParam::new( - "fromAmount", - &from_amount, - )) - .query(&progenitor_middleware_client::QueryParam::new( - "fromToken", - &from_token, - )) - .query(&progenitor_middleware_client::QueryParam::new( - "gasPrice", &gas_price, - )) - .query(&progenitor_middleware_client::QueryParam::new( - "network", &network, - )) - .query(&progenitor_middleware_client::QueryParam::new( - "signerAddress", - &signer_address, - )) - .query(&progenitor_middleware_client::QueryParam::new( - "slippageBps", - &slippage_bps, - )) - .query(&progenitor_middleware_client::QueryParam::new( - "taker", &taker, + "pageSize", &page_size, )) .query(&progenitor_middleware_client::QueryParam::new( - "toToken", &to_token, + "pageToken", + &page_token, )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "get_evm_swap_price", + operation_id: "list_payment_methods", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -94018,101 +107831,54 @@ pub mod builder { 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 403u16 => Err(Error::ErrorResponse( + 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 502u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 503u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::list_evm_token_balances`] + /**Builder for [`Client::get_payment_method`] - [`Client::list_evm_token_balances`]: super::Client::list_evm_token_balances*/ + [`Client::get_payment_method`]: super::Client::get_payment_method*/ #[derive(Debug, Clone)] - pub struct ListEvmTokenBalances<'a> { + pub struct GetPaymentMethod<'a> { client: &'a super::Client, - network: Result, - address: Result, - page_size: Result, String>, - page_token: Result, String>, + payment_method_id: Result, } - impl<'a> ListEvmTokenBalances<'a> { + impl<'a> GetPaymentMethod<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - network: Err("network was not initialized".to_string()), - address: Err("address was not initialized".to_string()), - page_size: Ok(None), - page_token: Ok(None), + payment_method_id: Err("payment_method_id was not initialized".to_string()), } } - pub fn network(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.network = value.try_into().map_err(|_| { - "conversion to `ListEvmTokenBalancesNetwork` for network failed".to_string() - }); - self - } - pub fn address(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.address = value.try_into().map_err(|_| { - "conversion to `ListEvmTokenBalancesAddress` for address failed".to_string() - }); - self - } - pub fn page_size(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.page_size = value - .try_into() - .map(Some) - .map_err(|_| "conversion to `i64` for page_size failed".to_string()); - self - } - pub fn page_token(mut self, value: V) -> Self + pub fn payment_method_id(mut self, value: V) -> Self where - V: std::convert::TryInto<::std::string::String>, + V: std::convert::TryInto, { - self.page_token = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: string :: String` for page_token failed".to_string() + self.payment_method_id = value.try_into().map_err(|_| { + "conversion to `PaymentMethodId` for payment_method_id failed".to_string() }); self } - ///Sends a `GET` request to `/v2/evm/token-balances/{network}/{address}` + ///Sends a `GET` request to `/v2/payment-methods/{paymentMethodId}` pub async fn send( self, - ) -> Result, Error> + ) -> Result, Error> { let Self { client, - network, - address, - page_size, - page_token, + payment_method_id, } = self; - let network = network.map_err(Error::InvalidRequest)?; - let address = address.map_err(Error::InvalidRequest)?; - let page_size = page_size.map_err(Error::InvalidRequest)?; - let page_token = page_token.map_err(Error::InvalidRequest)?; + let payment_method_id = payment_method_id.map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/evm/token-balances/{}/{}", + "{}/v2/payment-methods/{}", client.baseurl, - encode_path(&network.to_string()), - encode_path(&address.to_string()), + encode_path(&payment_method_id.to_string()), ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( @@ -94127,17 +107893,10 @@ pub mod builder { ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) - .query(&progenitor_middleware_client::QueryParam::new( - "pageSize", &page_size, - )) - .query(&progenitor_middleware_client::QueryParam::new( - "pageToken", - &page_token, - )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "list_evm_token_balances", + operation_id: "get_payment_method", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -94148,71 +107907,81 @@ pub mod builder { 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 404u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 500u16 => Err(Error::ErrorResponse( + 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 502u16 => Err(Error::ErrorResponse( + 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 503u16 => Err(Error::ErrorResponse( + 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::get_onramp_user_limits`] + /**Builder for [`Client::list_policies`] - [`Client::get_onramp_user_limits`]: super::Client::get_onramp_user_limits*/ + [`Client::list_policies`]: super::Client::list_policies*/ #[derive(Debug, Clone)] - pub struct GetOnrampUserLimits<'a> { + pub struct ListPolicies<'a> { client: &'a super::Client, - body: Result, + page_size: Result, String>, + page_token: Result, String>, + scope: Result, String>, } - impl<'a> GetOnrampUserLimits<'a> { + impl<'a> ListPolicies<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - body: Ok(::std::default::Default::default()), + page_size: Ok(None), + page_token: Ok(None), + scope: Ok(None), } } - pub fn body(mut self, value: V) -> Self + pub fn page_size(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto, { - self.body = value.try_into().map(From::from).map_err(|s| { - format!( - "conversion to `GetOnrampUserLimitsBody` for body failed: {}", - s - ) + self.page_size = value + .try_into() + .map(Some) + .map_err(|_| "conversion to `i64` for page_size failed".to_string()); + self + } + pub fn page_token(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.page_token = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for page_token failed".to_string() }); self } - pub fn body_map(mut self, f: F) -> Self + pub fn scope(mut self, value: V) -> Self where - F: std::ops::FnOnce( - types::builder::GetOnrampUserLimitsBody, - ) -> types::builder::GetOnrampUserLimitsBody, + V: std::convert::TryInto, { - self.body = self.body.map(f); + self.scope = value + .try_into() + .map(Some) + .map_err(|_| "conversion to `ListPoliciesScope` for scope failed".to_string()); self } - ///Sends a `POST` request to `/v2/onramp/limits` + ///Sends a `GET` request to `/v2/policy-engine/policies` pub async fn send( self, - ) -> Result, Error> - { - let Self { client, body } = self; - let body = body - .and_then(|v| { - types::GetOnrampUserLimitsBody::try_from(v).map_err(|e| e.to_string()) - }) - .map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/onramp/limits", client.baseurl,); + ) -> Result, Error> { + let Self { + client, + page_size, + page_token, + scope, + } = self; + let page_size = page_size.map_err(Error::InvalidRequest)?; + let page_token = page_token.map_err(Error::InvalidRequest)?; + let scope = scope.map_err(Error::InvalidRequest)?; + let url = format!("{}/v2/policy-engine/policies", client.baseurl,); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), @@ -94221,16 +107990,25 @@ pub mod builder { #[allow(unused_mut)] let mut request = client .client - .post(url) + .get(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) - .json(&body) + .query(&progenitor_middleware_client::QueryParam::new( + "pageSize", &page_size, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "pageToken", + &page_token, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "scope", &scope, + )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "get_onramp_user_limits", + operation_id: "list_policies", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -94238,74 +108016,86 @@ pub mod builder { let response = result?; match response.status().as_u16() { 200u16 => ResponseValue::from_response::(response).await, - 400u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 401u16 => Err(Error::ErrorResponse( + 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 429u16 => Err(Error::ErrorResponse( + 502u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 500u16 => Err(Error::ErrorResponse( + 503u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::request_limits_upgrade`] + /**Builder for [`Client::create_policy`] - [`Client::request_limits_upgrade`]: super::Client::request_limits_upgrade*/ + [`Client::create_policy`]: super::Client::create_policy*/ #[derive(Debug, Clone)] - pub struct RequestLimitsUpgrade<'a> { + pub struct CreatePolicy<'a> { client: &'a super::Client, - body: Result, + x_idempotency_key: Result, String>, + body: Result, } - impl<'a> RequestLimitsUpgrade<'a> { + impl<'a> CreatePolicy<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, + x_idempotency_key: Ok(None), body: Ok(::std::default::Default::default()), } } - pub fn body(mut self, value: V) -> Self + pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: - std::fmt::Display, + V: std::convert::TryInto, { - self.body = value.try_into().map(From::from).map_err(|s| { - format!( - "conversion to `OnrampLimitUpgradeRequest` for body failed: {}", - s - ) + self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { + "conversion to `CreatePolicyXIdempotencyKey` for x_idempotency_key failed" + .to_string() }); self } + pub fn body(mut self, value: V) -> Self + where + V: std::convert::TryInto, + >::Error: std::fmt::Display, + { + self.body = value + .try_into() + .map(From::from) + .map_err(|s| format!("conversion to `CreatePolicyBody` for body failed: {}", s)); + self + } pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::OnrampLimitUpgradeRequest, - ) -> types::builder::OnrampLimitUpgradeRequest, + types::builder::CreatePolicyBody, + ) -> types::builder::CreatePolicyBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/onramp/limits/upgrade` - pub async fn send(self) -> Result, Error> { - let Self { client, body } = self; + ///Sends a `POST` request to `/v2/policy-engine/policies` + pub async fn send(self) -> Result, Error> { + let Self { + client, + x_idempotency_key, + body, + } = self; + let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; let body = body - .and_then(|v| { - types::OnrampLimitUpgradeRequest::try_from(v).map_err(|e| e.to_string()) - }) + .and_then(|v| types::CreatePolicyBody::try_from(v).map_err(|e| e.to_string())) .map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/onramp/limits/upgrade", client.baseurl,); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + let url = format!("{}/v2/policy-engine/policies", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(2usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); + if let Some(value) = x_idempotency_key { + header_map.append("X-Idempotency-Key", value.to_string().try_into()?); + } #[allow(unused_mut)] let mut request = client .client @@ -94318,76 +108108,69 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "request_limits_upgrade", + operation_id: "create_policy", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 202u16 => Ok(ResponseValue::empty(response)), + 201u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 401u16 => Err(Error::ErrorResponse( + 409u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 429u16 => Err(Error::ErrorResponse( + 422u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 502u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 503u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::create_onramp_order`] + /**Builder for [`Client::get_policy_by_id`] - [`Client::create_onramp_order`]: super::Client::create_onramp_order*/ + [`Client::get_policy_by_id`]: super::Client::get_policy_by_id*/ #[derive(Debug, Clone)] - pub struct CreateOnrampOrder<'a> { + pub struct GetPolicyById<'a> { client: &'a super::Client, - body: Result, + policy_id: Result, } - impl<'a> CreateOnrampOrder<'a> { + impl<'a> GetPolicyById<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - body: Ok(::std::default::Default::default()), + policy_id: Err("policy_id was not initialized".to_string()), } } - pub fn body(mut self, value: V) -> Self + pub fn policy_id(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto, { - self.body = value.try_into().map(From::from).map_err(|s| { - format!( - "conversion to `CreateOnrampOrderBody` for body failed: {}", - s - ) + self.policy_id = value.try_into().map_err(|_| { + "conversion to `GetPolicyByIdPolicyId` for policy_id failed".to_string() }); self } - pub fn body_map(mut self, f: F) -> Self - where - F: std::ops::FnOnce( - types::builder::CreateOnrampOrderBody, - ) -> types::builder::CreateOnrampOrderBody, - { - self.body = self.body.map(f); - self - } - ///Sends a `POST` request to `/v2/onramp/orders` - pub async fn send( - self, - ) -> Result, Error> { - let Self { client, body } = self; - let body = body - .and_then(|v| types::CreateOnrampOrderBody::try_from(v).map_err(|e| e.to_string())) - .map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/onramp/orders", client.baseurl,); + ///Sends a `GET` request to `/v2/policy-engine/policies/{policyId}` + pub async fn send(self) -> Result, Error> { + let Self { client, policy_id } = self; + let policy_id = policy_id.map_err(Error::InvalidRequest)?; + let url = format!( + "{}/v2/policy-engine/policies/{}", + client.baseurl, + encode_path(&policy_id.to_string()), + ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), @@ -94396,91 +108179,135 @@ pub mod builder { #[allow(unused_mut)] let mut request = client .client - .post(url) + .get(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) - .json(&body) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "create_onramp_order", + operation_id: "get_policy_by_id", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 201u16 => ResponseValue::from_response::(response).await, - 400u16 => Err(Error::ErrorResponse( + 200u16 => ResponseValue::from_response::(response).await, + 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 401u16 => Err(Error::ErrorResponse( + 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 429u16 => Err(Error::ErrorResponse( + 502u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 500u16 => Err(Error::ErrorResponse( + 503u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::get_onramp_order_by_id`] + /**Builder for [`Client::update_policy`] - [`Client::get_onramp_order_by_id`]: super::Client::get_onramp_order_by_id*/ + [`Client::update_policy`]: super::Client::update_policy*/ #[derive(Debug, Clone)] - pub struct GetOnrampOrderById<'a> { + pub struct UpdatePolicy<'a> { client: &'a super::Client, - order_id: Result<::std::string::String, String>, + policy_id: Result, + x_idempotency_key: Result, String>, + body: Result, } - impl<'a> GetOnrampOrderById<'a> { + impl<'a> UpdatePolicy<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - order_id: Err("order_id was not initialized".to_string()), + policy_id: Err("policy_id was not initialized".to_string()), + x_idempotency_key: Ok(None), + body: Ok(::std::default::Default::default()), } } - pub fn order_id(mut self, value: V) -> Self + pub fn policy_id(mut self, value: V) -> Self where - V: std::convert::TryInto<::std::string::String>, + V: std::convert::TryInto, { - self.order_id = value.try_into().map_err(|_| { - "conversion to `:: std :: string :: String` for order_id failed".to_string() + self.policy_id = value.try_into().map_err(|_| { + "conversion to `UpdatePolicyPolicyId` for policy_id failed".to_string() }); self } - ///Sends a `GET` request to `/v2/onramp/orders/{orderId}` - pub async fn send( - self, - ) -> Result, Error> { - let Self { client, order_id } = self; - let order_id = order_id.map_err(Error::InvalidRequest)?; + pub fn x_idempotency_key(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { + "conversion to `UpdatePolicyXIdempotencyKey` for x_idempotency_key failed" + .to_string() + }); + self + } + pub fn body(mut self, value: V) -> Self + where + V: std::convert::TryInto, + >::Error: std::fmt::Display, + { + self.body = value + .try_into() + .map(From::from) + .map_err(|s| format!("conversion to `UpdatePolicyBody` for body failed: {}", s)); + self + } + pub fn body_map(mut self, f: F) -> Self + where + F: std::ops::FnOnce( + types::builder::UpdatePolicyBody, + ) -> types::builder::UpdatePolicyBody, + { + self.body = self.body.map(f); + self + } + ///Sends a `PUT` request to `/v2/policy-engine/policies/{policyId}` + pub async fn send(self) -> Result, Error> { + let Self { + client, + policy_id, + x_idempotency_key, + body, + } = self; + let policy_id = policy_id.map_err(Error::InvalidRequest)?; + let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; + let body = body + .and_then(|v| types::UpdatePolicyBody::try_from(v).map_err(|e| e.to_string())) + .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/onramp/orders/{}", + "{}/v2/policy-engine/policies/{}", client.baseurl, - encode_path(&order_id.to_string()), + encode_path(&policy_id.to_string()), ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(2usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); + if let Some(value) = x_idempotency_key { + header_map.append("X-Idempotency-Key", value.to_string().try_into()?); + } #[allow(unused_mut)] let mut request = client .client - .get(url) + .put(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) + .json(&body) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "get_onramp_order_by_id", + operation_id: "update_policy", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -94488,126 +108315,148 @@ pub mod builder { let response = result?; match response.status().as_u16() { 200u16 => ResponseValue::from_response::(response).await, - 401u16 => Err(Error::ErrorResponse( + 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 429u16 => Err(Error::ErrorResponse( + 409u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 422u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 500u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 502u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 503u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::create_onramp_session`] + /**Builder for [`Client::delete_policy`] - [`Client::create_onramp_session`]: super::Client::create_onramp_session*/ + [`Client::delete_policy`]: super::Client::delete_policy*/ #[derive(Debug, Clone)] - pub struct CreateOnrampSession<'a> { + pub struct DeletePolicy<'a> { client: &'a super::Client, - body: Result, + policy_id: Result, + x_idempotency_key: Result, String>, } - impl<'a> CreateOnrampSession<'a> { + impl<'a> DeletePolicy<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - body: Ok(::std::default::Default::default()), + policy_id: Err("policy_id was not initialized".to_string()), + x_idempotency_key: Ok(None), } } - pub fn body(mut self, value: V) -> Self + pub fn policy_id(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto, { - self.body = value.try_into().map(From::from).map_err(|s| { - format!( - "conversion to `CreateOnrampSessionBody` for body failed: {}", - s - ) + self.policy_id = value.try_into().map_err(|_| { + "conversion to `DeletePolicyPolicyId` for policy_id failed".to_string() }); self } - pub fn body_map(mut self, f: F) -> Self + pub fn x_idempotency_key(mut self, value: V) -> Self where - F: std::ops::FnOnce( - types::builder::CreateOnrampSessionBody, - ) -> types::builder::CreateOnrampSessionBody, + V: std::convert::TryInto, { - self.body = self.body.map(f); + self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { + "conversion to `DeletePolicyXIdempotencyKey` for x_idempotency_key failed" + .to_string() + }); self } - ///Sends a `POST` request to `/v2/onramp/sessions` - pub async fn send( - self, - ) -> Result, Error> - { - let Self { client, body } = self; - let body = body - .and_then(|v| { - types::CreateOnrampSessionBody::try_from(v).map_err(|e| e.to_string()) - }) - .map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/onramp/sessions", client.baseurl,); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + ///Sends a `DELETE` request to `/v2/policy-engine/policies/{policyId}` + pub async fn send(self) -> Result, Error> { + let Self { + client, + policy_id, + x_idempotency_key, + } = self; + let policy_id = policy_id.map_err(Error::InvalidRequest)?; + let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; + let url = format!( + "{}/v2/policy-engine/policies/{}", + client.baseurl, + encode_path(&policy_id.to_string()), + ); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(2usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); + if let Some(value) = x_idempotency_key { + header_map.append("X-Idempotency-Key", value.to_string().try_into()?); + } #[allow(unused_mut)] let mut request = client .client - .post(url) + .delete(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) - .json(&body) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "create_onramp_session", + operation_id: "delete_policy", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 201u16 => ResponseValue::from_response::(response).await, + 204u16 => Ok(ResponseValue::empty(response)), 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 401u16 => Err(Error::ErrorResponse( + 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 429u16 => Err(Error::ErrorResponse( + 409u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 422u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 502u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 503u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::list_policies`] + /**Builder for [`Client::list_solana_accounts`] - [`Client::list_policies`]: super::Client::list_policies*/ + [`Client::list_solana_accounts`]: super::Client::list_solana_accounts*/ #[derive(Debug, Clone)] - pub struct ListPolicies<'a> { + pub struct ListSolanaAccounts<'a> { client: &'a super::Client, page_size: Result, String>, page_token: Result, String>, - scope: Result, String>, } - impl<'a> ListPolicies<'a> { + impl<'a> ListSolanaAccounts<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, page_size: Ok(None), page_token: Ok(None), - scope: Ok(None), } } pub fn page_size(mut self, value: V) -> Self @@ -94629,30 +108478,18 @@ pub mod builder { }); self } - pub fn scope(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.scope = value - .try_into() - .map(Some) - .map_err(|_| "conversion to `ListPoliciesScope` for scope failed".to_string()); - self - } - ///Sends a `GET` request to `/v2/policy-engine/policies` + ///Sends a `GET` request to `/v2/solana/accounts` pub async fn send( self, - ) -> Result, Error> { + ) -> Result, Error> { let Self { client, page_size, page_token, - scope, } = self; let page_size = page_size.map_err(Error::InvalidRequest)?; let page_token = page_token.map_err(Error::InvalidRequest)?; - let scope = scope.map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/policy-engine/policies", client.baseurl,); + let url = format!("{}/v2/solana/accounts", client.baseurl,); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), @@ -94673,13 +108510,10 @@ pub mod builder { "pageToken", &page_token, )) - .query(&progenitor_middleware_client::QueryParam::new( - "scope", &scope, - )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "list_policies", + operation_id: "list_solana_accounts", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -94700,66 +108534,85 @@ pub mod builder { } } } - /**Builder for [`Client::create_policy`] + /**Builder for [`Client::create_solana_account`] - [`Client::create_policy`]: super::Client::create_policy*/ + [`Client::create_solana_account`]: super::Client::create_solana_account*/ #[derive(Debug, Clone)] - pub struct CreatePolicy<'a> { + pub struct CreateSolanaAccount<'a> { client: &'a super::Client, - x_idempotency_key: Result, String>, - body: Result, + x_idempotency_key: Result, String>, + x_wallet_auth: Result<::std::string::String, String>, + body: Result, } - impl<'a> CreatePolicy<'a> { + impl<'a> CreateSolanaAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, x_idempotency_key: Ok(None), + x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), body: Ok(::std::default::Default::default()), } } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `CreatePolicyXIdempotencyKey` for x_idempotency_key failed" + "conversion to `CreateSolanaAccountXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self } + pub fn x_wallet_auth(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.x_wallet_auth = value.try_into().map_err(|_| { + "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() + }); + self + } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto, + >::Error: std::fmt::Display, { - self.body = value - .try_into() - .map(From::from) - .map_err(|s| format!("conversion to `CreatePolicyBody` for body failed: {}", s)); + self.body = value.try_into().map(From::from).map_err(|s| { + format!( + "conversion to `CreateSolanaAccountBody` for body failed: {}", + s + ) + }); self } pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::CreatePolicyBody, - ) -> types::builder::CreatePolicyBody, + types::builder::CreateSolanaAccountBody, + ) -> types::builder::CreateSolanaAccountBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/policy-engine/policies` - pub async fn send(self) -> Result, Error> { + ///Sends a `POST` request to `/v2/solana/accounts` + pub async fn send( + self, + ) -> Result, Error> { let Self { client, x_idempotency_key, + x_wallet_auth, body, } = self; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; + let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body - .and_then(|v| types::CreatePolicyBody::try_from(v).map_err(|e| e.to_string())) + .and_then(|v| { + types::CreateSolanaAccountBody::try_from(v).map_err(|e| e.to_string()) + }) .map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/policy-engine/policies", client.baseurl,); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(2usize); + let url = format!("{}/v2/solana/accounts", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), @@ -94767,6 +108620,7 @@ pub mod builder { if let Some(value) = x_idempotency_key { header_map.append("X-Idempotency-Key", value.to_string().try_into()?); } + header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client @@ -94779,7 +108633,7 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "create_policy", + operation_id: "create_solana_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -94790,6 +108644,12 @@ pub mod builder { 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 401u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 402u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 409u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -94809,38 +108669,40 @@ pub mod builder { } } } - /**Builder for [`Client::get_policy_by_id`] + /**Builder for [`Client::get_solana_account_by_name`] - [`Client::get_policy_by_id`]: super::Client::get_policy_by_id*/ + [`Client::get_solana_account_by_name`]: super::Client::get_solana_account_by_name*/ #[derive(Debug, Clone)] - pub struct GetPolicyById<'a> { + pub struct GetSolanaAccountByName<'a> { client: &'a super::Client, - policy_id: Result, + name: Result<::std::string::String, String>, } - impl<'a> GetPolicyById<'a> { + impl<'a> GetSolanaAccountByName<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - policy_id: Err("policy_id was not initialized".to_string()), + name: Err("name was not initialized".to_string()), } } - pub fn policy_id(mut self, value: V) -> Self + pub fn name(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto<::std::string::String>, { - self.policy_id = value.try_into().map_err(|_| { - "conversion to `GetPolicyByIdPolicyId` for policy_id failed".to_string() + self.name = value.try_into().map_err(|_| { + "conversion to `:: std :: string :: String` for name failed".to_string() }); self } - ///Sends a `GET` request to `/v2/policy-engine/policies/{policyId}` - pub async fn send(self) -> Result, Error> { - let Self { client, policy_id } = self; - let policy_id = policy_id.map_err(Error::InvalidRequest)?; + ///Sends a `GET` request to `/v2/solana/accounts/by-name/{name}` + pub async fn send( + self, + ) -> Result, Error> { + let Self { client, name } = self; + let name = name.map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/policy-engine/policies/{}", + "{}/v2/solana/accounts/by-name/{}", client.baseurl, - encode_path(&policy_id.to_string()), + encode_path(&name.to_string()), ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( @@ -94858,7 +108720,7 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "get_policy_by_id", + operation_id: "get_solana_account_by_name", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -94866,6 +108728,9 @@ pub mod builder { let response = result?; match response.status().as_u16() { 200u16 => ResponseValue::from_response::(response).await, + 400u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -94882,83 +108747,107 @@ pub mod builder { } } } - /**Builder for [`Client::update_policy`] + /**Builder for [`Client::export_solana_account_by_name`] - [`Client::update_policy`]: super::Client::update_policy*/ + [`Client::export_solana_account_by_name`]: super::Client::export_solana_account_by_name*/ #[derive(Debug, Clone)] - pub struct UpdatePolicy<'a> { + pub struct ExportSolanaAccountByName<'a> { client: &'a super::Client, - policy_id: Result, - x_idempotency_key: Result, String>, - body: Result, + name: Result<::std::string::String, String>, + x_idempotency_key: Result, String>, + x_wallet_auth: Result<::std::string::String, String>, + body: Result, } - impl<'a> UpdatePolicy<'a> { + impl<'a> ExportSolanaAccountByName<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - policy_id: Err("policy_id was not initialized".to_string()), + name: Err("name was not initialized".to_string()), x_idempotency_key: Ok(None), + x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), body: Ok(::std::default::Default::default()), } } - pub fn policy_id(mut self, value: V) -> Self + pub fn name(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto<::std::string::String>, { - self.policy_id = value.try_into().map_err(|_| { - "conversion to `UpdatePolicyPolicyId` for policy_id failed".to_string() + self.name = value.try_into().map_err(|_| { + "conversion to `:: std :: string :: String` for name failed".to_string() }); self } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `UpdatePolicyXIdempotencyKey` for x_idempotency_key failed" - .to_string() + self.x_idempotency_key = value + .try_into() + .map(Some) + .map_err(|_| { + "conversion to `ExportSolanaAccountByNameXIdempotencyKey` for x_idempotency_key failed" + .to_string() + }); + self + } + pub fn x_wallet_auth(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.x_wallet_auth = value.try_into().map_err(|_| { + "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() }); self } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto, + >::Error: + std::fmt::Display, { - self.body = value - .try_into() - .map(From::from) - .map_err(|s| format!("conversion to `UpdatePolicyBody` for body failed: {}", s)); + self.body = value.try_into().map(From::from).map_err(|s| { + format!( + "conversion to `ExportSolanaAccountByNameBody` for body failed: {}", + s + ) + }); self } pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::UpdatePolicyBody, - ) -> types::builder::UpdatePolicyBody, + types::builder::ExportSolanaAccountByNameBody, + ) -> types::builder::ExportSolanaAccountByNameBody, { self.body = self.body.map(f); self } - ///Sends a `PUT` request to `/v2/policy-engine/policies/{policyId}` - pub async fn send(self) -> Result, Error> { + ///Sends a `POST` request to `/v2/solana/accounts/export/by-name/{name}` + pub async fn send( + self, + ) -> Result, Error> + { let Self { client, - policy_id, + name, x_idempotency_key, + x_wallet_auth, body, } = self; - let policy_id = policy_id.map_err(Error::InvalidRequest)?; + let name = name.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; + let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body - .and_then(|v| types::UpdatePolicyBody::try_from(v).map_err(|e| e.to_string())) + .and_then(|v| { + types::ExportSolanaAccountByNameBody::try_from(v).map_err(|e| e.to_string()) + }) .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/policy-engine/policies/{}", + "{}/v2/solana/accounts/export/by-name/{}", client.baseurl, - encode_path(&policy_id.to_string()), + encode_path(&name.to_string()), ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(2usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), @@ -94966,10 +108855,11 @@ pub mod builder { if let Some(value) = x_idempotency_key { header_map.append("X-Idempotency-Key", value.to_string().try_into()?); } + header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client - .put(url) + .post(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), @@ -94978,7 +108868,7 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "update_policy", + operation_id: "export_solana_account_by_name", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -94989,10 +108879,13 @@ pub mod builder { 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 404u16 => Err(Error::ErrorResponse( + 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 409u16 => Err(Error::ErrorResponse( + 402u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 422u16 => Err(Error::ErrorResponse( @@ -95011,57 +108904,85 @@ pub mod builder { } } } - /**Builder for [`Client::delete_policy`] + /**Builder for [`Client::import_solana_account`] - [`Client::delete_policy`]: super::Client::delete_policy*/ + [`Client::import_solana_account`]: super::Client::import_solana_account*/ #[derive(Debug, Clone)] - pub struct DeletePolicy<'a> { + pub struct ImportSolanaAccount<'a> { client: &'a super::Client, - policy_id: Result, - x_idempotency_key: Result, String>, + x_idempotency_key: Result, String>, + x_wallet_auth: Result<::std::string::String, String>, + body: Result, } - impl<'a> DeletePolicy<'a> { + impl<'a> ImportSolanaAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - policy_id: Err("policy_id was not initialized".to_string()), x_idempotency_key: Ok(None), + x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), + body: Ok(::std::default::Default::default()), } } - pub fn policy_id(mut self, value: V) -> Self + pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.policy_id = value.try_into().map_err(|_| { - "conversion to `DeletePolicyPolicyId` for policy_id failed".to_string() + self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { + "conversion to `ImportSolanaAccountXIdempotencyKey` for x_idempotency_key failed" + .to_string() }); self } - pub fn x_idempotency_key(mut self, value: V) -> Self + pub fn x_wallet_auth(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto<::std::string::String>, { - self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `DeletePolicyXIdempotencyKey` for x_idempotency_key failed" - .to_string() + self.x_wallet_auth = value.try_into().map_err(|_| { + "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() }); self } - ///Sends a `DELETE` request to `/v2/policy-engine/policies/{policyId}` - pub async fn send(self) -> Result, Error> { + pub fn body(mut self, value: V) -> Self + where + V: std::convert::TryInto, + >::Error: std::fmt::Display, + { + self.body = value.try_into().map(From::from).map_err(|s| { + format!( + "conversion to `ImportSolanaAccountBody` for body failed: {}", + s + ) + }); + self + } + pub fn body_map(mut self, f: F) -> Self + where + F: std::ops::FnOnce( + types::builder::ImportSolanaAccountBody, + ) -> types::builder::ImportSolanaAccountBody, + { + self.body = self.body.map(f); + self + } + ///Sends a `POST` request to `/v2/solana/accounts/import` + pub async fn send( + self, + ) -> Result, Error> { let Self { client, - policy_id, x_idempotency_key, + x_wallet_auth, + body, } = self; - let policy_id = policy_id.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; - let url = format!( - "{}/v2/policy-engine/policies/{}", - client.baseurl, - encode_path(&policy_id.to_string()), - ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(2usize); + let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; + let body = body + .and_then(|v| { + types::ImportSolanaAccountBody::try_from(v).map_err(|e| e.to_string()) + }) + .map_err(Error::InvalidRequest)?; + let url = format!("{}/v2/solana/accounts/import", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), @@ -95069,129 +108990,42 @@ pub mod builder { if let Some(value) = x_idempotency_key { header_map.append("X-Idempotency-Key", value.to_string().try_into()?); } + header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client - .delete(url) + .post(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) + .json(&body) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "delete_policy", + operation_id: "import_solana_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 204u16 => Ok(ResponseValue::empty(response)), + 201u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 404u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 409u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 422u16 => Err(Error::ErrorResponse( + 401u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 500u16 => Err(Error::ErrorResponse( + 402u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 502u16 => Err(Error::ErrorResponse( + 409u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 503u16 => Err(Error::ErrorResponse( + 422u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - _ => Err(Error::UnexpectedResponse(response)), - } - } - } - /**Builder for [`Client::list_solana_accounts`] - - [`Client::list_solana_accounts`]: super::Client::list_solana_accounts*/ - #[derive(Debug, Clone)] - pub struct ListSolanaAccounts<'a> { - client: &'a super::Client, - page_size: Result, String>, - page_token: Result, String>, - } - impl<'a> ListSolanaAccounts<'a> { - pub fn new(client: &'a super::Client) -> Self { - Self { - client: client, - page_size: Ok(None), - page_token: Ok(None), - } - } - pub fn page_size(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.page_size = value - .try_into() - .map(Some) - .map_err(|_| "conversion to `i64` for page_size failed".to_string()); - self - } - pub fn page_token(mut self, value: V) -> Self - where - V: std::convert::TryInto<::std::string::String>, - { - self.page_token = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: string :: String` for page_token failed".to_string() - }); - self - } - ///Sends a `GET` request to `/v2/solana/accounts` - pub async fn send( - self, - ) -> Result, Error> { - let Self { - client, - page_size, - page_token, - } = self; - let page_size = page_size.map_err(Error::InvalidRequest)?; - let page_token = page_token.map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/solana/accounts", client.baseurl,); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); - header_map.append( - ::reqwest::header::HeaderName::from_static("api-version"), - ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), - ); - #[allow(unused_mut)] - let mut request = client - .client - .get(url) - .header( - ::reqwest::header::ACCEPT, - ::reqwest::header::HeaderValue::from_static("application/json"), - ) - .query(&progenitor_middleware_client::QueryParam::new( - "pageSize", &page_size, - )) - .query(&progenitor_middleware_client::QueryParam::new( - "pageToken", - &page_token, - )) - .headers(header_map) - .build()?; - let info = OperationInfo { - operation_id: "list_solana_accounts", - }; - client.pre(&mut request, &info).await?; - let result = client.exec(request, &info).await; - client.post(&result, &info).await?; - let response = result?; - match response.status().as_u16() { - 200u16 => ResponseValue::from_response::(response).await, 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -95205,17 +109039,17 @@ pub mod builder { } } } - /**Builder for [`Client::create_solana_account`] + /**Builder for [`Client::send_solana_transaction`] - [`Client::create_solana_account`]: super::Client::create_solana_account*/ + [`Client::send_solana_transaction`]: super::Client::send_solana_transaction*/ #[derive(Debug, Clone)] - pub struct CreateSolanaAccount<'a> { + pub struct SendSolanaTransaction<'a> { client: &'a super::Client, - x_idempotency_key: Result, String>, + x_idempotency_key: Result, String>, x_wallet_auth: Result<::std::string::String, String>, - body: Result, + body: Result, } - impl<'a> CreateSolanaAccount<'a> { + impl<'a> SendSolanaTransaction<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, @@ -95226,10 +109060,10 @@ pub mod builder { } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `CreateSolanaAccountXIdempotencyKey` for x_idempotency_key failed" + "conversion to `SendSolanaTransactionXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self @@ -95245,12 +109079,13 @@ pub mod builder { } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto, + >::Error: + std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `CreateSolanaAccountBody` for body failed: {}", + "conversion to `SendSolanaTransactionBody` for body failed: {}", s ) }); @@ -95259,16 +109094,17 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::CreateSolanaAccountBody, - ) -> types::builder::CreateSolanaAccountBody, + types::builder::SendSolanaTransactionBody, + ) -> types::builder::SendSolanaTransactionBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/solana/accounts` + ///Sends a `POST` request to `/v2/solana/accounts/send/transaction` pub async fn send( self, - ) -> Result, Error> { + ) -> Result, Error> + { let Self { client, x_idempotency_key, @@ -95279,10 +109115,10 @@ pub mod builder { let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body .and_then(|v| { - types::CreateSolanaAccountBody::try_from(v).map_err(|e| e.to_string()) + types::SendSolanaTransactionBody::try_from(v).map_err(|e| e.to_string()) }) .map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/solana/accounts", client.baseurl,); + let url = format!("{}/v2/solana/accounts/send/transaction", client.baseurl,); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), @@ -95304,14 +109140,14 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "create_solana_account", + operation_id: "send_solana_transaction", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 201u16 => ResponseValue::from_response::(response).await, + 200u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -95321,7 +109157,10 @@ pub mod builder { 402u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 409u16 => Err(Error::ErrorResponse( + 403u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 422u16 => Err(Error::ErrorResponse( @@ -95340,58 +109179,187 @@ pub mod builder { } } } - /**Builder for [`Client::get_solana_account_by_name`] + /**Builder for [`Client::get_solana_account`] - [`Client::get_solana_account_by_name`]: super::Client::get_solana_account_by_name*/ + [`Client::get_solana_account`]: super::Client::get_solana_account*/ #[derive(Debug, Clone)] - pub struct GetSolanaAccountByName<'a> { + pub struct GetSolanaAccount<'a> { client: &'a super::Client, - name: Result<::std::string::String, String>, + address: Result, } - impl<'a> GetSolanaAccountByName<'a> { + impl<'a> GetSolanaAccount<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + address: Err("address was not initialized".to_string()), + } + } + pub fn address(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.address = value.try_into().map_err(|_| { + "conversion to `GetSolanaAccountAddress` for address failed".to_string() + }); + self + } + ///Sends a `GET` request to `/v2/solana/accounts/{address}` + pub async fn send( + self, + ) -> Result, Error> { + let Self { client, address } = self; + let address = address.map_err(Error::InvalidRequest)?; + let url = format!( + "{}/v2/solana/accounts/{}", + client.baseurl, + encode_path(&address.to_string()), + ); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + #[allow(unused_mut)] + let mut request = client + .client + .get(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "get_solana_account", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 200u16 => ResponseValue::from_response::(response).await, + 400u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 404u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 500u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 502u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 503u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + _ => Err(Error::UnexpectedResponse(response)), + } + } + } + /**Builder for [`Client::update_solana_account`] + + [`Client::update_solana_account`]: super::Client::update_solana_account*/ + #[derive(Debug, Clone)] + pub struct UpdateSolanaAccount<'a> { + client: &'a super::Client, + address: Result, + x_idempotency_key: Result, String>, + body: Result, + } + impl<'a> UpdateSolanaAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - name: Err("name was not initialized".to_string()), + address: Err("address was not initialized".to_string()), + x_idempotency_key: Ok(None), + body: Ok(::std::default::Default::default()), } } - pub fn name(mut self, value: V) -> Self + pub fn address(mut self, value: V) -> Self where - V: std::convert::TryInto<::std::string::String>, + V: std::convert::TryInto, { - self.name = value.try_into().map_err(|_| { - "conversion to `:: std :: string :: String` for name failed".to_string() + self.address = value.try_into().map_err(|_| { + "conversion to `UpdateSolanaAccountAddress` for address failed".to_string() }); self } - ///Sends a `GET` request to `/v2/solana/accounts/by-name/{name}` + pub fn x_idempotency_key(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { + "conversion to `UpdateSolanaAccountXIdempotencyKey` for x_idempotency_key failed" + .to_string() + }); + self + } + pub fn body(mut self, value: V) -> Self + where + V: std::convert::TryInto, + >::Error: std::fmt::Display, + { + self.body = value.try_into().map(From::from).map_err(|s| { + format!( + "conversion to `UpdateSolanaAccountBody` for body failed: {}", + s + ) + }); + self + } + pub fn body_map(mut self, f: F) -> Self + where + F: std::ops::FnOnce( + types::builder::UpdateSolanaAccountBody, + ) -> types::builder::UpdateSolanaAccountBody, + { + self.body = self.body.map(f); + self + } + ///Sends a `PUT` request to `/v2/solana/accounts/{address}` pub async fn send( self, ) -> Result, Error> { - let Self { client, name } = self; - let name = name.map_err(Error::InvalidRequest)?; + let Self { + client, + address, + x_idempotency_key, + body, + } = self; + let address = address.map_err(Error::InvalidRequest)?; + let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; + let body = body + .and_then(|v| { + types::UpdateSolanaAccountBody::try_from(v).map_err(|e| e.to_string()) + }) + .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/solana/accounts/by-name/{}", + "{}/v2/solana/accounts/{}", client.baseurl, - encode_path(&name.to_string()), + encode_path(&address.to_string()), ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(2usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); + if let Some(value) = x_idempotency_key { + header_map.append("X-Idempotency-Key", value.to_string().try_into()?); + } #[allow(unused_mut)] let mut request = client .client - .get(url) + .put(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) + .json(&body) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "get_solana_account_by_name", + operation_id: "update_solana_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -95405,6 +109373,12 @@ pub mod builder { 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 409u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 422u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -95418,47 +109392,44 @@ pub mod builder { } } } - /**Builder for [`Client::export_solana_account_by_name`] + /**Builder for [`Client::export_solana_account`] - [`Client::export_solana_account_by_name`]: super::Client::export_solana_account_by_name*/ + [`Client::export_solana_account`]: super::Client::export_solana_account*/ #[derive(Debug, Clone)] - pub struct ExportSolanaAccountByName<'a> { + pub struct ExportSolanaAccount<'a> { client: &'a super::Client, - name: Result<::std::string::String, String>, - x_idempotency_key: Result, String>, + address: Result, + x_idempotency_key: Result, String>, x_wallet_auth: Result<::std::string::String, String>, - body: Result, + body: Result, } - impl<'a> ExportSolanaAccountByName<'a> { + impl<'a> ExportSolanaAccount<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - name: Err("name was not initialized".to_string()), + address: Err("address was not initialized".to_string()), x_idempotency_key: Ok(None), x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), body: Ok(::std::default::Default::default()), } } - pub fn name(mut self, value: V) -> Self + pub fn address(mut self, value: V) -> Self where - V: std::convert::TryInto<::std::string::String>, + V: std::convert::TryInto, { - self.name = value.try_into().map_err(|_| { - "conversion to `:: std :: string :: String` for name failed".to_string() + self.address = value.try_into().map_err(|_| { + "conversion to `ExportSolanaAccountAddress` for address failed".to_string() }); self } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.x_idempotency_key = value - .try_into() - .map(Some) - .map_err(|_| { - "conversion to `ExportSolanaAccountByNameXIdempotencyKey` for x_idempotency_key failed" - .to_string() - }); + self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { + "conversion to `ExportSolanaAccountXIdempotencyKey` for x_idempotency_key failed" + .to_string() + }); self } pub fn x_wallet_auth(mut self, value: V) -> Self @@ -95472,13 +109443,12 @@ pub mod builder { } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: - std::fmt::Display, + V: std::convert::TryInto, + >::Error: std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `ExportSolanaAccountByNameBody` for body failed: {}", + "conversion to `ExportSolanaAccountBody` for body failed: {}", s ) }); @@ -95487,36 +109457,36 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::ExportSolanaAccountByNameBody, - ) -> types::builder::ExportSolanaAccountByNameBody, + types::builder::ExportSolanaAccountBody, + ) -> types::builder::ExportSolanaAccountBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/solana/accounts/export/by-name/{name}` + ///Sends a `POST` request to `/v2/solana/accounts/{address}/export` pub async fn send( self, - ) -> Result, Error> + ) -> Result, Error> { let Self { client, - name, + address, x_idempotency_key, x_wallet_auth, body, } = self; - let name = name.map_err(Error::InvalidRequest)?; + let address = address.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body .and_then(|v| { - types::ExportSolanaAccountByNameBody::try_from(v).map_err(|e| e.to_string()) + types::ExportSolanaAccountBody::try_from(v).map_err(|e| e.to_string()) }) .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/solana/accounts/export/by-name/{}", + "{}/v2/solana/accounts/{}/export", client.baseurl, - encode_path(&name.to_string()), + encode_path(&address.to_string()), ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( @@ -95539,7 +109509,7 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "export_solana_account_by_name", + operation_id: "export_solana_account", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -95575,31 +109545,42 @@ pub mod builder { } } } - /**Builder for [`Client::import_solana_account`] + /**Builder for [`Client::sign_solana_message`] - [`Client::import_solana_account`]: super::Client::import_solana_account*/ + [`Client::sign_solana_message`]: super::Client::sign_solana_message*/ #[derive(Debug, Clone)] - pub struct ImportSolanaAccount<'a> { + pub struct SignSolanaMessage<'a> { client: &'a super::Client, - x_idempotency_key: Result, String>, + address: Result, + x_idempotency_key: Result, String>, x_wallet_auth: Result<::std::string::String, String>, - body: Result, + body: Result, } - impl<'a> ImportSolanaAccount<'a> { + impl<'a> SignSolanaMessage<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, + address: Err("address was not initialized".to_string()), x_idempotency_key: Ok(None), x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), body: Ok(::std::default::Default::default()), } } + pub fn address(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.address = value.try_into().map_err(|_| { + "conversion to `SignSolanaMessageAddress` for address failed".to_string() + }); + self + } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `ImportSolanaAccountXIdempotencyKey` for x_idempotency_key failed" + "conversion to `SignSolanaMessageXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self @@ -95615,12 +109596,12 @@ pub mod builder { } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto, + >::Error: std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `ImportSolanaAccountBody` for body failed: {}", + "conversion to `SignSolanaMessageBody` for body failed: {}", s ) }); @@ -95629,30 +109610,34 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::ImportSolanaAccountBody, - ) -> types::builder::ImportSolanaAccountBody, + types::builder::SignSolanaMessageBody, + ) -> types::builder::SignSolanaMessageBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/solana/accounts/import` + ///Sends a `POST` request to `/v2/solana/accounts/{address}/sign/message` pub async fn send( self, - ) -> Result, Error> { + ) -> Result, Error> { let Self { client, + address, x_idempotency_key, x_wallet_auth, body, } = self; + let address = address.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body - .and_then(|v| { - types::ImportSolanaAccountBody::try_from(v).map_err(|e| e.to_string()) - }) + .and_then(|v| types::SignSolanaMessageBody::try_from(v).map_err(|e| e.to_string())) .map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/solana/accounts/import", client.baseurl,); + let url = format!( + "{}/v2/solana/accounts/{}/sign/message", + client.baseurl, + encode_path(&address.to_string()), + ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), @@ -95674,14 +109659,14 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "import_solana_account", + operation_id: "sign_solana_message", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; client.post(&result, &info).await?; let response = result?; match response.status().as_u16() { - 201u16 => ResponseValue::from_response::(response).await, + 200u16 => ResponseValue::from_response::(response).await, 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -95691,6 +109676,9 @@ pub mod builder { 402u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 404u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 409u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -95710,31 +109698,42 @@ pub mod builder { } } } - /**Builder for [`Client::send_solana_transaction`] + /**Builder for [`Client::sign_solana_transaction`] - [`Client::send_solana_transaction`]: super::Client::send_solana_transaction*/ + [`Client::sign_solana_transaction`]: super::Client::sign_solana_transaction*/ #[derive(Debug, Clone)] - pub struct SendSolanaTransaction<'a> { + pub struct SignSolanaTransaction<'a> { client: &'a super::Client, - x_idempotency_key: Result, String>, + address: Result, + x_idempotency_key: Result, String>, x_wallet_auth: Result<::std::string::String, String>, - body: Result, + body: Result, } - impl<'a> SendSolanaTransaction<'a> { + impl<'a> SignSolanaTransaction<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, + address: Err("address was not initialized".to_string()), x_idempotency_key: Ok(None), x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), body: Ok(::std::default::Default::default()), } } + pub fn address(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.address = value.try_into().map_err(|_| { + "conversion to `SignSolanaTransactionAddress` for address failed".to_string() + }); + self + } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `SendSolanaTransactionXIdempotencyKey` for x_idempotency_key failed" + "conversion to `SignSolanaTransactionXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self @@ -95750,13 +109749,13 @@ pub mod builder { } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: + V: std::convert::TryInto, + >::Error: std::fmt::Display, { self.body = value.try_into().map(From::from).map_err(|s| { format!( - "conversion to `SendSolanaTransactionBody` for body failed: {}", + "conversion to `SignSolanaTransactionBody` for body failed: {}", s ) }); @@ -95765,31 +109764,37 @@ pub mod builder { pub fn body_map(mut self, f: F) -> Self where F: std::ops::FnOnce( - types::builder::SendSolanaTransactionBody, - ) -> types::builder::SendSolanaTransactionBody, + types::builder::SignSolanaTransactionBody, + ) -> types::builder::SignSolanaTransactionBody, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/solana/accounts/send/transaction` + ///Sends a `POST` request to `/v2/solana/accounts/{address}/sign/transaction` pub async fn send( self, - ) -> Result, Error> + ) -> Result, Error> { let Self { client, + address, x_idempotency_key, x_wallet_auth, body, } = self; + let address = address.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body .and_then(|v| { - types::SendSolanaTransactionBody::try_from(v).map_err(|e| e.to_string()) + types::SignSolanaTransactionBody::try_from(v).map_err(|e| e.to_string()) }) .map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/solana/accounts/send/transaction", client.baseurl,); + let url = format!( + "{}/v2/solana/accounts/{}/sign/transaction", + client.baseurl, + encode_path(&address.to_string()), + ); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), @@ -95811,7 +109816,7 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "send_solana_transaction", + operation_id: "sign_solana_transaction", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -95834,6 +109839,9 @@ pub mod builder { 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), + 409u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), 422u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -95850,41 +109858,55 @@ pub mod builder { } } } - /**Builder for [`Client::get_solana_account`] + /**Builder for [`Client::request_solana_faucet`] - [`Client::get_solana_account`]: super::Client::get_solana_account*/ + [`Client::request_solana_faucet`]: super::Client::request_solana_faucet*/ #[derive(Debug, Clone)] - pub struct GetSolanaAccount<'a> { + pub struct RequestSolanaFaucet<'a> { client: &'a super::Client, - address: Result, + body: Result, } - impl<'a> GetSolanaAccount<'a> { + impl<'a> RequestSolanaFaucet<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - address: Err("address was not initialized".to_string()), + body: Ok(::std::default::Default::default()), } } - pub fn address(mut self, value: V) -> Self + pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, + >::Error: std::fmt::Display, { - self.address = value.try_into().map_err(|_| { - "conversion to `GetSolanaAccountAddress` for address failed".to_string() + self.body = value.try_into().map(From::from).map_err(|s| { + format!( + "conversion to `RequestSolanaFaucetBody` for body failed: {}", + s + ) }); self } - ///Sends a `GET` request to `/v2/solana/accounts/{address}` + pub fn body_map(mut self, f: F) -> Self + where + F: std::ops::FnOnce( + types::builder::RequestSolanaFaucetBody, + ) -> types::builder::RequestSolanaFaucetBody, + { + self.body = self.body.map(f); + self + } + ///Sends a `POST` request to `/v2/solana/faucet` pub async fn send( self, - ) -> Result, Error> { - let Self { client, address } = self; - let address = address.map_err(Error::InvalidRequest)?; - let url = format!( - "{}/v2/solana/accounts/{}", - client.baseurl, - encode_path(&address.to_string()), - ); + ) -> Result, Error> + { + let Self { client, body } = self; + let body = body + .and_then(|v| { + types::RequestSolanaFaucetBody::try_from(v).map_err(|e| e.to_string()) + }) + .map_err(Error::InvalidRequest)?; + let url = format!("{}/v2/solana/faucet", client.baseurl,); let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), @@ -95893,15 +109915,16 @@ pub mod builder { #[allow(unused_mut)] let mut request = client .client - .get(url) + .post(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) + .json(&body) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "get_solana_account", + operation_id: "request_solana_faucet", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -95912,7 +109935,10 @@ pub mod builder { 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 404u16 => Err(Error::ErrorResponse( + 403u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 429u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 500u16 => Err(Error::ErrorResponse( @@ -95928,109 +109954,110 @@ pub mod builder { } } } - /**Builder for [`Client::update_solana_account`] + /**Builder for [`Client::list_solana_token_balances`] - [`Client::update_solana_account`]: super::Client::update_solana_account*/ + [`Client::list_solana_token_balances`]: super::Client::list_solana_token_balances*/ #[derive(Debug, Clone)] - pub struct UpdateSolanaAccount<'a> { + pub struct ListSolanaTokenBalances<'a> { client: &'a super::Client, - address: Result, - x_idempotency_key: Result, String>, - body: Result, + network: Result, + address: Result, + page_size: Result, String>, + page_token: Result, String>, } - impl<'a> UpdateSolanaAccount<'a> { + impl<'a> ListSolanaTokenBalances<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, + network: Err("network was not initialized".to_string()), address: Err("address was not initialized".to_string()), - x_idempotency_key: Ok(None), - body: Ok(::std::default::Default::default()), + page_size: Ok(None), + page_token: Ok(None), } } - pub fn address(mut self, value: V) -> Self + pub fn network(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.address = value.try_into().map_err(|_| { - "conversion to `UpdateSolanaAccountAddress` for address failed".to_string() + self.network = value.try_into().map_err(|_| { + "conversion to `ListSolanaTokenBalancesNetwork` for network failed".to_string() }); self } - pub fn x_idempotency_key(mut self, value: V) -> Self + pub fn address(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `UpdateSolanaAccountXIdempotencyKey` for x_idempotency_key failed" - .to_string() + self.address = value.try_into().map_err(|_| { + "conversion to `ListSolanaTokenBalancesAddress` for address failed".to_string() }); self } - pub fn body(mut self, value: V) -> Self + pub fn page_size(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto, { - self.body = value.try_into().map(From::from).map_err(|s| { - format!( - "conversion to `UpdateSolanaAccountBody` for body failed: {}", - s - ) - }); + self.page_size = value + .try_into() + .map(Some) + .map_err(|_| "conversion to `i64` for page_size failed".to_string()); self } - pub fn body_map(mut self, f: F) -> Self + pub fn page_token(mut self, value: V) -> Self where - F: std::ops::FnOnce( - types::builder::UpdateSolanaAccountBody, - ) -> types::builder::UpdateSolanaAccountBody, + V: std::convert::TryInto<::std::string::String>, { - self.body = self.body.map(f); + self.page_token = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for page_token failed".to_string() + }); self } - ///Sends a `PUT` request to `/v2/solana/accounts/{address}` + ///Sends a `GET` request to `/v2/solana/token-balances/{network}/{address}` pub async fn send( self, - ) -> Result, Error> { + ) -> Result, Error> + { let Self { client, + network, address, - x_idempotency_key, - body, + page_size, + page_token, } = self; + let network = network.map_err(Error::InvalidRequest)?; let address = address.map_err(Error::InvalidRequest)?; - let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; - let body = body - .and_then(|v| { - types::UpdateSolanaAccountBody::try_from(v).map_err(|e| e.to_string()) - }) - .map_err(Error::InvalidRequest)?; + let page_size = page_size.map_err(Error::InvalidRequest)?; + let page_token = page_token.map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/solana/accounts/{}", + "{}/v2/solana/token-balances/{}/{}", client.baseurl, + encode_path(&network.to_string()), encode_path(&address.to_string()), ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(2usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); - if let Some(value) = x_idempotency_key { - header_map.append("X-Idempotency-Key", value.to_string().try_into()?); - } #[allow(unused_mut)] let mut request = client .client - .put(url) + .get(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) - .json(&body) + .query(&progenitor_middleware_client::QueryParam::new( + "pageSize", &page_size, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "pageToken", + &page_token, + )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "update_solana_account", + operation_id: "list_solana_token_balances", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -96044,12 +110071,6 @@ pub mod builder { 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 409u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 422u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 500u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), @@ -96062,125 +110083,336 @@ pub mod builder { _ => Err(Error::UnexpectedResponse(response)), } } - } - /**Builder for [`Client::export_solana_account`] - - [`Client::export_solana_account`]: super::Client::export_solana_account*/ - #[derive(Debug, Clone)] - pub struct ExportSolanaAccount<'a> { - client: &'a super::Client, - address: Result, - x_idempotency_key: Result, String>, - x_wallet_auth: Result<::std::string::String, String>, - body: Result, - } - impl<'a> ExportSolanaAccount<'a> { - pub fn new(client: &'a super::Client) -> Self { - Self { - client: client, - address: Err("address was not initialized".to_string()), - x_idempotency_key: Ok(None), - x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), - body: Ok(::std::default::Default::default()), - } + } + /**Builder for [`Client::list_transfers`] + + [`Client::list_transfers`]: super::Client::list_transfers*/ + #[derive(Debug, Clone)] + pub struct ListTransfers<'a> { + client: &'a super::Client, + account_id: Result, String>, + created_after: Result>, String>, + created_before: Result>, String>, + page_size: Result, String>, + page_token: Result, String>, + source_account_id: Result, String>, + source_address: Result, String>, + source_asset: Result, String>, + status: Result, String>, + target_account_id: Result, String>, + target_address: Result, String>, + target_asset: Result, String>, + target_email: Result, String>, + transfer_id: Result, String>, + updated_after: Result>, String>, + updated_before: Result>, String>, + } + impl<'a> ListTransfers<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + account_id: Ok(None), + created_after: Ok(None), + created_before: Ok(None), + page_size: Ok(None), + page_token: Ok(None), + source_account_id: Ok(None), + source_address: Ok(None), + source_asset: Ok(None), + status: Ok(None), + target_account_id: Ok(None), + target_address: Ok(None), + target_asset: Ok(None), + target_email: Ok(None), + transfer_id: Ok(None), + updated_after: Ok(None), + updated_before: Ok(None), + } + } + pub fn account_id(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.account_id = value + .try_into() + .map(Some) + .map_err(|_| "conversion to `AccountId` for account_id failed".to_string()); + self + } + pub fn created_after(mut self, value: V) -> Self + where + V: std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, + { + self.created_after = value + .try_into() + .map(Some) + .map_err(|_| { + "conversion to `:: chrono :: DateTime < :: chrono :: offset :: Utc >` for created_after failed" + .to_string() + }); + self + } + pub fn created_before(mut self, value: V) -> Self + where + V: std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, + { + self.created_before = value + .try_into() + .map(Some) + .map_err(|_| { + "conversion to `:: chrono :: DateTime < :: chrono :: offset :: Utc >` for created_before failed" + .to_string() + }); + self + } + pub fn page_size(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.page_size = value + .try_into() + .map(Some) + .map_err(|_| "conversion to `i64` for page_size failed".to_string()); + self + } + pub fn page_token(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.page_token = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for page_token failed".to_string() + }); + self + } + pub fn source_account_id(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.source_account_id = value + .try_into() + .map(Some) + .map_err(|_| "conversion to `AccountId` for source_account_id failed".to_string()); + self + } + pub fn source_address(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.source_address = value.try_into().map(Some).map_err(|_| { + "conversion to `BlockchainAddress` for source_address failed".to_string() + }); + self + } + pub fn source_asset(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::string::String>, + { + self.source_asset = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for source_asset failed".to_string() + }); + self + } + pub fn status(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.status = value + .try_into() + .map(Some) + .map_err(|_| "conversion to `TransferStatus` for status failed".to_string()); + self + } + pub fn target_account_id(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.target_account_id = value + .try_into() + .map(Some) + .map_err(|_| "conversion to `AccountId` for target_account_id failed".to_string()); + self } - pub fn address(mut self, value: V) -> Self + pub fn target_address(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.address = value.try_into().map_err(|_| { - "conversion to `ExportSolanaAccountAddress` for address failed".to_string() + self.target_address = value.try_into().map(Some).map_err(|_| { + "conversion to `BlockchainAddress` for target_address failed".to_string() }); self } - pub fn x_idempotency_key(mut self, value: V) -> Self + pub fn target_asset(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto<::std::string::String>, { - self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `ExportSolanaAccountXIdempotencyKey` for x_idempotency_key failed" - .to_string() + self.target_asset = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for target_asset failed".to_string() }); self } - pub fn x_wallet_auth(mut self, value: V) -> Self + pub fn target_email(mut self, value: V) -> Self where V: std::convert::TryInto<::std::string::String>, { - self.x_wallet_auth = value.try_into().map_err(|_| { - "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() + self.target_email = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: string :: String` for target_email failed".to_string() }); self } - pub fn body(mut self, value: V) -> Self + pub fn transfer_id(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto, { - self.body = value.try_into().map(From::from).map_err(|s| { - format!( - "conversion to `ExportSolanaAccountBody` for body failed: {}", - s - ) + self.transfer_id = value.try_into().map(Some).map_err(|_| { + "conversion to `ListTransfersTransferId` for transfer_id failed".to_string() }); self } - pub fn body_map(mut self, f: F) -> Self + pub fn updated_after(mut self, value: V) -> Self where - F: std::ops::FnOnce( - types::builder::ExportSolanaAccountBody, - ) -> types::builder::ExportSolanaAccountBody, + V: std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, { - self.body = self.body.map(f); + self.updated_after = value + .try_into() + .map(Some) + .map_err(|_| { + "conversion to `:: chrono :: DateTime < :: chrono :: offset :: Utc >` for updated_after failed" + .to_string() + }); self } - ///Sends a `POST` request to `/v2/solana/accounts/{address}/export` + pub fn updated_before(mut self, value: V) -> Self + where + V: std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, + { + self.updated_before = value + .try_into() + .map(Some) + .map_err(|_| { + "conversion to `:: chrono :: DateTime < :: chrono :: offset :: Utc >` for updated_before failed" + .to_string() + }); + self + } + ///Sends a `GET` request to `/v2/transfers` pub async fn send( self, - ) -> Result, Error> - { + ) -> Result, Error> { let Self { client, - address, - x_idempotency_key, - x_wallet_auth, - body, + account_id, + created_after, + created_before, + page_size, + page_token, + source_account_id, + source_address, + source_asset, + status, + target_account_id, + target_address, + target_asset, + target_email, + transfer_id, + updated_after, + updated_before, } = self; - let address = address.map_err(Error::InvalidRequest)?; - let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; - let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; - let body = body - .and_then(|v| { - types::ExportSolanaAccountBody::try_from(v).map_err(|e| e.to_string()) - }) - .map_err(Error::InvalidRequest)?; - let url = format!( - "{}/v2/solana/accounts/{}/export", - client.baseurl, - encode_path(&address.to_string()), - ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); + let account_id = account_id.map_err(Error::InvalidRequest)?; + let created_after = created_after.map_err(Error::InvalidRequest)?; + let created_before = created_before.map_err(Error::InvalidRequest)?; + let page_size = page_size.map_err(Error::InvalidRequest)?; + let page_token = page_token.map_err(Error::InvalidRequest)?; + let source_account_id = source_account_id.map_err(Error::InvalidRequest)?; + let source_address = source_address.map_err(Error::InvalidRequest)?; + let source_asset = source_asset.map_err(Error::InvalidRequest)?; + let status = status.map_err(Error::InvalidRequest)?; + let target_account_id = target_account_id.map_err(Error::InvalidRequest)?; + let target_address = target_address.map_err(Error::InvalidRequest)?; + let target_asset = target_asset.map_err(Error::InvalidRequest)?; + let target_email = target_email.map_err(Error::InvalidRequest)?; + let transfer_id = transfer_id.map_err(Error::InvalidRequest)?; + let updated_after = updated_after.map_err(Error::InvalidRequest)?; + let updated_before = updated_before.map_err(Error::InvalidRequest)?; + let url = format!("{}/v2/transfers", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); - if let Some(value) = x_idempotency_key { - header_map.append("X-Idempotency-Key", value.to_string().try_into()?); - } - header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client - .post(url) + .get(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) - .json(&body) + .query(&progenitor_middleware_client::QueryParam::new( + "accountId", + &account_id, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "createdAfter", + &created_after, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "createdBefore", + &created_before, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "pageSize", &page_size, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "pageToken", + &page_token, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "sourceAccountId", + &source_account_id, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "sourceAddress", + &source_address, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "sourceAsset", + &source_asset, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "status", &status, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "targetAccountId", + &target_account_id, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "targetAddress", + &target_address, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "targetAsset", + &target_asset, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "targetEmail", + &target_email, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "transferId", + &transfer_id, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "updatedAfter", + &updated_after, + )) + .query(&progenitor_middleware_client::QueryParam::new( + "updatedBefore", + &updated_before, + )) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "export_solana_account", + operation_id: "list_transfers", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -96191,125 +110423,68 @@ pub mod builder { 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 401u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 402u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 404u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 422u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 500u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 502u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 503u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::sign_solana_message`] + /**Builder for [`Client::create_transfer`] - [`Client::sign_solana_message`]: super::Client::sign_solana_message*/ + [`Client::create_transfer`]: super::Client::create_transfer*/ #[derive(Debug, Clone)] - pub struct SignSolanaMessage<'a> { + pub struct CreateTransfer<'a> { client: &'a super::Client, - address: Result, - x_idempotency_key: Result, String>, - x_wallet_auth: Result<::std::string::String, String>, - body: Result, + x_idempotency_key: Result, String>, + body: Result, } - impl<'a> SignSolanaMessage<'a> { + impl<'a> CreateTransfer<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - address: Err("address was not initialized".to_string()), x_idempotency_key: Ok(None), - x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), body: Ok(::std::default::Default::default()), } } - pub fn address(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.address = value.try_into().map_err(|_| { - "conversion to `SignSolanaMessageAddress` for address failed".to_string() - }); - self - } pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `SignSolanaMessageXIdempotencyKey` for x_idempotency_key failed" + "conversion to `CreateTransferXIdempotencyKey` for x_idempotency_key failed" .to_string() }); self } - pub fn x_wallet_auth(mut self, value: V) -> Self - where - V: std::convert::TryInto<::std::string::String>, - { - self.x_wallet_auth = value.try_into().map_err(|_| { - "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() - }); - self - } pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto, + >::Error: std::fmt::Display, { - self.body = value.try_into().map(From::from).map_err(|s| { - format!( - "conversion to `SignSolanaMessageBody` for body failed: {}", - s - ) - }); + self.body = value + .try_into() + .map(From::from) + .map_err(|s| format!("conversion to `TransferRequest` for body failed: {}", s)); self } pub fn body_map(mut self, f: F) -> Self where - F: std::ops::FnOnce( - types::builder::SignSolanaMessageBody, - ) -> types::builder::SignSolanaMessageBody, + F: std::ops::FnOnce(types::builder::TransferRequest) -> types::builder::TransferRequest, { self.body = self.body.map(f); self } - ///Sends a `POST` request to `/v2/solana/accounts/{address}/sign/message` - pub async fn send( - self, - ) -> Result, Error> { + ///Sends a `POST` request to `/v2/transfers` + pub async fn send(self) -> Result, Error> { let Self { client, - address, x_idempotency_key, - x_wallet_auth, body, } = self; - let address = address.map_err(Error::InvalidRequest)?; let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; - let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; let body = body - .and_then(|v| types::SignSolanaMessageBody::try_from(v).map_err(|e| e.to_string())) + .and_then(|v| types::TransferRequest::try_from(v).map_err(|e| e.to_string())) .map_err(Error::InvalidRequest)?; - let url = format!( - "{}/v2/solana/accounts/{}/sign/message", - client.baseurl, - encode_path(&address.to_string()), - ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); + let url = format!("{}/v2/transfers", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(2usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), @@ -96317,7 +110492,6 @@ pub mod builder { if let Some(value) = x_idempotency_key { header_map.append("X-Idempotency-Key", value.to_string().try_into()?); } - header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client @@ -96330,7 +110504,7 @@ pub mod builder { .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "sign_solana_message", + operation_id: "create_transfer", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -96341,153 +110515,66 @@ pub mod builder { 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 401u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 402u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 404u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 409u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 422u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 500u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 502u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 503u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::sign_solana_transaction`] + /**Builder for [`Client::get_transfer_by_id`] - [`Client::sign_solana_transaction`]: super::Client::sign_solana_transaction*/ + [`Client::get_transfer_by_id`]: super::Client::get_transfer_by_id*/ #[derive(Debug, Clone)] - pub struct SignSolanaTransaction<'a> { + pub struct GetTransferById<'a> { client: &'a super::Client, - address: Result, - x_idempotency_key: Result, String>, - x_wallet_auth: Result<::std::string::String, String>, - body: Result, + transfer_id: Result, } - impl<'a> SignSolanaTransaction<'a> { + impl<'a> GetTransferById<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - address: Err("address was not initialized".to_string()), - x_idempotency_key: Ok(None), - x_wallet_auth: Err("x_wallet_auth was not initialized".to_string()), - body: Ok(::std::default::Default::default()), + transfer_id: Err("transfer_id was not initialized".to_string()), } } - pub fn address(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.address = value.try_into().map_err(|_| { - "conversion to `SignSolanaTransactionAddress` for address failed".to_string() - }); - self - } - pub fn x_idempotency_key(mut self, value: V) -> Self - where - V: std::convert::TryInto, - { - self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { - "conversion to `SignSolanaTransactionXIdempotencyKey` for x_idempotency_key failed" - .to_string() - }); - self - } - pub fn x_wallet_auth(mut self, value: V) -> Self - where - V: std::convert::TryInto<::std::string::String>, - { - self.x_wallet_auth = value.try_into().map_err(|_| { - "conversion to `:: std :: string :: String` for x_wallet_auth failed".to_string() - }); - self - } - pub fn body(mut self, value: V) -> Self + pub fn transfer_id(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: - std::fmt::Display, + V: std::convert::TryInto, { - self.body = value.try_into().map(From::from).map_err(|s| { - format!( - "conversion to `SignSolanaTransactionBody` for body failed: {}", - s - ) + self.transfer_id = value.try_into().map_err(|_| { + "conversion to `GetTransferByIdTransferId` for transfer_id failed".to_string() }); self } - pub fn body_map(mut self, f: F) -> Self - where - F: std::ops::FnOnce( - types::builder::SignSolanaTransactionBody, - ) -> types::builder::SignSolanaTransactionBody, - { - self.body = self.body.map(f); - self - } - ///Sends a `POST` request to `/v2/solana/accounts/{address}/sign/transaction` - pub async fn send( - self, - ) -> Result, Error> - { + ///Sends a `GET` request to `/v2/transfers/{transferId}` + pub async fn send(self) -> Result, Error> { let Self { client, - address, - x_idempotency_key, - x_wallet_auth, - body, + transfer_id, } = self; - let address = address.map_err(Error::InvalidRequest)?; - let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; - let x_wallet_auth = x_wallet_auth.map_err(Error::InvalidRequest)?; - let body = body - .and_then(|v| { - types::SignSolanaTransactionBody::try_from(v).map_err(|e| e.to_string()) - }) - .map_err(Error::InvalidRequest)?; + let transfer_id = transfer_id.map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/solana/accounts/{}/sign/transaction", + "{}/v2/transfers/{}", client.baseurl, - encode_path(&address.to_string()), + encode_path(&transfer_id.to_string()), ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); - if let Some(value) = x_idempotency_key { - header_map.append("X-Idempotency-Key", value.to_string().try_into()?); - } - header_map.append("X-Wallet-Auth", x_wallet_auth.to_string().try_into()?); #[allow(unused_mut)] let mut request = client .client - .post(url) + .get(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) - .json(&body) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "sign_solana_transaction", + operation_id: "get_transfer_by_id", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -96495,94 +110582,71 @@ pub mod builder { let response = result?; match response.status().as_u16() { 200u16 => ResponseValue::from_response::(response).await, - 400u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 401u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 402u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 403u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 409u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 422u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 500u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 502u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 503u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), _ => Err(Error::UnexpectedResponse(response)), } } } - /**Builder for [`Client::request_solana_faucet`] + /**Builder for [`Client::execute_fund_transfer`] - [`Client::request_solana_faucet`]: super::Client::request_solana_faucet*/ + [`Client::execute_fund_transfer`]: super::Client::execute_fund_transfer*/ #[derive(Debug, Clone)] - pub struct RequestSolanaFaucet<'a> { + pub struct ExecuteFundTransfer<'a> { client: &'a super::Client, - body: Result, + transfer_id: Result, + x_idempotency_key: Result, String>, } - impl<'a> RequestSolanaFaucet<'a> { + impl<'a> ExecuteFundTransfer<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - body: Ok(::std::default::Default::default()), + transfer_id: Err("transfer_id was not initialized".to_string()), + x_idempotency_key: Ok(None), } } - pub fn body(mut self, value: V) -> Self + pub fn transfer_id(mut self, value: V) -> Self where - V: std::convert::TryInto, - >::Error: std::fmt::Display, + V: std::convert::TryInto, { - self.body = value.try_into().map(From::from).map_err(|s| { - format!( - "conversion to `RequestSolanaFaucetBody` for body failed: {}", - s - ) + self.transfer_id = value.try_into().map_err(|_| { + "conversion to `ExecuteFundTransferTransferId` for transfer_id failed".to_string() }); self } - pub fn body_map(mut self, f: F) -> Self + pub fn x_idempotency_key(mut self, value: V) -> Self where - F: std::ops::FnOnce( - types::builder::RequestSolanaFaucetBody, - ) -> types::builder::RequestSolanaFaucetBody, + V: std::convert::TryInto, { - self.body = self.body.map(f); + self.x_idempotency_key = value.try_into().map(Some).map_err(|_| { + "conversion to `ExecuteFundTransferXIdempotencyKey` for x_idempotency_key failed" + .to_string() + }); self } - ///Sends a `POST` request to `/v2/solana/faucet` - pub async fn send( - self, - ) -> Result, Error> - { - let Self { client, body } = self; - let body = body - .and_then(|v| { - types::RequestSolanaFaucetBody::try_from(v).map_err(|e| e.to_string()) - }) - .map_err(Error::InvalidRequest)?; - let url = format!("{}/v2/solana/faucet", client.baseurl,); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + ///Sends a `POST` request to `/v2/transfers/{transferId}/execute` + pub async fn send(self) -> Result, Error> { + let Self { + client, + transfer_id, + x_idempotency_key, + } = self; + let transfer_id = transfer_id.map_err(Error::InvalidRequest)?; + let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; + let url = format!( + "{}/v2/transfers/{}/execute", + client.baseurl, + encode_path(&transfer_id.to_string()), + ); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(2usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); + if let Some(value) = x_idempotency_key { + header_map.append("X-Idempotency-Key", value.to_string().try_into()?); + } #[allow(unused_mut)] let mut request = client .client @@ -96591,11 +110655,10 @@ pub mod builder { ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) - .json(&body) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "request_solana_faucet", + operation_id: "execute_fund_transfer", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -96606,7 +110669,13 @@ pub mod builder { 400u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 403u16 => Err(Error::ErrorResponse( + 401u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 404u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 422u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), 429u16 => Err(Error::ErrorResponse( @@ -96625,110 +110694,113 @@ pub mod builder { } } } - /**Builder for [`Client::list_solana_token_balances`] + /**Builder for [`Client::submit_deposit_travel_rule`] - [`Client::list_solana_token_balances`]: super::Client::list_solana_token_balances*/ + [`Client::submit_deposit_travel_rule`]: super::Client::submit_deposit_travel_rule*/ #[derive(Debug, Clone)] - pub struct ListSolanaTokenBalances<'a> { + pub struct SubmitDepositTravelRule<'a> { client: &'a super::Client, - network: Result, - address: Result, - page_size: Result, String>, - page_token: Result, String>, + transfer_id: Result, + x_idempotency_key: Result, String>, + body: Result, } - impl<'a> ListSolanaTokenBalances<'a> { + impl<'a> SubmitDepositTravelRule<'a> { pub fn new(client: &'a super::Client) -> Self { Self { client: client, - network: Err("network was not initialized".to_string()), - address: Err("address was not initialized".to_string()), - page_size: Ok(None), - page_token: Ok(None), + transfer_id: Err("transfer_id was not initialized".to_string()), + x_idempotency_key: Ok(None), + body: Ok(::std::default::Default::default()), } } - pub fn network(mut self, value: V) -> Self + pub fn transfer_id(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.network = value.try_into().map_err(|_| { - "conversion to `ListSolanaTokenBalancesNetwork` for network failed".to_string() + self.transfer_id = value.try_into().map_err(|_| { + "conversion to `SubmitDepositTravelRuleTransferId` for transfer_id failed" + .to_string() }); self } - pub fn address(mut self, value: V) -> Self + pub fn x_idempotency_key(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, { - self.address = value.try_into().map_err(|_| { - "conversion to `ListSolanaTokenBalancesAddress` for address failed".to_string() - }); + self.x_idempotency_key = value + .try_into() + .map(Some) + .map_err(|_| { + "conversion to `SubmitDepositTravelRuleXIdempotencyKey` for x_idempotency_key failed" + .to_string() + }); self } - pub fn page_size(mut self, value: V) -> Self + pub fn body(mut self, value: V) -> Self where - V: std::convert::TryInto, + V: std::convert::TryInto, + >::Error: std::fmt::Display, { - self.page_size = value - .try_into() - .map(Some) - .map_err(|_| "conversion to `i64` for page_size failed".to_string()); + self.body = value.try_into().map(From::from).map_err(|s| { + format!( + "conversion to `DepositTravelRuleRequest` for body failed: {}", + s + ) + }); self } - pub fn page_token(mut self, value: V) -> Self + pub fn body_map(mut self, f: F) -> Self where - V: std::convert::TryInto<::std::string::String>, + F: std::ops::FnOnce( + types::builder::DepositTravelRuleRequest, + ) -> types::builder::DepositTravelRuleRequest, { - self.page_token = value.try_into().map(Some).map_err(|_| { - "conversion to `:: std :: string :: String` for page_token failed".to_string() - }); + self.body = self.body.map(f); self } - ///Sends a `GET` request to `/v2/solana/token-balances/{network}/{address}` + ///Sends a `POST` request to `/v2/transfers/{transferId}/travel-rule` pub async fn send( self, - ) -> Result, Error> - { + ) -> Result, Error> { let Self { client, - network, - address, - page_size, - page_token, + transfer_id, + x_idempotency_key, + body, } = self; - let network = network.map_err(Error::InvalidRequest)?; - let address = address.map_err(Error::InvalidRequest)?; - let page_size = page_size.map_err(Error::InvalidRequest)?; - let page_token = page_token.map_err(Error::InvalidRequest)?; + let transfer_id = transfer_id.map_err(Error::InvalidRequest)?; + let x_idempotency_key = x_idempotency_key.map_err(Error::InvalidRequest)?; + let body = body + .and_then(|v| { + types::DepositTravelRuleRequest::try_from(v).map_err(|e| e.to_string()) + }) + .map_err(Error::InvalidRequest)?; let url = format!( - "{}/v2/solana/token-balances/{}/{}", + "{}/v2/transfers/{}/travel-rule", client.baseurl, - encode_path(&network.to_string()), - encode_path(&address.to_string()), + encode_path(&transfer_id.to_string()), ); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(2usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); + if let Some(value) = x_idempotency_key { + header_map.append("X-Idempotency-Key", value.to_string().try_into()?); + } #[allow(unused_mut)] let mut request = client .client - .get(url) + .post(url) .header( ::reqwest::header::ACCEPT, ::reqwest::header::HeaderValue::from_static("application/json"), ) - .query(&progenitor_middleware_client::QueryParam::new( - "pageSize", &page_size, - )) - .query(&progenitor_middleware_client::QueryParam::new( - "pageToken", - &page_token, - )) + .json(&body) .headers(header_map) .build()?; let info = OperationInfo { - operation_id: "list_solana_token_balances", + operation_id: "submit_deposit_travel_rule", }; client.pre(&mut request, &info).await?; let result = client.exec(request, &info).await; @@ -96742,13 +110814,7 @@ pub mod builder { 404u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), - 500u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 502u16 => Err(Error::ErrorResponse( - ResponseValue::from_response(response).await?, - )), - 503u16 => Err(Error::ErrorResponse( + 422u16 => Err(Error::ErrorResponse( ResponseValue::from_response(response).await?, )), _ => Err(Error::UnexpectedResponse(response)), diff --git a/typescript/src/index.ts b/typescript/src/index.ts index bf6c4cf49..c6b175cbc 100644 --- a/typescript/src/index.ts +++ b/typescript/src/index.ts @@ -75,3 +75,20 @@ export { listX402DiscoveryMerchant, searchX402Resources, } from "./openapi-client/index.js"; + +export { + CdpOpenApiClient, + configure, + listFoundationAccounts, + getFoundationAccountById, + listBalances, + getBalanceByAsset, + createTransfer, + listTransfers, + getTransferById, + listDepositDestinations, + createDepositDestination, + listPaymentMethods, + getPaymentMethod, +} from "./openapi-client/index.js"; +export type { CdpOptions } from "./openapi-client/cdpApiClient.js"; diff --git a/typescript/src/openapi-client/cdpApiClient.ts b/typescript/src/openapi-client/cdpApiClient.ts index 86f34fddb..bc2772cf8 100644 --- a/typescript/src/openapi-client/cdpApiClient.ts +++ b/typescript/src/openapi-client/cdpApiClient.ts @@ -314,7 +314,7 @@ export const cdpApiClient = async ( * @throws {Error} If the call is not valid. */ const validateCall = (config: AxiosRequestConfig) => { - if (!axiosInstance.getUri() || axiosInstance.getUri() === "") { + if (!axiosInstance || !axiosInstance.getUri() || axiosInstance.getUri() === "") { throw new Error("CDP client URI not configured. Call configure() first."); } diff --git a/typescript/src/openapi-client/generated/accounts/accounts.ts b/typescript/src/openapi-client/generated/accounts/accounts.ts new file mode 100644 index 000000000..ac95cc32d --- /dev/null +++ b/typescript/src/openapi-client/generated/accounts/accounts.ts @@ -0,0 +1,103 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * OpenAPI spec version: 2.0.0 + */ +import type { + Account, + AccountId, + Asset, + Balance, + CreateAccountRequest, + ListBalances200, + ListBalancesParams, + ListFoundationAccounts200, + ListFoundationAccountsParams, +} from "../coinbaseDeveloperPlatformAPIs.schemas.js"; + +import { cdpApiClient } from "../../cdpApiClient.js"; + +type SecondParameter unknown> = Parameters[1]; + +/** + * List all accounts. The API will return all accounts that the API Key has Permissions to access. You can filter the results by using query parameters, which will be treated as a single conjunction (i.e. AND). Results are sorted by creation date in descending order (newest first). + * @summary List accounts + */ +export const listFoundationAccounts = ( + params?: ListFoundationAccountsParams, + options?: SecondParameter>, +) => { + return cdpApiClient( + { url: `/v2/accounts`, method: "GET", params }, + options, + ); +}; +/** + * Create an account for your Entity. Support for creating Customer-owned accounts is in development. + * @summary Create account + */ +export const createFoundationAccount = ( + createAccountRequest: CreateAccountRequest, + options?: SecondParameter>, +) => { + return cdpApiClient( + { + url: `/v2/accounts`, + method: "POST", + headers: { "Content-Type": "application/json" }, + data: createAccountRequest, + }, + options, + ); +}; +/** + * Get an account by its ID. + * @summary Get account + */ +export const getFoundationAccountById = ( + accountId: AccountId, + options?: SecondParameter>, +) => { + return cdpApiClient({ url: `/v2/accounts/${accountId}`, method: "GET" }, options); +}; +/** + * List the balances for an account. Results are sorted by native-fiat equivalent balance in descending order. + * @summary List balances for account + */ +export const listBalances = ( + accountId: AccountId, + params?: ListBalancesParams, + options?: SecondParameter>, +) => { + return cdpApiClient( + { url: `/v2/accounts/${accountId}/balances`, method: "GET", params }, + options, + ); +}; +/** + * Get the balance for an account by asset. + * @summary Get balance for account + */ +export const getBalanceByAsset = ( + accountId: AccountId, + asset: Asset, + options?: SecondParameter>, +) => { + return cdpApiClient( + { url: `/v2/accounts/${accountId}/balances/${asset}`, method: "GET" }, + options, + ); +}; +export type ListFoundationAccountsResult = NonNullable< + Awaited> +>; +export type CreateFoundationAccountResult = NonNullable< + Awaited> +>; +export type GetFoundationAccountByIdResult = NonNullable< + Awaited> +>; +export type ListBalancesResult = NonNullable>>; +export type GetBalanceByAssetResult = NonNullable>>; diff --git a/typescript/src/openapi-client/generated/coinbaseDeveloperPlatformAPIs.schemas.ts b/typescript/src/openapi-client/generated/coinbaseDeveloperPlatformAPIs.schemas.ts index 8f9582ba8..8c1104751 100644 --- a/typescript/src/openapi-client/generated/coinbaseDeveloperPlatformAPIs.schemas.ts +++ b/typescript/src/openapi-client/generated/coinbaseDeveloperPlatformAPIs.schemas.ts @@ -5,6 +5,903 @@ * The Coinbase Developer Platform APIs - leading the world's transition onchain. * OpenAPI spec version: 2.0.0 */ +/** + * The type of the Account. + */ +export type AccountType = (typeof AccountType)[keyof typeof AccountType]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const AccountType = { + prime: "prime", + business: "business", + cdp: "cdp", +} as const; + +/** + * The ID of the Account, which is a UUID prefixed by the string `account_`. + * @pattern ^account_[a-f0-9\-]{36}$ + */ +export type AccountId = string; + +/** + * The Owner ID of the Account. +Owner IDs are UUIDs prefixed with the Owner Type as follows: +* **Entity**: `entity_` - If the Owner is your Entity, e.g. `entity_af2937b0-9846-4fe7-bfe9-ccc22d935114`. +Support for Customer-owned accounts (`customer_` prefix) is in development. + * @pattern ^(entity|customer)_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$ + */ +export type Owner = string; + +/** + * An optional name for the account. Must be 1-64 characters and can only contain alphanumeric characters, hyphens, and spaces. + * @maxLength 64 + * @pattern ^[a-zA-Z0-9 -]{1,64}$ + */ +export type AccountName = string; + +export interface Account { + accountId: AccountId; + type: AccountType; + owner: Owner; + name?: AccountName; + /** The timestamp when the account was created. */ + createdAt: string; + /** The timestamp when the account was last updated. */ + updatedAt: string; +} + +export interface ListResponse { + /** The token for the next page of items, if any. */ + nextPageToken?: string; +} + +/** + * The code that indicates the type of error that occurred. These error codes can be used to determine how to handle the error. + */ +export type ErrorType = (typeof ErrorType)[keyof typeof ErrorType]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const ErrorType = { + already_exists: "already_exists", + authorization_expired: "authorization_expired", + bad_gateway: "bad_gateway", + capture_expired: "capture_expired", + client_closed_request: "client_closed_request", + endpoint_unavailable: "endpoint_unavailable", + faucet_limit_exceeded: "faucet_limit_exceeded", + forbidden: "forbidden", + idempotency_error: "idempotency_error", + internal_server_error: "internal_server_error", + invalid_request: "invalid_request", + invalid_sql_query: "invalid_sql_query", + invalid_signature: "invalid_signature", + malformed_transaction: "malformed_transaction", + not_found: "not_found", + payment_method_required: "payment_method_required", + payment_required: "payment_required", + settlement_failed: "settlement_failed", + rate_limit_exceeded: "rate_limit_exceeded", + request_canceled: "request_canceled", + service_unavailable: "service_unavailable", + timed_out: "timed_out", + unauthorized: "unauthorized", + unsupported_tos_language: "unsupported_tos_language", + policy_violation: "policy_violation", + policy_in_use: "policy_in_use", + account_limit_exceeded: "account_limit_exceeded", + network_not_tradable: "network_not_tradable", + guest_permission_denied: "guest_permission_denied", + guest_region_forbidden: "guest_region_forbidden", + guest_transaction_limit: "guest_transaction_limit", + guest_transaction_count: "guest_transaction_count", + phone_number_verification_expired: "phone_number_verification_expired", + document_verification_failed: "document_verification_failed", + recipient_allowlist_violation: "recipient_allowlist_violation", + recipient_allowlist_pending: "recipient_allowlist_pending", + refund_expired: "refund_expired", + travel_rules_recipient_violation: "travel_rules_recipient_violation", + source_account_invalid: "source_account_invalid", + target_account_invalid: "target_account_invalid", + source_account_not_found: "source_account_not_found", + target_account_not_found: "target_account_not_found", + source_asset_not_supported: "source_asset_not_supported", + target_asset_not_supported: "target_asset_not_supported", + target_email_invalid: "target_email_invalid", + target_onchain_address_invalid: "target_onchain_address_invalid", + transfer_amount_invalid: "transfer_amount_invalid", + transfer_asset_not_supported: "transfer_asset_not_supported", + transfer_quote_expired: "transfer_quote_expired", + insufficient_balance: "insufficient_balance", + metadata_too_many_entries: "metadata_too_many_entries", + metadata_key_too_long: "metadata_key_too_long", + metadata_value_too_long: "metadata_value_too_long", + travel_rules_field_missing: "travel_rules_field_missing", + asset_mismatch: "asset_mismatch", + mfa_already_enrolled: "mfa_already_enrolled", + mfa_invalid_code: "mfa_invalid_code", + mfa_flow_expired: "mfa_flow_expired", + mfa_required: "mfa_required", + mfa_not_enrolled: "mfa_not_enrolled", + order_quote_expired: "order_quote_expired", + order_already_filled: "order_already_filled", + order_already_canceled: "order_already_canceled", + account_not_ready: "account_not_ready", + insufficient_liquidity: "insufficient_liquidity", + insufficient_allowance: "insufficient_allowance", + transaction_simulation_failed: "transaction_simulation_failed", + delegation_not_found: "delegation_not_found", + delegation_expired: "delegation_expired", + delegation_revoked: "delegation_revoked", + delegation_not_authorized: "delegation_not_authorized", + delegation_not_enabled: "delegation_not_enabled", +} as const; + +/** + * A valid HTTP or HTTPS URL. + * @minLength 11 + * @maxLength 2048 + * @pattern ^https?://.*$ + */ +export type Url = string; + +/** + * An error response including the code for the type of error and a human-readable message describing the error. + */ +export interface Error { + errorType: ErrorType; + /** The error message. */ + errorMessage: string; + /** A unique identifier for the request that generated the error. This can be used to help debug issues with the API. */ + correlationId?: string; + /** A link to the corresponding error documentation. */ + errorLink?: Url; +} + +export interface CreateAccountRequest { + name?: AccountName; +} + +/** + * The symbol of the asset (e.g., eth, usd, usdc, usdt). + * @minLength 1 + * @maxLength 42 + */ +export type Asset = string; + +/** + * The type of the asset. + */ +export type AssetType = (typeof AssetType)[keyof typeof AssetType]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const AssetType = { + fiat: "fiat", + crypto: "crypto", +} as const; + +/** + * An asset, e.g. fiat or crypto. + */ +export interface BalancesAsset { + symbol: Asset; + type: AssetType; + /** The name of the asset. */ + name: string; + /** The number of decimals (i.e. significant digits to the right of the decimal point) supported for the asset. */ + decimals: number; +} + +/** + * Available and total amounts for a specific currency. + */ +export interface AmountDetail { + /** The amount that is currently available to be used. */ + available: string; + /** The total amount, including the amount that is currently on hold. */ + total: string; +} + +/** + * Amount details denominated in different assets. +- The keys represent the asset symbols (e.g., "btc", "usd"), - Each value contains available and total amounts. - There will always be an entry for the asset specified in the `asset` field. + */ +export type BalanceAmount = { [key: string]: AmountDetail }; + +/** + * A balance of an asset. + */ +export interface Balance { + asset: BalancesAsset; + /** Amount details denominated in different assets. +- The keys represent the asset symbols (e.g., "btc", "usd"), - Each value contains available and total amounts. - There will always be an entry for the asset specified in the `asset` field. */ + amount: BalanceAmount; +} + +/** + * A list of balances for an account. + */ +export interface Balances { + /** The list of balances. */ + balances: Balance[]; +} + +/** + * The type of deposit destination. + */ +export type DepositDestinationType = string; + +/** + * The ID of the Deposit Destination, which is a UUID prefixed by the string `depositDestination_`. + * @pattern ^depositDestination_[a-f0-9\-]{36}$ + */ +export type DepositDestinationId = string; + +/** + * The blockchain network for the payment. Supported networks depend on the account type. See [API and Network Support](https://docs.cdp.coinbase.com/api-reference/payment-apis/supported-networks-assets#by-asset-and-network) for more details. + */ +export type Network = (typeof Network)[keyof typeof Network]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const Network = { + base: "base", + ethereum: "ethereum", + solana: "solana", + aptos: "aptos", + arbitrum: "arbitrum", + "arbitrum-sepolia": "arbitrum-sepolia", + optimism: "optimism", + polygon: "polygon", + world: "world", + "world-sepolia": "world-sepolia", +} as const; + +/** + * A blockchain address. Format varies by network (e.g., 0x-prefixed for EVM, base58 for Solana). + * @minLength 1 + * @maxLength 128 + */ +export type BlockchainAddress = string; + +/** + * Crypto-specific deposit destination details. In responses, this object is always present. Contains the network and address for the deposit destination. + */ +export interface DepositDestinationCrypto { + network: Network; + address: BlockchainAddress; +} + +/** + * The account and asset where incoming deposits should be credited. + */ +export interface DepositDestinationTargetAccount { + /** The ID of the CDP Account to which deposited funds should be transferred. */ + accountId?: AccountId; + /** The symbol of the asset that should land in the target account. */ + asset: Asset; +} + +/** + * The intended target for deposited funds. + */ +export type DepositDestinationTarget = DepositDestinationTargetAccount; + +/** + * The status of the deposit destination. + */ +export type DepositDestinationStatus = + (typeof DepositDestinationStatus)[keyof typeof DepositDestinationStatus]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const DepositDestinationStatus = { + active: "active", + inactive: "inactive", + pending: "pending", +} as const; + +/** + * Optional metadata as key-value pairs. Use this to store additional structured information on a resource, such as customer IDs, order references, or any application-specific data. Up to 10 key/value pairs may be provided. Keys and values are both strings. Keys must be ≤ 40 characters; values must be ≤ 500 characters. + */ +export interface Metadata { + [key: string]: string; +} + +export type CryptoDepositDestinationType = + (typeof CryptoDepositDestinationType)[keyof typeof CryptoDepositDestinationType]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const CryptoDepositDestinationType = { + crypto: "crypto", +} as const; + +/** + * A cryptocurrency deposit destination. + */ +export interface CryptoDepositDestination { + depositDestinationId: DepositDestinationId; + accountId: AccountId; + type: CryptoDepositDestinationType; + /** Crypto-specific details for this deposit destination. Always populated in responses. Contains the network and address. */ + crypto: DepositDestinationCrypto; + target?: DepositDestinationTarget; + status: DepositDestinationStatus; + metadata?: Metadata; + /** The timestamp when the deposit destination was created. */ + createdAt: string; + /** The timestamp when the deposit destination was last updated. */ + updatedAt: string; +} + +/** + * A deposit destination for receiving funds to an account. + */ +export type DepositDestination = CryptoDepositDestination; + +/** + * Common fields for creating a deposit destination. + */ +export interface CreateDepositDestinationRequestBase { + /** The ID of the Account, which is a UUID prefixed by the string `account_`, that owns the deposit destination. */ + accountId: AccountId; + type: DepositDestinationType; + target?: DepositDestinationTarget; + metadata?: Metadata; +} + +/** + * Crypto-specific details for creating a deposit destination. + */ +export interface CreateDepositDestinationCrypto { + network: Network; +} + +export type CreateCryptoDepositDestinationRequestAllOfType = + (typeof CreateCryptoDepositDestinationRequestAllOfType)[keyof typeof CreateCryptoDepositDestinationRequestAllOfType]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const CreateCryptoDepositDestinationRequestAllOfType = { + crypto: "crypto", +} as const; + +export type CreateCryptoDepositDestinationRequestAllOf = { + type?: CreateCryptoDepositDestinationRequestAllOfType; + /** Crypto-specific details. Required when `type` is `crypto`. */ + crypto: CreateDepositDestinationCrypto; +}; + +export type CreateCryptoDepositDestinationRequestType = + (typeof CreateCryptoDepositDestinationRequestType)[keyof typeof CreateCryptoDepositDestinationRequestType]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const CreateCryptoDepositDestinationRequestType = { + crypto: "crypto", +} as const; + +export type CreateCryptoDepositDestinationRequest = CreateDepositDestinationRequestBase & + CreateCryptoDepositDestinationRequestAllOf & { + type: CreateCryptoDepositDestinationRequestType; + }; + +/** + * Request to create a new deposit destination. Provide the type-specific details matching the chosen `type`. + */ +export type CreateDepositDestinationRequest = CreateCryptoDepositDestinationRequest; + +/** + * The current status of the transfer, indicating what action you need to take next. Required when validateOnly is false. + */ +export type TransferStatus = (typeof TransferStatus)[keyof typeof TransferStatus]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const TransferStatus = { + /** Transfer was created with `execute: true`, but is momentarily being quoted before executing _or_ the transfer was created with `execute: false`. It can be executed by calling `\/v2\/transfers\/{transferId}\/execute` with `execute: true`. */ + quoted: "quoted", + /** Transfer is executing after being quoted. No action needed - monitor progress via the transfers webhook. */ + processing: "processing", + /** Transfer completed successfully. */ + completed: "completed", + /** Transfer failed. See `failureReason` for details. */ + failed: "failed", +} as const; + +/** + * The Account specific details for the transfer. + */ +export interface TransfersAccount { + /** The ID of the Account. */ + accountId: string; + asset: Asset; +} + +/** + * The Payment Method specific details for the transfer. + */ +export interface PaymentMethod { + /** The ID of the Payment Method. */ + paymentMethodId: string; + asset: Asset; +} + +/** + * The target of the payment is an onchain address. + */ +export interface OnchainAddress { + /** The onchain crypto address of the recipient. + +Examples: +- EVM address: 0xabc1234567890abcdef1234567890abcdef123456 +- Solana address: HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT +- XRP address: rhccc5p23aKiCGFcEqqnjEfLRZ6xEvfy3s + */ + address: BlockchainAddress; + network: Network; + /** The destination tag of the onchain address. Destination tags are used by certain networks +(primarily XRP/Ripple) to identify specific recipients when multiple users share a single address. +The tag ensures funds are credited to the correct account within the shared address. + +Examples by network: +- XRP/Ripple: Numeric values like "1234567890" or "123456" +- Stellar (XLM): Memos which can be text, ID, or hash format + +Note: Most networks (Ethereum, Bitcoin, Solana) do not use destination tags. + */ + destinationTag?: string; + /** Asset symbol of the payment received by the recipient. */ + asset: Asset; +} + +/** + * The originating US bank account details for the transfer source. Present when funds were deposited from an external bank account into a deposit destination. Only the last 4 digits of the account number are exposed. + */ +export interface OriginatingBankAccountUS { + /** The name of the bank that originated the deposit. */ + bankName: string; + /** + * The last 4 digits of the originating bank account number. + * @pattern ^[0-9]{4}$ + */ + accountLast4: string; + /** The fiat currency of the deposit (e.g., `usd`). */ + currency: string; +} + +/** + * The source of the transfer. + */ +export type TransferSource = + | TransfersAccount + | PaymentMethod + | OnchainAddress + | OriginatingBankAccountUS; + +/** + * The target of the payment is an email address. + */ +export interface EmailAddress { + /** The email address of the recipient. The recipient will need to have an account with Coinbase or onboard to Coinbase to receive the payment. */ + email: string; +} + +export type EmailInstrumentAllOf = { + /** Asset symbol of the payment received by the recipient. */ + asset: Asset; +}; + +/** + * The target of the payment is an email address. + */ +export type EmailInstrument = EmailAddress & EmailInstrumentAllOf; + +/** + * The target of the transfer. + */ +export type TransferTarget = TransfersAccount | PaymentMethod | OnchainAddress | EmailInstrument; + +/** + * Exchange rate information for currency conversion. The rate indicates how much of the target asset is equivalent to one unit of the source asset. + */ +export interface TransferExchangeRate { + /** The asset being converted from. */ + sourceAsset: Asset; + /** The asset being converted to. */ + targetAsset: Asset; + /** The exchange rate value as a decimal string. Indicates how many units of the target asset equal one unit of the source asset. */ + rate: string; +} + +/** + * The type of the fee, indicating its purpose. + */ +export type TransferFeeType = (typeof TransferFeeType)[keyof typeof TransferFeeType]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const TransferFeeType = { + BankFee: "bank", + ConversionFee: "conversion", + NetworkFee: "network", + OtherFee: "other", +} as const; + +/** + * A single fee for a transfer. + */ +export interface TransferFee { + /** The type of the fee, indicating its purpose. */ + type: TransferFeeType; + /** The amount of the fee in units of the asset specified by `asset`. */ + amount: string; + /** The asset symbol. */ + asset: Asset; +} + +/** + * The fees associated with this transfer. Different transfer types have different fee structures. + +**NOTE:** These examples are not exhaustive. + +Common examples: +* **Crypto transfers**: Network fees (gas) paid in the native token +* **Fiat conversions**: Processing fees + exchange fees in USD +* **Wire transfers**: Wire fees ($15) + processing fees ($5) in USD +* **Crypto conversions**: Spread fees paid in the source asset. + */ +export type TransferFees = TransferFee[]; + +/** + * A point-in-time snapshot of estimated values for a transfer where exact amounts cannot be locked in at quote time (e.g., when the executed rate is determined at execution time and moves with the market). + +Present in both pre-execution and post-execution states: +* **Quoted state:** top-level fields whose values cannot be guaranteed are absent; + `estimate` holds their estimated values. + +* **Completed state:** top-level fields contain the actual executed values; + `estimate` is retained as an immutable audit snapshot of the pre-execution estimate. + */ +export interface TransferEstimate { + exchangeRate?: TransferExchangeRate; + /** Estimated amount of the target asset that will be received, as a decimal string in standard unit denomination. */ + targetAmount?: string; + /** The asset symbol of the estimated target amount. */ + targetAsset?: Asset; + fees?: TransferFees; + /** The date and time when this estimate was captured. */ + estimatedAt: string; +} + +/** + * A reference to the deposit destination associated with the transfer. + */ +export interface DepositDestinationReference { + id: DepositDestinationId; +} + +/** + * The status of a travel rule submission. + */ +export type TravelRuleStatus = (typeof TravelRuleStatus)[keyof typeof TravelRuleStatus]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const TravelRuleStatus = { + /** Additional fields are required before the transfer can proceed. */ + TravelRuleStatusIncomplete: "incomplete", + /** All requirements are satisfied and the transfer will proceed. */ + TravelRuleStatusCompleted: "completed", +} as const; + +/** + * An onchain transaction associated with the transfer. + */ +export type TransferDetailsOnchainTransactionsItem = { + /** The transaction hash. */ + transactionHash: string; + network: Network; +}; + +/** + * Travel rule compliance status for deposit transfers. Present when the transfer requires travel rule information. + */ +export type TransferDetailsTravelRule = { + status?: TravelRuleStatus; + /** Additional details about the current travel rule status. For example, when status is `incomplete`, this may indicate the specific missing information required to proceed. */ + statusMessage?: string; +}; + +/** + * Additional details about the transfer. For example, if the transfer was sent to a deposit destination, the information about that destination will be included in this field. + */ +export interface TransferDetails { + depositDestination?: DepositDestinationReference; + /** The onchain transactions associated with the transfer. */ + onchainTransactions?: TransferDetailsOnchainTransactionsItem[]; + /** Travel rule compliance status for deposit transfers. Present when the transfer requires travel rule information. */ + travelRule?: TransferDetailsTravelRule; +} + +/** + * A Transfer represents all the information needed to execute a transfer and tracks the lifecycle of a transfer from initiation through completion or failure. + */ +export interface Transfer { + /** The ID of the transfer. Required when validateOnly is false. */ + transferId?: string; + status?: TransferStatus; + source: TransferSource; + target: TransferTarget; + /** The amount of the source asset that will be transferred out, as a decimal string in standard unit denomination. */ + sourceAmount?: string; + /** The asset symbol of the source amount. */ + sourceAsset?: Asset; + /** The amount of the target asset that will be received, as a decimal string in standard unit denomination. */ + targetAmount?: string; + /** The asset symbol of the target amount. */ + targetAsset?: Asset; + exchangeRate?: TransferExchangeRate; + fees?: TransferFees; + estimate?: TransferEstimate; + /** The date and time the transfer was completed. */ + completedAt?: string; + /** The reason for failure, if the transfer failed. Only present when status is `failed`. */ + failureReason?: string; + /** The date and time when this transfer will expire if not executed. Only present for `quoted` status. A new transfer must be created to obtain an updated quote after expiration. Required when validateOnly is false. */ + expiresAt?: string; + /** The date and time the transfer was executed and moved to processing. Only present when status has progressed beyond `quoted`. */ + executedAt?: string; + /** The date and time the transfer was created. Required when validateOnly is false. */ + createdAt?: string; + /** The date and time the transfer was last updated. Required when validateOnly is false. */ + updatedAt?: string; + metadata?: Metadata; + details?: TransferDetails; +} + +/** + * The source of the transfer. + */ +export type CreateTransferSource = TransfersAccount | PaymentMethod; + +/** + * A physical address with standard address components including street, city, state/province, postal code, and country. + */ +export interface PhysicalAddress { + /** Primary street address. */ + line1?: string; + /** Secondary address information. */ + line2?: string; + /** City or locality. */ + city?: string; + /** State, province, or region. */ + state?: string; + /** Postal or ZIP code. */ + postCode?: string; + /** + * ISO 3166-1 alpha-2 country code (2 characters). See https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes. + * @minLength 2 + * @maxLength 2 + */ + countryCode?: string; +} + +/** + * Information about a party (originator or beneficiary) for travel rule compliance. + */ +export interface TravelRuleParty { + /** Name of the financial institution. */ + financialInstitution?: string; + /** Full name of the party. */ + name?: string; + address?: PhysicalAddress; +} + +/** + * Information about the originating Virtual Asset Service Provider (VASP) that handles cryptocurrency or other virtual assets on behalf of customers. + */ +export type TravelRuleOriginatorAllOfVirtualAssetServiceProvider = { + /** The name of the originating Virtual Asset Service Provider (VASP). */ + name?: string; + /** The address of the originating Virtual Asset Service Provider (VASP). */ + address?: PhysicalAddress; + /** The Legal Entity Identifier of the originating Virtual Asset Service Provider (VASP). */ + identifier?: string; +}; + +export type TravelRuleOriginatorAllOf = { + /** Information about the originating Virtual Asset Service Provider (VASP) that handles cryptocurrency or other virtual assets on behalf of customers. */ + virtualAssetServiceProvider?: TravelRuleOriginatorAllOfVirtualAssetServiceProvider; +}; + +/** + * Originator (sender) party. + */ +export type TravelRuleOriginator = TravelRuleParty & TravelRuleOriginatorAllOf; + +/** + * The type of the beneficiary's wallet. + */ +export type TravelRuleBeneficiaryAllOfWalletType = + (typeof TravelRuleBeneficiaryAllOfWalletType)[keyof typeof TravelRuleBeneficiaryAllOfWalletType]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const TravelRuleBeneficiaryAllOfWalletType = { + custodial: "custodial", + self_custody: "self_custody", +} as const; + +export type TravelRuleBeneficiaryAllOf = { + /** The type of the beneficiary's wallet. */ + walletType?: TravelRuleBeneficiaryAllOfWalletType; +}; + +/** + * Beneficiary (receiver) party. + */ +export type TravelRuleBeneficiary = TravelRuleParty & TravelRuleBeneficiaryAllOf; + +/** + * Required Travel Rule fields differ by region. These requirements are determined based on which Coinbase entity the customer has signed the service agreement for. + */ +export interface TravelRule { + /** Indicates whether the user attests that the receiving wallet belongs to them. */ + isSelf?: boolean; + /** Indicates whether Coinbase is being used as an intermediary Virtual Asset Service Provider (VASP) to send crypto on behalf of your customer. + +**Background:** + +The Travel Rule (FATF Recommendation 16) requires VASPs to share originator and beneficiary information for virtual asset transfers. When Coinbase acts as an intermediary, additional Travel Rule data must be provided to satisfy compliance requirements. + +**Set to `true` when:** + +- Your organization is a VASP using Coinbase to send crypto **on behalf of your end customer** +- In this scenario, Coinbase acts as an intermediary in the transfer chain and handles Travel Rule data exchange with the beneficiary VASP + +**Set to `false` (or omit) when:** + +- You are transferring funds directly from your own Coinbase account, where **Coinbase is your primary VASP** rather than an intermediary for another institution + +**Impact on required fields:** + +When `isIntermediary` is `true`, you must provide the `originator` object with details about the original sender, including: +- Originator name +- Originator address +- Your VASP information (`virtualAssetServiceProvider` object with `name`, `address`, and `identifier`) + */ + isIntermediary?: boolean; + originator?: TravelRuleOriginator; + beneficiary?: TravelRuleBeneficiary; +} + +/** + * Specifies whether the given amount is to be received by the target or taken from the source. + +- `target`: The transfer `target` receives the exact value specified in `amount`. Fees are added to the amount taken from the transfer `source`. +- `source`: The transfer `target` receives the value specified in `amount`, minus any fees. + + */ +export type TransferRequestAmountType = + (typeof TransferRequestAmountType)[keyof typeof TransferRequestAmountType]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const TransferRequestAmountType = { + target: "target", + source: "source", +} as const; + +/** + * A request to create a transfer. + */ +export interface TransferRequest { + source: CreateTransferSource; + target: TransferTarget; + /** The amount of the transfer, as a decimal string in standard unit denomination of the asset specified by `asset` (e.g., "100.00" for 100 USD, "0.05" for 0.05 ETH). */ + amount: string; + /** The symbol of the asset for the amount. This must be one of the assets of the source or target. */ + asset: Asset; + /** Specifies whether the given amount is to be received by the target or taken from the source. + +- `target`: The transfer `target` receives the exact value specified in `amount`. Fees are added to the amount taken from the transfer `source`. +- `source`: The transfer `target` receives the value specified in `amount`, minus any fees. + */ + amountType?: TransferRequestAmountType; + /** If true, validates the transfer without initiating it. If the request is valid, a 2xx will be returned. If the request is invalid, a 4xx error will be returned. The response will include an errorType, for e.g. invalid_target if the specified target cannot receive funds. */ + validateOnly?: boolean; + /** Whether to immediately execute the transfer. If false, the transfer will be created in quoted status and must be executed manually via the /execute endpoint. */ + execute: boolean; + metadata?: Metadata; + travelRule?: TravelRule; +} + +/** + * Information about the Virtual Asset Service Provider (VASP) for a deposit travel rule submission. + */ +export interface DepositTravelRuleVasp { + /** The Legal Entity Identifier (LEI) of the Virtual Asset Service Provider (VASP). */ + identifier?: string; + /** The name of the Virtual Asset Service Provider (VASP). */ + name?: string; +} + +/** + * Date of birth. + */ +export interface DateOfBirth { + /** + * Day of birth (01-31). + * @minLength 2 + * @maxLength 2 + * @pattern ^[0-9]{2}$ + */ + day?: string; + /** + * Month of birth (01-12). + * @minLength 2 + * @maxLength 2 + * @pattern ^[0-9]{2}$ + */ + month?: string; + /** + * Year of birth (four digits). + * @minLength 4 + * @maxLength 4 + * @pattern ^[0-9]{4}$ + */ + year?: string; +} + +/** + * The type of the originator's wallet. + */ +export type DepositTravelRuleOriginatorWalletType = + (typeof DepositTravelRuleOriginatorWalletType)[keyof typeof DepositTravelRuleOriginatorWalletType]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const DepositTravelRuleOriginatorWalletType = { + /** The originator\'s wallet is held by a custodial service. */ + custodial: "custodial", + /** The originator\'s wallet is self-custodied. */ + self_custody: "self_custody", +} as const; + +/** + * Originator information for a deposit travel rule submission. + */ +export interface DepositTravelRuleOriginator { + /** Full name of the originator. */ + name?: string; + address?: PhysicalAddress; + /** The type of the originator's wallet. */ + walletType?: DepositTravelRuleOriginatorWalletType; + virtualAssetServiceProvider?: DepositTravelRuleVasp; + /** Government-issued personal identification number for the originator. */ + personalId?: string; + dateOfBirth?: DateOfBirth; +} + +/** + * Beneficiary information for a deposit travel rule submission. + */ +export interface DepositTravelRuleBeneficiary { + /** Full name of the beneficiary. */ + name?: string; +} + +/** + * Request body for submitting travel rule information for a deposit transfer. Required fields vary by jurisdiction. + */ +export interface DepositTravelRuleRequest { + originator?: DepositTravelRuleOriginator; + beneficiary?: DepositTravelRuleBeneficiary; + /** Indicates whether the user attests that the originating wallet belongs to them. */ + isSelf?: boolean; +} + +/** + * Response from submitting travel rule information for a deposit transfer. + */ +export interface DepositTravelRuleResponse { + status: TravelRuleStatus; + /** List of field paths that are still required to complete travel rule compliance. Each entry is a dot-separated path (e.g., "originator.name", "originator.address.countryCode"). Empty when status is "completed". */ + missingFields?: string[]; + /** Additional context about the current status. Present when status is `incomplete` to explain what needs to be fixed before the transfer can proceed. */ + reason?: string; +} + /** * The type of authentication information. */ @@ -121,13 +1018,6 @@ export interface TelegramAuthentication { username?: string; } -/** - * A blockchain address. Format varies by network (e.g., 0x-prefixed for EVM, base58 for Solana). - * @minLength 1 - * @maxLength 128 - */ -export type BlockchainAddress = string; - /** * The type of authentication information. */ @@ -271,112 +1161,6 @@ export interface EndUser { createdAt: string; } -export interface ListResponse { - /** The token for the next page of items, if any. */ - nextPageToken?: string; -} - -/** - * The code that indicates the type of error that occurred. These error codes can be used to determine how to handle the error. - */ -export type ErrorType = (typeof ErrorType)[keyof typeof ErrorType]; - -// eslint-disable-next-line @typescript-eslint/no-redeclare -export const ErrorType = { - already_exists: "already_exists", - authorization_expired: "authorization_expired", - bad_gateway: "bad_gateway", - capture_expired: "capture_expired", - client_closed_request: "client_closed_request", - faucet_limit_exceeded: "faucet_limit_exceeded", - forbidden: "forbidden", - idempotency_error: "idempotency_error", - internal_server_error: "internal_server_error", - invalid_request: "invalid_request", - invalid_sql_query: "invalid_sql_query", - invalid_signature: "invalid_signature", - malformed_transaction: "malformed_transaction", - not_found: "not_found", - payment_method_required: "payment_method_required", - payment_required: "payment_required", - settlement_failed: "settlement_failed", - rate_limit_exceeded: "rate_limit_exceeded", - request_canceled: "request_canceled", - service_unavailable: "service_unavailable", - timed_out: "timed_out", - unauthorized: "unauthorized", - policy_violation: "policy_violation", - policy_in_use: "policy_in_use", - account_limit_exceeded: "account_limit_exceeded", - network_not_tradable: "network_not_tradable", - guest_permission_denied: "guest_permission_denied", - guest_region_forbidden: "guest_region_forbidden", - guest_transaction_limit: "guest_transaction_limit", - guest_transaction_count: "guest_transaction_count", - phone_number_verification_expired: "phone_number_verification_expired", - document_verification_failed: "document_verification_failed", - recipient_allowlist_violation: "recipient_allowlist_violation", - recipient_allowlist_pending: "recipient_allowlist_pending", - refund_expired: "refund_expired", - travel_rules_recipient_violation: "travel_rules_recipient_violation", - source_account_invalid: "source_account_invalid", - target_account_invalid: "target_account_invalid", - source_account_not_found: "source_account_not_found", - target_account_not_found: "target_account_not_found", - source_asset_not_supported: "source_asset_not_supported", - target_asset_not_supported: "target_asset_not_supported", - target_email_invalid: "target_email_invalid", - target_onchain_address_invalid: "target_onchain_address_invalid", - transfer_amount_invalid: "transfer_amount_invalid", - transfer_asset_not_supported: "transfer_asset_not_supported", - insufficient_balance: "insufficient_balance", - metadata_too_many_entries: "metadata_too_many_entries", - metadata_key_too_long: "metadata_key_too_long", - metadata_value_too_long: "metadata_value_too_long", - travel_rules_field_missing: "travel_rules_field_missing", - asset_mismatch: "asset_mismatch", - mfa_already_enrolled: "mfa_already_enrolled", - mfa_invalid_code: "mfa_invalid_code", - mfa_flow_expired: "mfa_flow_expired", - mfa_required: "mfa_required", - mfa_not_enrolled: "mfa_not_enrolled", - order_quote_expired: "order_quote_expired", - order_already_filled: "order_already_filled", - order_already_canceled: "order_already_canceled", - account_not_ready: "account_not_ready", - insufficient_liquidity: "insufficient_liquidity", - insufficient_allowance: "insufficient_allowance", - transaction_simulation_failed: "transaction_simulation_failed", -} as const; - -/** - * A valid HTTP or HTTPS URL. - * @minLength 11 - * @maxLength 2048 - * @pattern ^https?://.*$ - */ -export type Url = string; - -/** - * An error response including the code for the type of error and a human-readable message describing the error. - */ -export interface Error { - errorType: ErrorType; - /** The error message. */ - errorMessage: string; - /** A unique identifier for the request that generated the error. This can be used to help debug issues with the API. */ - correlationId?: string; - /** A link to the corresponding error documentation. */ - errorLink?: Url; -} - -/** - * The symbol of the asset (e.g., eth, usd, usdc, usdt). - * @minLength 1 - * @maxLength 42 - */ -export type Asset = string; - /** * The domain of the EIP-712 typed data. */ @@ -2419,6 +3203,7 @@ export interface PrepareUserOperationRule { export type SendUserOperationCriteriaItem = | EthValueCriterion | EvmAddressCriterion + | EvmNetworkCriterion | EvmDataCriterion | NetUSDChangeCriterion; @@ -3201,13 +3986,6 @@ export interface AccountTokenAddressesResponse { totalCount?: number; } -/** - * Optional metadata as key-value pairs. Use this to store additional structured information on a resource, such as customer IDs, order references, or any application-specific data. Up to 10 key/value pairs may be provided. Keys and values are both strings. Keys must be ≤ 40 characters; values must be ≤ 500 characters. - */ -export interface Metadata { - [key: string]: string; -} - /** * Additional headers to include in webhook requests. */ @@ -4089,6 +4867,24 @@ export interface X402DiscoveryResource { /** Map of x402 protocol extensions supported by the resource, keyed by extension name. */ extensions?: X402DiscoveryResourceExtensions; quality?: X402ResourceQuality; + /** Provider-supplied display name of the service this resource belongs to. This is a free-form +label for grouping and presentation only — it is not a stable identifier, and two resources +sharing the same `serviceName` are not guaranteed to belong to the same logical service. + */ + serviceName?: string; + /** Provider-supplied, low-cardinality string labels associated with the resource for client-side +filtering and display. Values are free-form (no controlled vocabulary) and case-sensitive. +Order is not significant and duplicates are not expected. + */ + tags?: string[]; + /** URL of a square icon representing the service this resource belongs to. Distinct from a +brand logo: this is intended for compact, list-view rendering (favicon-style) and is +normalized to a square aspect ratio at ingestion. The image is moderated and re-hosted by +Coinbase, so the URL is stable and safe to render directly in clients. Omitted when the +provider did not supply an icon, when the supplied icon failed moderation, or when image +processing was unavailable at ingestion time. + */ + iconUrl?: Url; } /** @@ -4457,33 +5253,6 @@ export interface OnrampUserLimit { remaining: string; } -/** - * Date of birth. - */ -export interface DateOfBirth { - /** - * Day of birth (01-31). - * @minLength 2 - * @maxLength 2 - * @pattern ^[0-9]{2}$ - */ - day?: string; - /** - * Month of birth (01-12). - * @minLength 2 - * @maxLength 2 - * @pattern ^[0-9]{2}$ - */ - month?: string; - /** - * Year of birth (four digits). - * @minLength 4 - * @maxLength 4 - * @pattern ^[0-9]{4}$ - */ - year?: string; -} - /** * Populate the properties that correspond to the `fields` array from the user's `OnrampLimitUpgradeOption`. */ @@ -4506,9 +5275,211 @@ export interface OnrampLimitUpgradeRequest { } /** - * Unauthorized. + * The ID of the Payment Method, which is a UUID prefixed by the string `paymentMethod_`. + * @pattern ^paymentMethod_[a-f0-9\-]{36}$ */ -export type UnauthorizedErrorResponse = Error; +export type PaymentMethodId = string; + +/** + * Common properties shared by all payment method types. + */ +export interface PaymentMethodBase { + paymentMethodId: PaymentMethodId; + /** Whether the payment method is active and can be used in transfers. A payment method may be inactive due to verification requirements or entity-level restrictions. */ + active: boolean; + /** The timestamp when the payment method was created. */ + createdAt: string; + /** The timestamp when the payment method was last updated. */ + updatedAt: string; +} + +/** + * Details specific to Fedwire (domestic USD wire) payment methods. + */ +export interface FedwireDetails { + /** The asset for this payment method. Always `usd` for Fedwire. */ + asset: string; + /** The name of the bank. */ + bankName: string; + /** + * The last 4 digits of the bank account number. + * @pattern ^[0-9]{4}$ + */ + accountLast4: string; + /** + * The ABA routing number of the bank. + * @pattern ^[0-9]{9}$ + */ + routingNumber: string; +} + +/** + * The payment rail for this payment method. + */ +export type FedwirePaymentMethodAllOfPaymentRail = + (typeof FedwirePaymentMethodAllOfPaymentRail)[keyof typeof FedwirePaymentMethodAllOfPaymentRail]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const FedwirePaymentMethodAllOfPaymentRail = { + fedwire: "fedwire", +} as const; + +export type FedwirePaymentMethodAllOf = { + /** The payment rail for this payment method. */ + paymentRail: FedwirePaymentMethodAllOfPaymentRail; + /** Fedwire (domestic USD wire) details. */ + fedwire: FedwireDetails; +}; + +export type FedwirePaymentMethodPaymentRail = + (typeof FedwirePaymentMethodPaymentRail)[keyof typeof FedwirePaymentMethodPaymentRail]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const FedwirePaymentMethodPaymentRail = { + fedwire: "fedwire", +} as const; + +/** + * A Fedwire (domestic USD wire) payment method linked to your entity. + */ +export type FedwirePaymentMethod = PaymentMethodBase & + FedwirePaymentMethodAllOf & { + paymentRail: FedwirePaymentMethodPaymentRail; + }; + +/** + * Details specific to SWIFT (international wire) payment methods. + */ +export interface SwiftDetails { + /** The asset for this payment method (e.g., `eur`, `gbp`). */ + asset: string; + /** The name of the bank. */ + bankName: string; + /** + * The last 4 characters of the account identifier. For IBAN-based accounts (e.g., EU), this is the last 4 characters of the IBAN. For account number-based accounts (e.g., US), this is the last 4 digits of the account number. + * @pattern ^[A-Z0-9]{4}$ + */ + accountLast4: string; + /** + * Deprecated: use `accountLast4` instead. The last 4 characters of the account identifier. + * @deprecated + * @pattern ^[A-Z0-9]{4}$ + */ + ibanLast4?: string; + /** + * The Bank Identifier Code (BIC) / SWIFT code. + * @pattern ^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$ + */ + bic: string; +} + +/** + * The payment rail for this payment method. + */ +export type SwiftPaymentMethodAllOfPaymentRail = + (typeof SwiftPaymentMethodAllOfPaymentRail)[keyof typeof SwiftPaymentMethodAllOfPaymentRail]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const SwiftPaymentMethodAllOfPaymentRail = { + swift: "swift", +} as const; + +export type SwiftPaymentMethodAllOf = { + /** The payment rail for this payment method. */ + paymentRail: SwiftPaymentMethodAllOfPaymentRail; + /** SWIFT (international wire) details. */ + swift: SwiftDetails; +}; + +export type SwiftPaymentMethodPaymentRail = + (typeof SwiftPaymentMethodPaymentRail)[keyof typeof SwiftPaymentMethodPaymentRail]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const SwiftPaymentMethodPaymentRail = { + swift: "swift", +} as const; + +/** + * A SWIFT (international wire) payment method linked to your entity. + */ +export type SwiftPaymentMethod = PaymentMethodBase & + SwiftPaymentMethodAllOf & { + paymentRail: SwiftPaymentMethodPaymentRail; + }; + +/** + * Details specific to SEPA (Single Euro Payments Area) payment methods. + */ +export interface SepaDetails { + /** The asset for this payment method. Always `eur` for SEPA. */ + asset: string; + /** The name of the bank. */ + bankName: string; + /** + * The last 4 characters of the IBAN. + * @pattern ^[A-Z0-9]{4}$ + */ + ibanLast4: string; + /** + * The Bank Identifier Code (BIC) / SWIFT code. + * @pattern ^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$ + */ + bic: string; +} + +/** + * The payment rail for this payment method. + */ +export type SepaPaymentMethodAllOfPaymentRail = + (typeof SepaPaymentMethodAllOfPaymentRail)[keyof typeof SepaPaymentMethodAllOfPaymentRail]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const SepaPaymentMethodAllOfPaymentRail = { + sepa: "sepa", +} as const; + +export type SepaPaymentMethodAllOf = { + /** The payment rail for this payment method. */ + paymentRail: SepaPaymentMethodAllOfPaymentRail; + /** SEPA (Single Euro Payments Area) details. */ + sepa: SepaDetails; +}; + +export type SepaPaymentMethodPaymentRail = + (typeof SepaPaymentMethodPaymentRail)[keyof typeof SepaPaymentMethodPaymentRail]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const SepaPaymentMethodPaymentRail = { + sepa: "sepa", +} as const; + +/** + * A SEPA (Single Euro Payments Area) payment method linked to your entity. + */ +export type SepaPaymentMethod = PaymentMethodBase & + SepaPaymentMethodAllOf & { + paymentRail: SepaPaymentMethodPaymentRail; + }; + +/** + * A payment method linked to your entity. Payment methods represent external financial instruments that can be used as a target for transfers. + +The `paymentRail` field indicates which type-specific details object is present. Type-specific fields are nested under a key matching the rail name (e.g., `fedwire`, `swift`). + */ +export type PaymentMethodsPaymentMethod = + | FedwirePaymentMethod + | SwiftPaymentMethod + | SepaPaymentMethod; + +/** + * Idempotency key conflict. + */ +export type IdempotencyErrorResponse = Error; + +/** + * The endpoint cannot serve the request right now, either because the API is in an unintended outage (`service_unavailable` — dependency failure, deploy issue) or because an operator has intentionally disabled this specific endpoint via a kill switch (`endpoint_unavailable`). Clients should dispatch on `errorType`: `service_unavailable` is typically transient and safe to retry, while `endpoint_unavailable` may persist until an operator re-enables the endpoint. + */ +export type EndpointUnavailableErrorResponse = Error; /** * Internal server error. @@ -4525,15 +5496,20 @@ export type BadGatewayErrorResponse = Error; */ export type ServiceUnavailableErrorResponse = Error; +/** + * Unauthorized. + */ +export type UnauthorizedErrorResponse = Error; + /** * A payment method is required to complete this operation. */ export type PaymentMethodRequiredErrorResponse = Error; /** - * Idempotency key conflict. + * The request was rejected due to a delegation issue. The errorType field indicates the specific reason. */ -export type IdempotencyErrorResponse = Error; +export type DelegationForbiddenErrorResponse = Error; /** * The resource already exists. @@ -4630,12 +5606,14 @@ export type X402SupportedPaymentKindsResponseResponse = { export type RateLimitExceededResponse = Error; /** - * A JWT signed using your Wallet Secret, encoded in base64. Refer to the -[Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) -section of our Authentication docs for more details on how to generate your Wallet Token. + * The number of resources to return per page. + */ +export type PageSizeParameter = number; +/** + * The token for the next page of resources, if any. */ -export type XWalletAuthParameter = string; +export type PageTokenParameter = string; /** * An optional string request header for making requests safely retryable. @@ -4645,6 +5623,14 @@ Refer to our [Idempotency docs](https://docs.cdp.coinbase.com/api-reference/v2/i */ export type IdempotencyKeyParameter = string; +/** + * A JWT signed using your Wallet Secret, encoded in base64. Refer to the +[Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) +section of our Authentication docs for more details on how to generate your Wallet Token. + + */ +export type XWalletAuthParameter = string; + /** * A JWT signed using your Wallet Secret, encoded in base64. Refer to the [Generate Wallet Token](https://docs.cdp.coinbase.com/api-reference/v2/authentication#2-generate-wallet-token) @@ -4666,15 +5652,149 @@ export type XDeveloperAuthParameter = string; */ export type ProjectIDOptionalParameter = string; -/** - * The number of resources to return per page. - */ -export type PageSizeParameter = number; +export type ListFoundationAccountsParams = { + /** + * The number of resources to return per page. + */ + pageSize?: PageSizeParameter; + /** + * The token for the next page of resources, if any. + */ + pageToken?: PageTokenParameter; + /** + * Filter accounts by account type. When omitted, accounts of any type are returned. Combined with `owner` using AND. + */ + type?: AccountType; +}; -/** - * The token for the next page of resources, if any. - */ -export type PageTokenParameter = string; +export type ListFoundationAccounts200AllOf = { + /** The list of accounts. */ + accounts: Account[]; +}; + +export type ListFoundationAccounts200 = ListFoundationAccounts200AllOf & ListResponse; + +export type ListBalancesParams = { + /** + * The number of resources to return per page. + */ + pageSize?: PageSizeParameter; + /** + * The token for the next page of resources, if any. + */ + pageToken?: PageTokenParameter; +}; + +export type ListBalances200 = Balances & ListResponse; + +export type ListDepositDestinationsParams = { + /** + * Filter deposit destinations by account ID. + */ + accountId?: AccountId; + /** + * The cryptocurrency address to filter by. Format depends on the network (e.g., 0x-prefixed for EVM networks, base58 for Solana). + */ + address?: string; + /** + * Filter deposit destinations by type. + */ + type?: DepositDestinationType; + /** + * The blockchain network to filter by (e.g., base, ethereum). Only applies to crypto deposit destinations. + */ + network?: string; + /** + * The number of resources to return per page. + */ + pageSize?: PageSizeParameter; + /** + * The token for the next page of resources, if any. + */ + pageToken?: PageTokenParameter; +}; + +export type ListDepositDestinations200AllOf = { + /** The list of deposit destinations. */ + depositDestinations: DepositDestination[]; +}; + +export type ListDepositDestinations200 = ListDepositDestinations200AllOf & ListResponse; + +export type ListTransfersParams = { + /** + * Filter transfers by status. Useful for building dashboards, monitoring active transfers, or finding transfers needing action. + */ + status?: TransferStatus; + /** + * Filter transfers by account ID. Returns transfers where the specified account is either the source or target (OR semantics). Cannot be combined with `sourceAccountId` or `targetAccountId`. + */ + accountId?: AccountId; + /** + * Filter transfers by source account ID. Returns only transfers where the specified account is the source. Cannot be combined with `accountId`. + */ + sourceAccountId?: AccountId; + /** + * Filter transfers by target account ID. Returns only transfers where the specified account is the target. Cannot be combined with `accountId`. + */ + targetAccountId?: AccountId; + /** + * Filter transfers to those created at or after this datetime (inclusive). ISO 8601 format. + */ + createdAfter?: string; + /** + * Filter transfers to those created at or before this datetime (inclusive). ISO 8601 format. + */ + createdBefore?: string; + /** + * Filter transfers to those updated at or after this datetime (inclusive). ISO 8601 format. Useful for incremental sync — poll for transfers that changed state since your last check. + */ + updatedAfter?: string; + /** + * Filter transfers to those updated at or before this datetime (inclusive). ISO 8601 format. + */ + updatedBefore?: string; + /** + * Filter transfers by source asset symbol (e.g., `usd`, `usdc`). + */ + sourceAsset?: string; + /** + * Filter transfers by target asset symbol (e.g., `usdc`, `eth`). + */ + targetAsset?: string; + /** + * Filter transfers by the on-chain address of the source. + */ + sourceAddress?: BlockchainAddress; + /** + * Filter transfers by the on-chain destination address of the target. + */ + targetAddress?: BlockchainAddress; + /** + * Filter transfers by the email address of the target recipient. + */ + targetEmail?: string; + /** + * Filter to a specific transfer by ID. When provided, returns only the matching transfer and bypasses pagination. + * @pattern ^transfer_[a-f0-9\-]{36}$ + */ + transferId?: string; + /** + * The number of resources to return per page. + */ + pageSize?: PageSizeParameter; + /** + * The token for the next page of resources, if any. + */ + pageToken?: PageTokenParameter; +}; + +export type ListTransfers200AllOf = { + /** The list of transfers. */ + transfers: Transfer[]; +}; + +export type ListTransfers200 = ListTransfers200AllOf & ListResponse; /** * Configuration for creating an EVM account for the end user. @@ -6171,3 +7291,21 @@ export type GetOnrampUserLimits200 = { /** The list of limits applicable to the user. */ limits: OnrampUserLimit[]; }; + +export type ListPaymentMethodsParams = { + /** + * The number of resources to return per page. + */ + pageSize?: PageSizeParameter; + /** + * The token for the next page of resources, if any. + */ + pageToken?: PageTokenParameter; +}; + +export type ListPaymentMethods200AllOf = { + /** The list of payment methods. */ + paymentMethods: PaymentMethodsPaymentMethod[]; +}; + +export type ListPaymentMethods200 = ListPaymentMethods200AllOf & ListResponse; diff --git a/typescript/src/openapi-client/generated/deposit-destinations/deposit-destinations.ts b/typescript/src/openapi-client/generated/deposit-destinations/deposit-destinations.ts new file mode 100644 index 000000000..c8eae12a0 --- /dev/null +++ b/typescript/src/openapi-client/generated/deposit-destinations/deposit-destinations.ts @@ -0,0 +1,72 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * OpenAPI spec version: 2.0.0 + */ +import type { + CreateDepositDestinationRequest, + DepositDestination, + DepositDestinationId, + ListDepositDestinations200, + ListDepositDestinationsParams, +} from "../coinbaseDeveloperPlatformAPIs.schemas.js"; + +import { cdpApiClient } from "../../cdpApiClient.js"; + +type SecondParameter unknown> = Parameters[1]; + +/** + * List deposit destinations. You can optionally filter the results by type, account ID, network, or cryptocurrency address. Results are sorted by creation date in descending order (newest first). + * @summary List deposit destinations + */ +export const listDepositDestinations = ( + params?: ListDepositDestinationsParams, + options?: SecondParameter>, +) => { + return cdpApiClient( + { url: `/v2/deposit-destinations`, method: "GET", params }, + options, + ); +}; +/** + * Create a new deposit destination for an account. A deposit destination is a cryptocurrency address that can be used to receive funds. The address will be generated for the specified network. + * @summary Create deposit destination + */ +export const createDepositDestination = ( + createDepositDestinationRequest: CreateDepositDestinationRequest, + options?: SecondParameter>, +) => { + return cdpApiClient( + { + url: `/v2/deposit-destinations`, + method: "POST", + headers: { "Content-Type": "application/json" }, + data: createDepositDestinationRequest, + }, + options, + ); +}; +/** + * Get a specific deposit destination by its ID. + * @summary Get deposit destination + */ +export const getDepositDestinationById = ( + depositDestinationId: DepositDestinationId, + options?: SecondParameter>, +) => { + return cdpApiClient( + { url: `/v2/deposit-destinations/${depositDestinationId}`, method: "GET" }, + options, + ); +}; +export type ListDepositDestinationsResult = NonNullable< + Awaited> +>; +export type CreateDepositDestinationResult = NonNullable< + Awaited> +>; +export type GetDepositDestinationByIdResult = NonNullable< + Awaited> +>; diff --git a/typescript/src/openapi-client/generated/embedded-wallets/embedded-wallets.ts b/typescript/src/openapi-client/generated/embedded-wallets/embedded-wallets.ts index acfcade32..4881195e4 100644 --- a/typescript/src/openapi-client/generated/embedded-wallets/embedded-wallets.ts +++ b/typescript/src/openapi-client/generated/embedded-wallets/embedded-wallets.ts @@ -62,7 +62,7 @@ type SecondParameter unknown> = Parameters[1]; The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. - * @summary Sign a transaction with end user EVM account + * @summary Sign transaction via end user EVM account */ export const signEvmTransactionWithEndUserAccount = ( userId: string, @@ -108,7 +108,7 @@ The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com - `value` *(Optional)*: The amount of ETH, in wei, to send with the transaction. - `data` *(Optional)*: The data to send with the transaction; only used for contract calls. - `accessList` *(Optional)*: The access list to use for the transaction. - * @summary Send a transaction with end user EVM account + * @summary Send transaction via end user EVM account */ export const sendEvmTransactionWithEndUserAccount = ( userId: string, @@ -155,7 +155,7 @@ export const sendEvmAssetWithEndUserAccount = ( * Signs an [EIP-191](https://eips.ethereum.org/EIPS/eip-191) message with the given end user EVM account. Per the specification, the message in the request body is prepended with `0x19 <0x45 (E)> ` before being signed. - * @summary Sign an EIP-191 message with end user EVM account + * @summary Sign EIP-191 message via end user EVM account */ export const signEvmMessageWithEndUserAccount = ( userId: string, @@ -176,7 +176,7 @@ export const signEvmMessageWithEndUserAccount = ( }; /** * Signs [EIP-712](https://eips.ethereum.org/EIPS/eip-712) typed data with the given end user EVM account. - * @summary Sign EIP-712 typed data with end user EVM account + * @summary Sign EIP-712 typed data via end user EVM account */ export const signEvmTypedDataWithEndUserAccount = ( userId: string, @@ -234,7 +234,7 @@ export const revokeDelegationForEndUser = ( * Creates an account-scoped delegation that allows a developer to sign on behalf of an end user for a single blockchain account (identified by its address) for the specified duration. The end user must be authenticated to authorize this delegation. Multiple account-scoped delegations may exist concurrently for a single end user (one per canonical account address). Account-scoped and user-scoped delegations cannot coexist for the same user. When the address corresponds to an EVM Smart Account, the delegation is scoped to the Smart Account's owner EOA rather than the Smart Account address itself. This means `/address/{smartAccountAddress}/delegation` and `/address/{ownerEoaAddress}/delegation` resolve to the same delegation, and the 409 `account_scoped_delegation_active` error may be returned when creating via either address if one already exists for the canonical owner. - * @summary Create account-scoped delegation for an end user account + * @summary Create account-scoped delegation for end user */ export const createDelegationForEndUserAccount = ( userId: string, @@ -257,7 +257,7 @@ export const createDelegationForEndUserAccount = ( /** * Returns the active account-scoped delegation for the specified end user account, if one exists. Useful for showing delegation status in a UI. When the address corresponds to an EVM Smart Account, this returns the delegation for the Smart Account's owner EOA. - * @summary Get account-scoped delegation for an end user account + * @summary Get account-scoped delegation for end user */ export const getDelegationForEndUserAccount = ( userId: string, @@ -277,7 +277,7 @@ export const getDelegationForEndUserAccount = ( /** * Revokes the active account-scoped delegation for the specified end user account. Other account-scoped delegations for the same user are unaffected. This operation can be performed by the end user themselves or by a developer using their API key. When the address corresponds to an EVM Smart Account, this revokes the delegation for the Smart Account's owner EOA. - * @summary Revoke account-scoped delegation for an end user account + * @summary Revoke account-scoped delegation for end user */ export const revokeDelegationForEndUserAccount = ( userId: string, @@ -328,7 +328,7 @@ export const createEvmEip7702DelegationWithEndUserAccount = ( }; /** * Prepares, signs, and sends a user operation for an end user's Smart Account. - * @summary Send a user operation for end user Smart Account + * @summary Send user operation for end user Smart Account */ export const sendUserOperationWithEndUserAccount = ( userId: string, @@ -351,7 +351,7 @@ export const sendUserOperationWithEndUserAccount = ( /** * Signs an arbitrary Base64 encoded message with the given Solana account. **WARNING:** Never sign a message that you didn't generate as it may put your funds at risk. - * @summary Sign a Base64 encoded message + * @summary Sign Base64-encoded message */ export const signSolanaMessageWithEndUserAccount = ( userId: string, @@ -378,7 +378,7 @@ The following transaction types are supported: * [Legacy transactions](https://solana-labs.github.io/solana-web3.js/classes/Transaction.html) * [Versioned transactions](https://solana-labs.github.io/solana-web3.js/classes/VersionedTransaction.html) The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. - * @summary Sign a transaction with end user Solana account + * @summary Sign transaction via end user Solana account */ export const signSolanaTransactionWithEndUserAccount = ( userId: string, @@ -412,7 +412,7 @@ The following Solana networks are supported: * `solana` - Solana Mainnet * `solana-devnet` - Solana Devnet The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. - * @summary Send a transaction with end user Solana account + * @summary Send transaction via end user Solana account */ export const sendSolanaTransactionWithEndUserAccount = ( userId: string, diff --git a/typescript/src/openapi-client/generated/end-user-accounts/end-user-accounts.ts b/typescript/src/openapi-client/generated/end-user-accounts/end-user-accounts.ts index 1016ab126..6d599e928 100644 --- a/typescript/src/openapi-client/generated/end-user-accounts/end-user-accounts.ts +++ b/typescript/src/openapi-client/generated/end-user-accounts/end-user-accounts.ts @@ -29,7 +29,7 @@ type SecondParameter unknown> = Parameters[1]; /** * Creates an end user. An end user is an entity that can own CDP EVM accounts, EVM smart accounts, and/or Solana accounts. 1 or more authentication methods must be associated with an end user. By default, no accounts are created unless the optional `evmAccount` and/or `solanaAccount` fields are provided. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. - * @summary Create an end user + * @summary Create end user */ export const createEndUser = ( createEndUserBody: CreateEndUserBody, @@ -80,7 +80,7 @@ export const validateEndUserAccessToken = ( * Gets an end user by ID. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. - * @summary Get an end user + * @summary Get end user */ export const getEndUser = ( userId: string, @@ -118,7 +118,7 @@ export const lookupEndUser = ( /** * Adds a new EVM EOA account to an existing end user. End users can have up to 10 EVM accounts. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. - * @summary Add an EVM account to an end user + * @summary Add EVM account to end user */ export const addEndUserEvmAccount = ( userId: string, @@ -138,7 +138,7 @@ export const addEndUserEvmAccount = ( /** * Creates an EVM smart account for an existing end user. The backend will create a new EVM EOA account to serve as the owner of the smart account. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. - * @summary Add an EVM smart account to an end user + * @summary Add EVM smart account to end user */ export const addEndUserEvmSmartAccount = ( userId: string, @@ -158,7 +158,7 @@ export const addEndUserEvmSmartAccount = ( /** * Adds a new Solana account to an existing end user. End users can have up to 10 Solana accounts. This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. - * @summary Add a Solana account to an end user + * @summary Add Solana account to end user */ export const addEndUserSolanaAccount = ( userId: string, @@ -179,7 +179,7 @@ export const addEndUserSolanaAccount = ( * Imports an existing private key for an end user into the developer's CDP Project. The private key must be encrypted using the CDP SDK's encryption scheme before being sent to this endpoint. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. This endpoint allows developers to import existing keys for their end users, supporting both EVM and Solana key types. The end user must have at least one authentication method configured. - * @summary Import a private key for an end user + * @summary Import end user private key */ export const importEndUser = ( importEndUserBody: ImportEndUserBody, diff --git a/typescript/src/openapi-client/generated/evm-accounts/evm-accounts.ts b/typescript/src/openapi-client/generated/evm-accounts/evm-accounts.ts index c55af269a..118085c2f 100644 --- a/typescript/src/openapi-client/generated/evm-accounts/evm-accounts.ts +++ b/typescript/src/openapi-client/generated/evm-accounts/evm-accounts.ts @@ -51,7 +51,7 @@ export const listEvmAccounts = ( }; /** * Creates a new EVM account. - * @summary Create an EVM account + * @summary Create EVM account */ export const createEvmAccount = ( createEvmAccountBody?: CreateEvmAccountBody, @@ -69,7 +69,7 @@ export const createEvmAccount = ( }; /** * Gets an EVM account by its address. - * @summary Get an EVM account by address + * @summary Get EVM account by address */ export const getEvmAccount = ( address: string, @@ -79,7 +79,7 @@ export const getEvmAccount = ( }; /** * Updates an existing EVM account. Use this to update the account's name or account-level policy. - * @summary Update an EVM account + * @summary Update EVM account */ export const updateEvmAccount = ( address: string, @@ -98,7 +98,7 @@ export const updateEvmAccount = ( }; /** * Gets an EVM account by its name. - * @summary Get an EVM account by name + * @summary Get EVM account by name */ export const getEvmAccountByName = ( name: string, @@ -136,7 +136,7 @@ The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com - `value` *(Optional)*: The amount of ETH, in wei, to send with the transaction. - `data` *(Optional)*: The data to send with the transaction; only used for contract calls. - `accessList` *(Optional)*: The access list to use for the transaction. - * @summary Send a transaction + * @summary Send transaction */ export const sendEvmTransaction = ( address: string, @@ -158,7 +158,7 @@ export const sendEvmTransaction = ( The transaction should be serialized as a hex string using [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. - * @summary Sign a transaction + * @summary Sign transaction */ export const signEvmTransaction = ( address: string, @@ -177,7 +177,7 @@ export const signEvmTransaction = ( }; /** * Signs an arbitrary 32 byte hash with the given EVM account. - * @summary Sign a hash + * @summary Sign hash */ export const signEvmHash = ( address: string, @@ -198,7 +198,7 @@ export const signEvmHash = ( * Signs an [EIP-191](https://eips.ethereum.org/EIPS/eip-191) message with the given EVM account. Per the specification, the message in the request body is prepended with `0x19 <0x45 (E)> ` before being signed. - * @summary Sign an EIP-191 message + * @summary Sign EIP-191 message */ export const signEvmMessage = ( address: string, @@ -263,7 +263,7 @@ export const createEvmEip7702Delegation = ( }; /** * Returns the EIP-7702 delegation operation. Use the delegationOperationId returned by the Create EIP-7702 delegation endpoint to poll for operation completion. - * @summary Get EIP-7702 delegation operation for an operationID + * @summary Get EIP-7702 delegation operation by ID */ export const getEvmEip7702DelegationOperationById = ( delegationOperationId: string, @@ -276,7 +276,7 @@ export const getEvmEip7702DelegationOperationById = ( }; /** * Import an existing EVM account into the developer's CDP Project. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. - * @summary Import an EVM account + * @summary Import EVM account */ export const importEvmAccount = ( importEvmAccountBody: ImportEvmAccountBody, @@ -294,7 +294,7 @@ export const importEvmAccount = ( }; /** * Export an existing EVM account's private key. It is important to store the private key in a secure place after it's exported. - * @summary Export an EVM account + * @summary Export EVM account */ export const exportEvmAccount = ( address: string, @@ -313,7 +313,7 @@ export const exportEvmAccount = ( }; /** * Export an existing EVM account's private key by its name. It is important to store the private key in a secure place after it's exported. - * @summary Export an EVM account by name + * @summary Export EVM account by name */ export const exportEvmAccountByName = ( name: string, diff --git a/typescript/src/openapi-client/generated/evm-smart-accounts/evm-smart-accounts.ts b/typescript/src/openapi-client/generated/evm-smart-accounts/evm-smart-accounts.ts index 7e453b344..722983745 100644 --- a/typescript/src/openapi-client/generated/evm-smart-accounts/evm-smart-accounts.ts +++ b/typescript/src/openapi-client/generated/evm-smart-accounts/evm-smart-accounts.ts @@ -41,7 +41,7 @@ export const listEvmSmartAccounts = ( }; /** * Creates a new Smart Account. - * @summary Create a Smart Account + * @summary Create Smart Account */ export const createEvmSmartAccount = ( createEvmSmartAccountBody: CreateEvmSmartAccountBody, @@ -59,7 +59,7 @@ export const createEvmSmartAccount = ( }; /** * Gets a Smart Account by its name. - * @summary Get a Smart Account by name + * @summary Get Smart Account by name */ export const getEvmSmartAccountByName = ( name: string, @@ -72,7 +72,7 @@ export const getEvmSmartAccountByName = ( }; /** * Gets a Smart Account by its address. - * @summary Get a Smart Account by address + * @summary Get Smart Account by address */ export const getEvmSmartAccount = ( address: string, @@ -85,7 +85,7 @@ export const getEvmSmartAccount = ( }; /** * Updates an existing EVM smart account. Use this to update the smart account's name. - * @summary Update an EVM Smart Account + * @summary Update EVM Smart Account */ export const updateEvmSmartAccount = ( address: string, @@ -104,7 +104,7 @@ export const updateEvmSmartAccount = ( }; /** * Prepares a new user operation on a Smart Account for a specific network. - * @summary Prepare a user operation + * @summary Prepare user operation */ export const prepareUserOperation = ( address: string, @@ -123,7 +123,7 @@ export const prepareUserOperation = ( }; /** * Prepares, signs, and sends a user operation for an EVM Smart Account. This API can be used only if the owner on Smart Account is a CDP EVM Account. - * @summary Prepare and send a user operation for EVM Smart Account + * @summary Prepare and send user operation */ export const prepareAndSendUserOperation = ( address: string, @@ -142,7 +142,7 @@ export const prepareAndSendUserOperation = ( }; /** * Gets a user operation by its hash. - * @summary Get a user operation + * @summary Get user operation */ export const getUserOperation = ( address: string, @@ -159,7 +159,7 @@ export const getUserOperation = ( The payload to sign must be the `userOpHash` field of the user operation. This hash should be signed directly (not using `personal_sign` or EIP-191 message hashing). The signature must be 65 bytes in length, consisting of: - 32 bytes for the `r` value - 32 bytes for the `s` value - 1 byte for the `v` value (must be 27 or 28) If using the CDP Paymaster, the user operation must be signed and sent within 2 minutes of being prepared. - * @summary Send a user operation + * @summary Send user operation */ export const sendUserOperation = ( address: string, @@ -179,7 +179,7 @@ export const sendUserOperation = ( }; /** * Creates a spend permission for the given smart account address. - * @summary Create a spend permission + * @summary Create spend permission */ export const createSpendPermission = ( address: string, @@ -212,7 +212,7 @@ export const listSpendPermissions = ( }; /** * Revokes an existing spend permission. - * @summary Revoke a spend permission + * @summary Revoke spend permission */ export const revokeSpendPermission = ( address: string, diff --git a/typescript/src/openapi-client/generated/evm-swaps/evm-swaps.ts b/typescript/src/openapi-client/generated/evm-swaps/evm-swaps.ts index 0befa1b8a..a39695e44 100644 --- a/typescript/src/openapi-client/generated/evm-swaps/evm-swaps.ts +++ b/typescript/src/openapi-client/generated/evm-swaps/evm-swaps.ts @@ -18,7 +18,7 @@ type SecondParameter unknown> = Parameters[1]; /** * Get a price estimate for a swap between two tokens on an EVM network. - * @summary Get a price estimate for a swap + * @summary Get swap price estimate */ export const getEvmSwapPrice = ( params: GetEvmSwapPriceParams, @@ -31,7 +31,7 @@ export const getEvmSwapPrice = ( }; /** * Create a swap quote, which includes the payload to sign as well as the transaction data needed to execute the swap. The developer is responsible for signing the payload and submitting the transaction to the network in order to execute the swap. - * @summary Create a swap quote + * @summary Create swap quote */ export const createEvmSwapQuote = ( createEvmSwapQuoteBody: CreateEvmSwapQuoteBody, diff --git a/typescript/src/openapi-client/generated/payment-methods/payment-methods.ts b/typescript/src/openapi-client/generated/payment-methods/payment-methods.ts new file mode 100644 index 000000000..f82ba859d --- /dev/null +++ b/typescript/src/openapi-client/generated/payment-methods/payment-methods.ts @@ -0,0 +1,53 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Coinbase Developer Platform APIs + * The Coinbase Developer Platform APIs - leading the world's transition onchain. + * OpenAPI spec version: 2.0.0 + */ +import type { + ListPaymentMethods200, + ListPaymentMethodsParams, + PaymentMethodId, + PaymentMethodsPaymentMethod, +} from "../coinbaseDeveloperPlatformAPIs.schemas.js"; + +import { cdpApiClient } from "../../cdpApiClient.js"; + +type SecondParameter unknown> = Parameters[1]; + +/** + * List payment methods linked to your entity. Payment methods represent external financial instruments that can be used as a target for transfers. The list will not include disabled or deleted payment methods. + +**Currently Supported Types:** +- `fedwire`: Domestic USD wire transfers +- `swift`: International wire transfers +- `sepa`: SEPA EUR transfers + +**Note:** Payment methods are created and verified through your linked CDP entity. Currently, fetching payment methods is only supported for Prime investment vehicles linked to CDP. + * @summary List payment methods + */ +export const listPaymentMethods = ( + params?: ListPaymentMethodsParams, + options?: SecondParameter>, +) => { + return cdpApiClient( + { url: `/v2/payment-methods`, method: "GET", params }, + options, + ); +}; +/** + * Get details of a specific payment method by its ID. Returns 404 if the payment method is not found or not owned by the requesting entity. + * @summary Get payment method + */ +export const getPaymentMethod = ( + paymentMethodId: PaymentMethodId, + options?: SecondParameter>, +) => { + return cdpApiClient( + { url: `/v2/payment-methods/${paymentMethodId}`, method: "GET" }, + options, + ); +}; +export type ListPaymentMethodsResult = NonNullable>>; +export type GetPaymentMethodResult = NonNullable>>; diff --git a/typescript/src/openapi-client/generated/policy-engine/policy-engine.ts b/typescript/src/openapi-client/generated/policy-engine/policy-engine.ts index 220041ddb..30c020aad 100644 --- a/typescript/src/openapi-client/generated/policy-engine/policy-engine.ts +++ b/typescript/src/openapi-client/generated/policy-engine/policy-engine.ts @@ -33,7 +33,7 @@ export const listPolicies = ( }; /** * Create a policy that can be used to govern the behavior of accounts. - * @summary Create a policy + * @summary Create policy */ export const createPolicy = ( createPolicyBody: CreatePolicyBody, @@ -51,7 +51,7 @@ export const createPolicy = ( }; /** * Get a policy by its ID. - * @summary Get a policy by ID + * @summary Get policy by ID */ export const getPolicyById = ( policyId: string, @@ -64,7 +64,7 @@ export const getPolicyById = ( }; /** * Delete a policy by its ID. This will have the effect of removing the policy from all accounts that are currently using it. - * @summary Delete a policy + * @summary Delete policy */ export const deletePolicy = ( policyId: string, @@ -77,7 +77,7 @@ export const deletePolicy = ( }; /** * Updates a policy by its ID. This will have the effect of applying the updated policy to all accounts that are currently using it. - * @summary Update a policy + * @summary Update policy */ export const updatePolicy = ( policyId: string, diff --git a/typescript/src/openapi-client/generated/solana-accounts/solana-accounts.ts b/typescript/src/openapi-client/generated/solana-accounts/solana-accounts.ts index efdb5cadc..6d00a925a 100644 --- a/typescript/src/openapi-client/generated/solana-accounts/solana-accounts.ts +++ b/typescript/src/openapi-client/generated/solana-accounts/solana-accounts.ts @@ -33,7 +33,7 @@ type SecondParameter unknown> = Parameters[1]; The response is paginated, and by default, returns 20 accounts per page. If a name is provided, the response will contain only the account with that name. - * @summary List Solana accounts or get account by name + * @summary List Solana accounts */ export const listSolanaAccounts = ( params?: ListSolanaAccountsParams, @@ -46,7 +46,7 @@ export const listSolanaAccounts = ( }; /** * Creates a new Solana account. - * @summary Create a Solana account + * @summary Create Solana account */ export const createSolanaAccount = ( createSolanaAccountBody?: CreateSolanaAccountBody, @@ -64,7 +64,7 @@ export const createSolanaAccount = ( }; /** * Gets a Solana account by its address. - * @summary Get a Solana account by address + * @summary Get Solana account by address */ export const getSolanaAccount = ( address: string, @@ -77,7 +77,7 @@ export const getSolanaAccount = ( }; /** * Updates an existing Solana account. Use this to update the account's name or account-level policy. - * @summary Update a Solana account + * @summary Update Solana account */ export const updateSolanaAccount = ( address: string, @@ -96,7 +96,7 @@ export const updateSolanaAccount = ( }; /** * Gets a Solana account by its name. - * @summary Get a Solana account by name + * @summary Get Solana account by name */ export const getSolanaAccountByName = ( name: string, @@ -109,7 +109,7 @@ export const getSolanaAccountByName = ( }; /** * Import an existing Solana account into the developer's CDP Project. This API should be called from the [CDP SDK](https://github.com/coinbase/cdp-sdk) to ensure that the associated private key is properly encrypted. - * @summary Import a Solana account + * @summary Import Solana account */ export const importSolanaAccount = ( importSolanaAccountBody: ImportSolanaAccountBody, @@ -127,7 +127,7 @@ export const importSolanaAccount = ( }; /** * Export an existing Solana account's private key. It is important to store the private key in a secure place after it's exported. - * @summary Export an Solana account + * @summary Export Solana account */ export const exportSolanaAccount = ( address: string, @@ -146,7 +146,7 @@ export const exportSolanaAccount = ( }; /** * Export an existing Solana account's private key by its name. It is important to store the private key in a secure place after it's exported. - * @summary Export a Solana account by name + * @summary Export Solana account by name */ export const exportSolanaAccountByName = ( name: string, @@ -174,7 +174,7 @@ The following transaction types are supported: * [Versioned transactions](https://solana-labs.github.io/solana-web3.js/classes/VersionedTransaction.html) The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. - * @summary Sign a transaction + * @summary Sign transaction */ export const signSolanaTransaction = ( address: string, @@ -195,7 +195,7 @@ export const signSolanaTransaction = ( * Signs an arbitrary message with the given Solana account. **WARNING:** Never sign a message that you didn't generate, as it can be an arbitrary transaction. For example, it might send all of your funds to an attacker. - * @summary Sign a message + * @summary Sign message */ export const signSolanaMessage = ( address: string, @@ -234,7 +234,7 @@ The following Solana networks are supported: * `solana-devnet` - Solana Devnet The developer is responsible for ensuring that the unsigned transaction is valid, as the API will not validate the transaction. - * @summary Send a Solana transaction + * @summary Send Solana transaction */ export const sendSolanaTransaction = ( sendSolanaTransactionBody: SendSolanaTransactionBody, diff --git a/typescript/src/openapi-client/generated/sql-api/sql-api.ts b/typescript/src/openapi-client/generated/sql-api/sql-api.ts index 46a67a405..a5b066e71 100644 --- a/typescript/src/openapi-client/generated/sql-api/sql-api.ts +++ b/typescript/src/openapi-client/generated/sql-api/sql-api.ts @@ -95,7 +95,7 @@ export const getSQLGrammar = (options?: SecondParameter unknown> = Parameters[1]; + +/** + * Create a new transfer to move funds from a source to a target. +All transfers first transition to `quoted`. If `execute: false`, the transfer stays quoted until you call `/v2/transfers/{transferId}/execute`. +If `execute: true`, quoted status emits momentarily before the transfer moves to `processing`, where execution proceeds. Subscribe to the transfers webhook to follow progress in real time instead of polling. + * @summary Create transfer + */ +export const createTransfer = ( + transferRequest: TransferRequest, + options?: SecondParameter>, +) => { + return cdpApiClient( + { + url: `/v2/transfers`, + method: "POST", + headers: { "Content-Type": "application/json" }, + data: transferRequest, + }, + options, + ); +}; +/** + * List transfers for your organization. Use this to view and monitor your transfer activity. + +**Status Filtering**: Filter by specific status to efficiently manage transfers: +* `?status=processing` - Monitor active transfers. +* `?status=quoted` - Find transfers awaiting execution. +* `?status=failed` - Review failed transfers for troubleshooting. +* `?status=completed` - Find completed transfers. + +**Account Filtering**: Filter by account ID to find transfers involving a specific account: +* `?accountId=` - All transfers where the account is either source or target (OR semantics). +* `?sourceAccountId=` - Only transfers where the account is the source (outbound). +* `?targetAccountId=` - Only transfers where the account is the target (inbound). +Providing `accountId` together with `sourceAccountId` or `targetAccountId` is a validation error and returns HTTP 400. + +**Date Range Filtering**: Filter by creation or last-updated time for reconciliation: +* `?createdAfter=2026-01-01T00:00:00Z&createdBefore=2026-01-31T23:59:59Z` - Transfers created within a date range. +* `?updatedAfter=2026-01-01T00:00:00Z` - Transfers updated since a given time. Useful for incremental sync. + +**Asset Filtering**: Filter by source or target asset symbol: +* `?sourceAsset=usd` - Transfers funded from a USD account. +* `?targetAsset=usdc` - Transfers delivering USDC to the target. + +**Other Filters**: +* `?sourceAddress=0x...` - Transfers from a specific on-chain source address. +* `?targetAddress=0x...` - Transfers to a specific on-chain destination address. +* `?targetEmail=user@example.com` - Transfers to a specific email recipient. +* `?transferId=transfer_...` - Look up a single transfer by ID; bypasses pagination. + * @summary List transfers + */ +export const listTransfers = ( + params?: ListTransfersParams, + options?: SecondParameter>, +) => { + return cdpApiClient({ url: `/v2/transfers`, method: "GET", params }, options); +}; +/** + * Get a transfer by its ID. + * @summary Get transfer + */ +export const getTransferById = ( + transferId: string, + options?: SecondParameter>, +) => { + return cdpApiClient({ url: `/v2/transfers/${transferId}`, method: "GET" }, options); +}; +/** + * Executes a transfer which was created using the Create a transfer endpoint. + * @summary Execute transfer + */ +export const executeFundTransfer = ( + transferId: string, + options?: SecondParameter>, +) => { + return cdpApiClient( + { url: `/v2/transfers/${transferId}/execute`, method: "POST" }, + options, + ); +}; +/** + * Submit travel rule information for a deposit transfer held pending compliance review. + +Required fields vary by jurisdiction and may include originator name, address, date of birth, personal ID, and VASP information. + +If the submitted information satisfies all jurisdictional requirements, `status` will be `completed` and the transfer will proceed. Otherwise, `status` will be `incomplete` and `missingFields` will indicate which fields still need to be provided. + * @summary Submit deposit travel rule information + */ +export const submitDepositTravelRule = ( + transferId: string, + depositTravelRuleRequest: DepositTravelRuleRequest, + options?: SecondParameter>, +) => { + return cdpApiClient( + { + url: `/v2/transfers/${transferId}/travel-rule`, + method: "POST", + headers: { "Content-Type": "application/json" }, + data: depositTravelRuleRequest, + }, + options, + ); +}; +export type CreateTransferResult = NonNullable>>; +export type ListTransfersResult = NonNullable>>; +export type GetTransferByIdResult = NonNullable>>; +export type ExecuteFundTransferResult = NonNullable< + Awaited> +>; +export type SubmitDepositTravelRuleResult = NonNullable< + Awaited> +>; diff --git a/typescript/src/openapi-client/generated/webhooks/webhooks.ts b/typescript/src/openapi-client/generated/webhooks/webhooks.ts index 28dc9c1e0..4b486b3d7 100644 --- a/typescript/src/openapi-client/generated/webhooks/webhooks.ts +++ b/typescript/src/openapi-client/generated/webhooks/webhooks.ts @@ -120,7 +120,7 @@ configuration, status, creation timestamp, and webhook signature secret. - Webhook signature secret for verification - Creation timestamp and status - * @summary Get webhook subscription details + * @summary Get webhook subscription */ export const getWebhookSubscription = ( subscriptionId: string, diff --git a/typescript/src/openapi-client/generated/x402-facilitator/x402-facilitator.ts b/typescript/src/openapi-client/generated/x402-facilitator/x402-facilitator.ts index 9ab0ddf8e..2c2400a15 100644 --- a/typescript/src/openapi-client/generated/x402-facilitator/x402-facilitator.ts +++ b/typescript/src/openapi-client/generated/x402-facilitator/x402-facilitator.ts @@ -27,7 +27,7 @@ type SecondParameter unknown> = Parameters[1]; /** * Verify an x402 protocol payment with a specific scheme and network. - * @summary Verify a payment + * @summary Verify payment */ export const verifyX402Payment = ( verifyX402PaymentBody: VerifyX402PaymentBody, @@ -45,7 +45,7 @@ export const verifyX402Payment = ( }; /** * Settle an x402 protocol payment with a specific scheme and network. - * @summary Settle a payment + * @summary Settle payment */ export const settleX402Payment = ( settleX402PaymentBody: SettleX402PaymentBody, @@ -77,7 +77,7 @@ export const supportedX402PaymentKinds = ( * Lists all active discovered x402 resources. This endpoint returns resources that have been discovered and cached by the x402 facilitator, including their payment requirements and metadata. The response is paginated, and by default, returns 100 items per page. - * @summary List discovered x402 resources + * @summary List x402 resources */ export const listX402DiscoveryResources = ( params?: ListX402DiscoveryResourcesParams, diff --git a/typescript/src/openapi-client/index.ts b/typescript/src/openapi-client/index.ts index b139f7aa1..08d1432fe 100644 --- a/typescript/src/openapi-client/index.ts +++ b/typescript/src/openapi-client/index.ts @@ -12,8 +12,15 @@ export * from "./generated/onchain-data/onchain-data.js"; export * from "./generated/end-user-accounts/end-user-accounts.js"; export * from "./generated/embedded-wallets/embedded-wallets.js"; export * from "./generated/x402-facilitator/x402-facilitator.js"; +export * from "./generated/sql-api/sql-api.js"; +export * from "./generated/accounts/accounts.js"; +export * from "./generated/deposit-destinations/deposit-destinations.js"; +export * from "./generated/transfers/transfers.js"; +export * from "./generated/payment-methods/payment-methods.js"; import { configure } from "./cdpApiClient.js"; +import * as accounts from "./generated/accounts/accounts.js"; +import * as depositDestinations from "./generated/deposit-destinations/deposit-destinations.js"; import * as embeddedWallets from "./generated/embedded-wallets/embedded-wallets.js"; import * as endUserAccounts from "./generated/end-user-accounts/end-user-accounts.js"; import * as evm from "./generated/evm-accounts/evm-accounts.js"; @@ -22,9 +29,11 @@ import * as evmSwaps from "./generated/evm-swaps/evm-swaps.js"; import * as evmTokenBalances from "./generated/evm-token-balances/evm-token-balances.js"; import * as faucets from "./generated/faucets/faucets.js"; import * as onchainData from "./generated/onchain-data/onchain-data.js"; +import * as paymentMethods from "./generated/payment-methods/payment-methods.js"; import * as policies from "./generated/policy-engine/policy-engine.js"; import * as solana from "./generated/solana-accounts/solana-accounts.js"; import * as solanaTokenBalances from "./generated/solana-token-balances/solana-token-balances.js"; +import * as transfers from "./generated/transfers/transfers.js"; import * as webhooks from "./generated/webhooks/webhooks.js"; export const CdpOpenApiClient = { @@ -40,6 +49,10 @@ export const CdpOpenApiClient = { ...policies, ...endUserAccounts, ...embeddedWallets, + ...accounts, + ...depositDestinations, + ...transfers, + ...paymentMethods, configure, }; @@ -61,4 +74,5 @@ export const OpenApiPoliciesMethods = { }; export type CdpOpenApiClientType = typeof CdpOpenApiClient; -export * from "./generated/sql-api/sql-api.js"; + +export { configure };